一个简单的基于注解的Controller 使用过低版本SpringMVC的读者都知道:当创建一个Controller时,我们需要直接或间接地实现org.springframework.web.servlet.mvc.Controller接口。一般情况下,我们是通过继承SimpleFormController或MultiActionController来定义自己的Controller的。在定义Controller后,一个重要的事件是在SpringMVC的配置文件中通过HandlerMapping定义请求和控制器的映射关系,以便将两者关联起来。 来看一下基于注解的Controller是如何定义做到这一点的,下面是使用注解的BbtForumController: 清单1.BbtForumController.java packagecom.baobaotao.web; importcom.baobaotao.service.BbtForumService; importorg.springframework.beans.factory.annotation.Autowired; importorg.springframework.stereotype.Controller; importorg.springframework.web.bind.annotation.ModelAttribute; importorg.springframework.web.bind.annotation.RequestMapping; importorg.springframework.web.bind.annotation.RequestMethod; importjava.util.Collection; @Controller// SpringAnnotationMVCSample contextConfigLocation classpath:applicationContext.xml org.springframework.web.context.ContextLoaderListener annomvc org.springframework.web.servlet.DispatcherServlet 2 annomvc *.do web.xml中定义了一个名为annomvc的SpringMVC模块,按照SpringMVC的契约,需要在WEB-INF/annomvc-servlet.xml配置文件中定义SpringMVC模块的具体配置。annomvc-servlet.xml的配置内容如下所示: 清单3.annomvc-servlet.xml 因为Spring所有功能都在Bean的基础上演化而来,所以必须事先将Controller变成Bean,这是通过在类中标注@Controller并在annomvc-servlet.xml中启用组件扫描机制来完成的,如①所示。 在②处,配置了一个AnnotationMethodHandlerAdapter,它负责根据Bean中的SpringMVC注解对Bean进行加工处理,使这些Bean变成控制器并映射特定的URL请求。 而③处的工作是定义模型视图名称的解析规则,这里我们使用了Spring2.5的特殊命名空间,即p命名空间,它将原先需要通过元素配置的内容转化为属性配置,在一定程度上简化了的配置。 启动Tomcat,发送.baobaotao.service.BbtForumService; importorg.springframework.beans.factory.annotation.Autowired; importorg.springframework.stereotype.Controller; importorg.springframework.web.bind.annotation.RequestMapping; @Controller @RequestMapping(“/bbtForum.do”)//<——①指定控制器对应URL请求 publicclassBbtForumController{ @Autowired privateBbtForumServicebbtForumService; //<——②如果URL请求中包括“method=listAllBoard”的参数,由本方法进行处理 @RequestMapping(params=“method=listAllBoard”) publicStringlistAllBoard(){ bbtForumService.getAllBoard(); System.out.println(“calllistAllBoardmethod.”); return“listBoard”; } //<——③如果URL请求中包括“method=listBoardTopic”的参数,由本方法进行处理 @RequestMapping(params=“method=listBoardTopic”) publicStringlistBoardTopic(inttopicId){ bbtForumService.getBoardTopics(topicId); System.out.println(“calllistBoardTopicmethod.”); return“listTopic”; } }