一个简单的基于注解的controller

来源:互联网 发布:江东是哪里 知乎 编辑:程序博客网 时间:2024/06/05 20:39
转载自:http://blog.csdn.net/liuyun1197628/article/details/22982749

低版本 的Spring MVC 创建一个 Controller 时,需要直接或间接地实现org.springframework.web.servlet.mvc.Controller 接口。一般情况下,我们是通过继承 SimpleFormController 或 MultiActionController 来定义自己的 Controller 的。

在定义 Controller 后,一个重要的事件是在 Spring MVC 的配置文件中通过 HandlerMapping 定义请求和控制器的映射关系,以便将两者关联起来。

来看一下基于注解的 Controller 是如何定义做到这一点的,下面是使用注解的 BbtForumController:
package com.baobaotao.web;import com.baobaotao.service.BbtForumService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.ModelAttribute;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import java.util.Collection;@Controller                   //<——①@RequestMapping("/forum.do")public class BbtForumController {    @Autowired    private BbtForumService bbtForumService;    @RequestMapping //<——②    public String listAllBoard() {        bbtForumService.getAllBoard();        System.out.println("call listAllBoard method.");        return "listBoard";    }}

       从上面代码中,我们可以看出 BbtForumController 和一般的类并没有区别,它没有实现任何特殊的接口,因而是一个地道的 POJO(简单的JAVA对象)。让这个 POJO 与众不同的魔棒就是 Spring MVC 的注解!

      在 ① 处使用了两个注解,分别是 @Controller 和 @RequestMapping。在“使用 Spring 2.5 基于注解驱动的 IoC”这篇文章里,笔者曾经指出过 @Controller、@Service 以及 @Repository 和 @Component 注解的作用是等价的:将一个类成为 Spring 容器的 Bean。

由于 Spring MVC 的 Controller 必须事先是一个 Bean,所以 @Controller 注解是不可缺少的。

         真正让 BbtForumController 具备 Spring MVC Controller 功能的是 @RequestMapping 这个注解。@RequestMapping 可以标注在类定义处,将 Controller 和特定请求关联起来;还可以标注在方法签名处,以便进一步对请求进行分流。在 ① 处,我们让 BbtForumController 关联“/forum.do”的请求,而 ② 处,我们具体地指定 listAllBoard() 方法来处理请求。所以在类声明处标注的 @RequestMapping 相当于让 POJO 实现了 Controller 接口,而在方法定义处的 @RequestMapping 相当于让 POJO 扩展 Spring 预定义的 Controller(如 SimpleFormController 等)。

       为了让基于注解的 Spring MVC 真正工作起来,需要在 Spring MVC 对应的 xxx-servlet.xml 配置文件中做一些手脚。在此之前,还是先来看一下 web.xml 的配置吧:


阅读全文
0 0