在本教程中,我们向您展示如何使用@RequestMapping
开发基于Spring MVC注释的MultiActionController 。
在基于XML的MultiActionController中,您必须配置方法名称解析程序( InternalPathMethodNameResolver , PropertiesMethodNameResolver或ParameterMethodNameResolver )以将URL映射到特定的方法名称。 但是,有了注释支持,生活变得更加轻松,现在您可以将@RequestMapping注释用作方法名称解析器,该解析器用于将URL映射到特定方法。
注意
这个基于注释的示例是从最后一个基于 Spring MVC MultiActionController XML的示例转换而来的。 因此,请比较并找出不同之处。
要对其进行配置,请在方法名称上方使用映射URL定义@RequestMapping 。
package com.mkyong.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将以以下模式映射到方法名称:
- /customer/add.htm –> add()方法
- /customer/delete.htm –> delete()方法
- /customer/update.htm –> update()方法
- /customer/list.htm –> list()方法
注意
在Spring MVC中,此@RequestMapping
始终是最灵活和易于使用的映射机制。
下载源代码
下载它– SpringMVC-MultiActionController-Annotation-Example.zip (7KB)
翻译自: https://mkyong.com/spring-mvc/spring-mvc-multiactioncontroller-annotation-example/