Spring MVC是一个构建于Spring Framework之上的现代Web应用程序框架. Spring3 全面支持REST风格的Web服务,"We're really seeing extensive interest and growth in REST, and it will have comprehensive support for RESTful Web services," said Johnson.spring3再加上对annotation的支持如虎添翼!
web.xml配置
<servlet> <servlet-name>controller</servlet-name> <servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value> classpath:*controller.xml </param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>controller</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping>
web.xml 中定义了一个名为 annomvc 的 Spring MVC 模块,按照 Spring MVC 的契约, 需要在 WEB-INF/annomvc-servlet.xml 配置文件中定义 Spring MVC 模块的具体配置 ,这里我们修改到*controller.xml中。
*controller.xml中加入
<!-- 对web包中的所有类进行扫描,以完成Bean创建和自动依赖注入的功能 --> <context:component-scan base-package="com.alan.manager.controller"/>
<!-- 使用tiles视图名解析器,即控制器返回的视图名均在tiles文件中定义 --> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/> <property name="prefix" value="/view/"/> <property name="suffix" value=".jsp"></property> </bean>
//注释功能开启
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/>
Java代码:
@Controller @RequestMapping("/resource.do")
public class TestController extends BaseController { @Autowired private TestDao testDao;
//用于ajax中,返回void
@RequestMapping(params = "method=validatName",method = RequestMethod.GET) public void validatName(HttpServletResponse response, @RequestParam(value = "enName", required = false)String name) throws IOException { Query<testDefinition> query = testDao.createQuery(); query.filter("enName", name); List list = testDao.find(query).asList(); if(list != null && list.size() > 0){ response.getWriter().write(String.valueOf(false)); }else{ response.getWriter().write(String.valueOf(true)); } response.getWriter().flush(); response.getWriter().close(); }
@RequestMapping(params = "method=test",method = RequestMethod.POST)
public ModelAndView test2(HttpServletRequest arg0, ②响应请求的方法 HttpServletResponse arg1) throws Exception { return new ModelAndView("index","greeting",greeting); ③返回一个ModelAndView对象 }
@RequestMapping(params = "method=test3")
public String test3(Model model) throws Exception {
model.addAttribute("resource", "hehh");
return "test3"
}
}
通过resource.do?method=validatName请求上面第一个方法。上面代码描述了controller中返回的几种形式,validatName返回text文本,不进行页面跳转,test2跳转到/view/index.jsp页面中,test3跳转到/view/test3.jsp,每个方法传入的参数可以是不同的,根据需要传入。
注意事项:
@Controller将该类注释为controller
1 处理多个请求
在每个方法前面使用 @RequestMapping("/名称.do") 不同的名称 处理不同的请求 缺点:xxx.do 太多不利于 跟踪 ,复制程度增加
在controller 类名前面定义 @RequestMapping("/名称.do")在方法前添加注解
@RequestMapping(params = "method=listAllBoard") 则处理 有此参数的请求 多一个参数思路清楚
2 处理不同的http 请求:
在方法前面增加注释:RequestMethod 有POST,GET如:@RequestMapping(params = "method=test",method = RequestMethod.POST)
3 参数处理:(默认这样处理,也是 约定优于设计原则 自动转换类型) 自由选择
普通属性: 如果入参是基本数据类型(如 int、long、float 等),URL 请求参数中一定要有对应的参数,否则将抛出 TypeMismatchException 异常,提示无法将 null 转换为基本数据类型。
对象及属性: Userbean 的 userId 属性的类型是基本数据类型,但如果 URL 中不存在 userId 参数,Spring 也不会报错,此时 Userbean.userId 值为 0。如果 Userbean 对象拥有一个 dept.deptId 的级联属性,那么它将和 dept.deptId参数绑定。
4 参数处理:(明确指定参数 匹配 自动转换类型)
普通属性 和 对象及属性: @RequestParam("id") 注解,所以它将和 id 的 URL 参数绑定
5 绑定域中的某个属性:
Model ModelMap 类,它作为通用的模型数据承载对象,传递数据供视图所用 代替 request.setParam
Session @SessionAttributes("currUser") //①将ModelMap中属性名为currUser的属性 放到Session属性列表中,以便这个属性可以跨请求访问 (类名前面写)
session 多个参数 !@SessionAttributes({“attr1”,”attr2”})。
取值绑定到方法上 (@ModelAttribute("currUser") User user)
注解及解释:
@Autowired 将分别寻找和它们类型匹配的 Bean 注入, @Autowired 可以对成员变量、方法以及构造函数进行注释,ByType
如果有多个匹配结果 或者没结果 BeanCreationException 异常
@Autowired(required = false),这等于告诉 Spring:在找不到匹配 Bean 时也不报错。
@Qualifier 注释指定注入 Bean 的名称 ,@Qualifier 的标注对象是成员变量、方法入参、构造函数入参 ---------- ByName
@Autowired 和 @Qualifier 结合使用时,自动注入的策略就从 byType 转变成 byName
@Resource 默认按 byName 自动注入
@InitBinder在controller方法前酌情使用,用于调用请求方法前的一些初始化
其他org.springframework.web.multipart.commons.CommonsMultipartResolver
org.springframework.web.servlet.view.json.MappingJacksonJsonView等根据需要在配置文件中配置
restful feature in spring mvc 3
spring mvc 3中rest风格的动态传参请求,java后台代码如下,一些值通过 URI 传递。
@RequestMapping(value="/hotels/{hotel}/bookings/{booking}", method=RequestMethod.GET) public String getBooking(@PathVariable("hotel") long hotelId, @PathVariable("booking") long bookingId, Model model) { Hotel hotel = hotelService.getHotel(hotelId); Booking booking = hotel.getBooking(bookingId); model.addAttribute("booking", booking); return "booking"; }详细参照: http://blog.springsource.com/2009/03/08/rest-in-spring-3-mvc/