springmvc参数绑定

来源:互联网 发布:网络电子游艺漏洞 编辑:程序博客网 时间:2024/04/29 17:51
springmvc中,接收页面提交的数据是通过方法形参来接收,而不是Controller类定义成员变更接收。
springmvc参数绑定过程:处理器适配器在执行Handler之前需要把http请求的key/value数据绑定到Handler方法形参数上。
默认支持的参数类型
直接在Controller方法形参上定义下边类型的对象,就可以使用这些对象,在参数绑定过程中,如果遇到下边类型直接进行绑定。
1.HttpServletRequest
通过request对象获取请求信息
2.HttpServletResponse
通过response处理响应信息
3.HttpSession
通过session对象得到session中存放的对象信息
4.Model/ModelMap
model是一个接口,modelMap是一个接口实现
使用ModelModelMap的效果一样,如果直接使用Modelspringmvc会实例化ModelMap
作用:将model数据填充到request域
简单类型
当请求的参数名称和处理器形参名称一致时会将请求参数与形参进行绑定。
public ModelAndView editUser(HttpServletRequest request,Integer id) throws Exception {
//int id = Integer.parseInt(request.getParameter("id"));
UserCustom userCustom = usersService.findUserByID(id);
}
整形 Integer
字符串 String
单精度/双精度 Double
布尔型 Boolean
说明:对于布尔类型的参数,请求的参数值为truefalse
@RequestParam 注解参数使用
使用@RequestParam常用于处理简单类型的绑定。 
value参数名字,即入参的请求参数名字,如value=“item_id”表示请求的参数区中的名字为item_id的参数的值将传入;
required是否必须,默认是true,表示请求中一定要有相应的参数,否则将报;
TTP Status 400 - Required Integer parameter 'XXXX' is not present
defaultValue默认值,表示如果请求中没有同名参数时的默认值
定义如下:
public ModelAndView editUser(HttpServletRequest request,@RequestParam(value="id",required=true,defaultValue="1") Integer uid) throws Exception {
UserCustom userCustom = usersService.findUserByID(uid);
}
pojo绑定
页面中input的name和Controller的pojo形参中的属性名称一致,将页面中的数据绑定到pojo

自定义参数绑定
对于日期类型,需要自定义参数绑定
将请求日期数据串转成日期类型(对于pojo的属性类型java.util.Date)
需要向处理器适配器中注入自定义的参数绑定组件
jsp界面
<input type="text" name="modifytime" value='<fmt:formatDate value="${userCustom.modifytime }" pattern="yyyy-MM-dd HH:mm:ss"/>'/>

springmvc.xml
<mvc:annotation-driven conversion-service="conversionService"></mvc:annotation-driven>
<!-- 自定义参数绑定 -->
<bean id="conversionService"
class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<property name="converters">
<list>
<bean class="sys.um.controller.converter.CustomDateConverter"></bean>
</list>
</property>
</bean>
转换器类
public class CustomDateConverter implements Converter<String, Date> {
@Override
public Date convert(String source) {
// TODO 自动生成的方法存根
SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
return dateFormat.parse(source);
} catch (ParseException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
return null;
}
}
0 0