在 Spring Web 框架中,通常将控制器实现为实现
org.springframework.web.servlet.mvc.Controller
的类,例如:public class InventoryController implements Controller {
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 在此处理请求
}
- 此类将在应用程序的 Spring 上下文 XML 文件(通常为
appname-servlet.xml
)中定义: <bean name="/home.htm" class="springapp.web.InventoryController">
...
</bean>
然而,使用 Spring 注解可以无需实现
org.springframework.web.servlet.mvc.controller
,也无需在 XML 文件中定义 bean。- 要将控制器类更改为使用注解,该类需要用
@Controller
和@RequestMapping
注解进行标注,如下所示: @Controller
@RequestMapping("/home.htm")
public class InventoryController {
@RequestMapping(method=RequestMethod.GET)
public ModelAndView handleRequest() {
// 在此处理请求
}
}
- 注意,此方法不再需要与
org.springframework.web.servlet.mvc.Controller
中定义的签名相同,现在只需返回ModelAndView
实例。
- 要将控制器类更改为使用注解,该类需要用
重新定义控制器类后,可以从应用程序的上下文文件中删除 bean 定义。
- 要让 Spring 使用带注解的控制器,需要在应用程序的上下文文件中指定使用注解,通过在上下文文件中添加
<annotation-driven />
注解来实现: <?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xsi:schemaLocation="
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<annotation-driven />
...
</beans:beans>
- 要让 Spring 使用带注解的控制器,需要在应用程序的上下文文件中指定使用注解,通过在上下文文件中添加
- 来源:http://www.davidsalter.co.uk/1/post/2011/04/converting-a-spring-controller-into-a-controller.html
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。