标签: springmvcjava
[TOC]git
本文主要介绍注解开发的简单参数绑定,包括简单类型、简单pojo以及自定义绑定实现类型转换github
从客户端请求key/value数据,通过参数绑定,将key/value数据绑定到controller方法的形参上。spring
springmvc中,接收页面提交的数据是经过方法形参来接收。而不是在controller类定义成员变动接收!!!!session
直接在controller方法形参上定义下边类型的对象,就能够使用这些对象。在参数绑定过程当中,若是遇到下边类型直接进行绑定。mvc
HttpServletRequest
:经过request对象获取请求信息HttpServletResponse
:经过response处理响应信息HttpSession
:经过session对象获得session中存放的对象Model/ModelMap
:model是一个接口,modelMap是一个接口实现。做用:将model数据填充到request域。经过@RequestParam
对简单类型的参数进行绑定。若是不使用@RequestParam
,要求request传入参数名称和controller方法的形参名称一致,方可绑定成功。app
若是使用@RequestParam
,不用限制request传入参数名称和controller方法的形参名称一致。框架
经过required属性指定参数是否必需要传入,若是设置为true,没有传入参数,报下边错误:jsp
@RequestMapping(value="/editItems",method={RequestMethod.POST,RequestMethod.GET}) //@RequestParam里边指定request传入参数名称和形参进行绑定。 //经过required属性指定参数是否必需要传入 //经过defaultValue能够设置默认值,若是id参数没有传入,将默认值和形参绑定。 public String editItems(Model model,@RequestParam(value="id",required=true) Integer items_id)throws Exception {
页面中input的name和controller的pojo形参中的属性名称一致,将页面中数据绑定到pojo。学习
注意:这里只是要求name和形参的属性名一致,而不是要求和形参的名称一致,这点不要混淆了,框架会进入形参内部自动匹配pojo类的属性名。(我没看源码,但应该是用反射实现的)
页面定义:
<table width="100%" border=1> <tr> <td>商品名称</td> <td><input type="text" name="name" value="${itemsCustom.name }"/></td> </tr> <tr> <td>商品价格</td> <td><input type="text" name="price" value="${itemsCustom.price }"/></td> </tr>
controller的pojo形参的定义:
public class Items { private Integer id; private String name; private Float price; private String pic; private Date createtime; private String detail;
对于controller形参中pojo对象,若是属性中有日期类型,须要自定义参数绑定。
将请求日期数据串传成日期类型,要转换的日期类型和pojo中日期属性的类型保持一致。本文示例中,自定义参数绑定将日期串转成java.util.Date类型。
须要向处理器适配器中注入自定义的参数绑定组件。
public class CustomDateConverter implements Converter<String,Date>{ public Date convert(String s) { //实现 将日期串转成日期类型(格式是yyyy-MM-dd HH:mm:ss) SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); try { //转成直接返回 return simpleDateFormat.parse(s); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } //若是参数绑定失败返回null return null; } }
<mvc:annotation-driven conversion-service="conversionService"></mvc:annotation-driven>
<!-- 自定义参数绑定 --> <bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean"> <!-- 转换器 --> <property name="converters"> <list> <!-- 日期类型转换 --> <bean class="com.iot.learnssm.firstssm.controller.converter.CustomDateConverter"/> </list> </property> </bean>
springmvc将url和controller方法映射。映射成功后springmvc生成一个Handler对象,对象中只包括了一个method。方法执行结束,形参数据销毁。springmvc的controller开发相似service开发。
2.springmvc能够进行单例开发,而且建议使用单例开发,struts2经过类的成员变量接收参数,没法使用单例,只能使用多例。
3.通过实际测试,struts2速度慢,在于使用struts标签,若是使用struts建议使用jstl。