示例2 基于注解的控制器
从Spring2.5开始新增了基于注解的控制器,也就是说控制器不用实现Controller接口,通过注解类型来描述。下面将SpringMVCTest这个Web应用进行修改演示一个基于注解的控制器Spring MVC的Web应用.
新建一个Dynamic Web Project,也就是新建一个动态Web项目,命名为AnnotationTest。所有步骤和2.3.3节的”第一个Spring MVC应用”示例一样,只是修改两个地方
1. Controller类的实现
HelloController类不需要Controller接口,改为使用注解类型来描述,处理/hello请求。示例代码如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| package org.fkit.controller;
import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView;
@Controller public class HelloController {
@RequestMapping(value = "/hello") public ModelAndView hello() { System.out.println("hello方法 被调用"); ModelAndView mv = new ModelAndView(); mv.addObject("message", "Hello World!"); mv.setViewName("/WEB-INF/content/welcome.jsp"); return mv; } }
|
HelloController是一个基于注解的控制器,org.springframework.stereotype.Controller注释类型用于指示Spring类的实例是一个控制器。org.springframework.web.bind.annotation.RequestMapping注释类型用来映射一个请求和请求的方法, value="/hello"表示请求由hello方法进行处理。方法返回一个包含视图名或视图名和模型的ModelAndView对象,这和2.3.4节中的示例一样。
2. 修改Spring MVC的配置文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="org.fkit.controller" /> <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping" /> <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter" /> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" /> </beans>
|
由于使用了注解类型,因此不需要再在配置文件中使用XML描述Bean。 Spring使用扫描机制査找应用程序中所有基于注解的控制器类。<context:component-scan base-package="org.fkit.controller" />指定需要Spring扫描org.fkit.controller包及其子包下面的所有Java文件
此处还配置类型的处理器映射器RequestMappingHandlerMapping,它根据请求査找映射;
同时配置了annotation类型的处理器适配器RequestMappingHandlerAdapter,来完成对Hellocontro11er类的@RequestMapping标注方法的调用;
最后配置了视图解析器InternalresourceviewResolver来解析视图,将View呈现给用户。
需要注意的是,在Spring4.0之后,处理器映射器、处理器适配器的配置还可以使用更简便的方式,笔者在此处显示配置处理过程,是希望读者能够了解Spring MVC的每一个动作,之后可以更好地理解Spring MVC的工作流程
3. 测试
使用Eclipse部署AnnotationTest这个Web应用,在浏览器中输入如下URL来测试应用
1
| http://localhost:8080/AnnotationTest/hello
|
此时浏览器上显示Hello World!字符串,这表示Spring MVC访问成功
原文链接: 示例2 基于注解的控制器