将一个 Spring 控制器转换为一个 @Controller 需要注意的是,在 Spring 框架中,使用 @Controller 注解来标识一个类为控制器,用于处理 HTTP 请求和生成响应。如果原来的 Spring 控制器没有使用 @Control

  • 在 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>
  • 来源:http://www.davidsalter.co.uk/1/post/2011/04/converting-a-spring-controller-into-a-controller.html
阅读 8
0 条评论