Пример аннотации Spring MVC MultiActionController

Пример аннотации Spring MVC MultiActionController

В этом руководстве мы покажем вам, как разработатьMultiActionController на основе аннотаций Spring MVC, используя@RequestMapping.

В основанном на XML MultiActionController вам необходимо настроить преобразователь имени метода (InternalPathMethodNameResolver,PropertiesMethodNameResolver илиParameterMethodNameResolver) для сопоставления URL-адреса с конкретным именем метода. Но жизнь стала проще с поддержкой аннотаций, теперь вы можете использовать аннотацию@RequestMapping в качестве преобразователя имени метода, который используется для сопоставления URL-адреса с определенным методом.

Note
Этот пример на основе аннотаций преобразован из последнего Spring MVCMultiActionController XML-based example. Поэтому, пожалуйста, сравните и отметьте разные.

Чтобы настроить его, определите@RequestMapping с сопоставлением URL-адреса над именем метода.

package com.example.common.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class CustomerController{

    @RequestMapping("/customer/add.htm")
    public ModelAndView add(HttpServletRequest request,
        HttpServletResponse response) throws Exception {

        return new ModelAndView("CustomerAddView");

    }

    @RequestMapping("/customer/delete.htm")
    public ModelAndView delete(HttpServletRequest request,
        HttpServletResponse response) throws Exception {

        return new ModelAndView("CustomerDeleteView");

    }

    @RequestMapping("/customer/update.htm")
    public ModelAndView update(HttpServletRequest request,
        HttpServletResponse response) throws Exception {

        return new ModelAndView("CustomerUpdateView");

    }

    @RequestMapping("/customer/list.htm")
    public ModelAndView list(HttpServletRequest request,
        HttpServletResponse response) throws Exception {

        return new ModelAndView("CustomerListView");

    }
}

Теперь URL будет сопоставлен с именем метода в следующих шаблонах:

  1. /customer/add.htm –> add() method

  2. /customer/delete.htm –> delete() method

  3. /customer/update.htm –> update() method

  4. /customer/list.htm –> list() method

Note
В Spring MVC этот@RequestMapping всегда является наиболее гибким и простым в использовании механизмом сопоставления.

Скачать исходный код