绑定简单数据类型
1 需求
打开商品编辑页面,展示商品信息。
2 需求分析
编辑商品信息,需要根据商品id查询商品信息,然后展示到页面。
请求的url:/itemEdit.action
参数:id(商品id)
响应结果:商品编辑页面,展示商品详细信息。
3 Service
@Overridepublic Items getItemById(int id) {Items items = itemMapper.getItemById(id);returnitems;}
4 Controller参数绑定
要根据id查询商品数据,需要从请求的参数中把请求的id取出来。Id应该包含在Request对象中。可以从Request对象中取id。
@RequestMapping("/itemEdit")public ModelAndView itemEdit(HttpServletRequest request) {//从Request中取idString strId = request.getParameter("id");Integer id = null;//如果id有值则转换成int类型if (strId != null && !"".equals(strId)) {id = newInteger(strId);} else {//出错returnnull;}Items items = itemService.getItemById(id);//创建ModelAndViewModelAndView modelAndView = new ModelAndView();//向jsp传递数据modelAndView.addObject("item", items);//设置跳转的jsp页面modelAndView.setViewName("editItem");return modelAndView;}
如果想获得Request对象只需要在Controller方法的形参中添加一个参数即可。Springmvc框架会自动把Request对象传递给方法。
5 默认支持的参数类型
处理器形参中添加如下类型的参数处理适配器会默认识别并进行赋值。
1) HttpServletRequest
通过request对象获取请求信息
2) HttpServletResponse
通过response处理响应信息
3) HttpSession
通过session对象得到session中存放的对象
4) Model/ModelMap
ModelMap是Model接口的实现类,通过Model或ModelMap向页面传递数据,如下:
//调用service查询商品信息Items item = itemService.findItemById(id);model.addAttribute("item", item);
页面通过${item.XXXX}获取item对象的属性值。
使用Model和ModelMap的效果一样,如果直接使用Model,springmvc会实例化ModelMap。
原来为 table,需要自己转换一下{"cells":[{"verticalAlign":"top","wrap":true,"backColor":"rgb(242, 242, 242)","value":"如果使用Model则可以不使用ModelAndView对象,Model对象可以向页面传递数据,View对象则可以使用String返回值替代。不管是Model还是ModelAndView,其本质都是使用Request对象向jsp传递数据。","inlineStyles":{"font-family":[{"from":0,"to":4,"value":"SimSun"},{"from":9,"to":15,"value":"SimSun"},{"from":27,"to":30,"value":"SimSun"},{"from":35,"to":47,"value":"SimSun"},{"from":51,"to":58,"value":"SimSun"},{"from":64,"to":73,"value":"SimSun"},{"from":78,"to":80,"value":"SimSun"},{"from":92,"to":100,"value":"SimSun"},{"from":107,"to":110,"value":"SimSun"},{"from":113,"to":118,"value":"SimSun"}],"color":[{"from":0,"to":118,"value":"#0000ff"}]}}],"heights":[40],"widths":[568]}
如果使用Model则方法可以改造成:
@RequestMapping("/itemEdit")public String itemEdit(HttpServletRequest request, Model model) {//从Request中取idString strId = request.getParameter("id");Integer id = null;//如果id有值则转换成int类型if (strId != null&& !"".equals(strId)) {id = newInteger(strId);} else {//出错returnnull;}Items items = itemService.getItemById(id);//创建ModelAndView//ModelAndView modelAndView = new ModelAndView();//向jsp传递数据//modelAndView.addObject("item", items);model.addAttribute("item", items);//设置跳转的jsp页面//modelAndView.setViewName("editItem");//return modelAndView;return "editItem";}
6 绑定简单类型
当请求的参数名称和处理器形参名称一致时会将请求参数与形参进行绑定。从Request取参数的方法可以进一步简化。
@RequestMapping("/itemEdit")public String itemEdit(Integer id, Model model) {Items items = itemService.getItemById(id);//向jsp传递数据model.addAttribute("item", items);//设置跳转的jsp页面return "editItem";}
1) 支持的数据类型
参数类型推荐使用包装数据类型,因为基础数据类型不可以为null
整形:Integer、int
字符串:String
单精度:Float、float
双精度:Double、double
布尔型:Boolean、boolean
说明:对于布尔类型的参数,请求的参数值为true或false。
处理器方法:
public String editItem(Model model,Integer id,Boolean status) throws Exception
请求url:
http://localhost:8080/xxx.action?id=2&status=false
2) @RequestParam
使用@RequestParam常用于处理简单类型的绑定。
value:参数名字,即入参的请求参数名字,如value=“item_id”表示请求的参数区中的名字为item_id的参数的值将传入;
required:是否必须,默认是true,表示请求中一定要有相应的参数,否则将报;
TTP Status 400 - Required Integer parameter ‘XXXX’ is not present
defaultValue:默认值,表示如果请求中没有同名参数时的默认值
定义如下:
public String editItem(@RequestParam(value="item_id",required=true) String id) {}
形参名称为id,但是这里使用value=”item_id”限定请求的参数名为item_id,所以页面传递参数的名必须为item_id。
注意:如果请求参数中没有item_id将跑出异常:
HTTP Status 500 - Required Integer parameter ‘item_id’ is not present
这里通过required=true限定item_id参数为必需传递,如果不传递则报400错误,可以使用defaultvalue设置默认值,即使required=true也可以不传item_id参数值
绑定pojo类型
1 需求
将页面修改后的商品信息保存到数据库中。
2 需求分析
请求的url:/updateitem.action
参数:表单中的数据。
响应内容:更新成功页面
3 使用pojo接收表单数据
如果提交的参数很多,或者提交的表单中的内容很多的时候可以使用pojo接收数据。要求pojo对象中的属性名和表单中input的name属性一致。
页面定义如下;
<input type="text" name="name"/><input type="text" name="price"/>
Pojo定义:

请求的参数名称和pojo的属性名称一致,会自动将请求参数赋值给pojo的属性。
@RequestMapping("/updateitem")public String updateItem(Items items) {itemService.updateItem(items);return"success";}
原来为 table,需要自己转换一下{"cells":[{"verticalAlign":"top","wrap":true,"backColor":"rgb(242, 242, 242)","value":"注意:提交的表单中不要有日期类型的数据,否则会报400错误。如果想提交日期类型的数据需要用到后面的自定义参数绑定的内容。","inlineStyles":{"font-family":[{"from":0,"to":24,"value":"SimSun"},{"from":27,"to":60,"value":"SimSun"}],"color":[{"from":0,"to":60,"value":"#0000ff"}]}}],"heights":[40],"widths":[568]}
4 解决post乱码问题
在web.xml中加入:
<filter><filter-name>CharacterEncodingFilter</filter-name><filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class><init-param><param-name>encoding</param-name><param-value>utf-8</param-value></init-param></filter><filter-mapping><filter-name>CharacterEncodingFilter</filter-name><url-pattern>/*</url-pattern></filter-mapping>
以上可以解决post请求乱码问题。
对于get请求中文参数出现乱码解决方法有两个:
修改tomcat配置文件添加编码与工程编码一致,如下:
<Connector URIEncoding="utf-8" connectionTimeout="20000"port="8080" protocol="HTTP/1.1" redirectPort="8443"/>
另外一种方法对参数进行重新编码:
String userName = new String(request.getParamter("userName").getBytes("ISO8859-1"),"utf-8")
ISO8859-1是tomcat默认编码,需要将tomcat编码后的内容按utf-8编码
绑定包装pojo
1需求
使用包装的pojo接收商品信息的查询条件。
2 需求分析
包装对象定义如下:
Public class QueryVo {private Items items;}
页面定义:
<input type="text" name="items.name" /><input type="text" name="items.price" />
Controller方法定义如下:
public String useraddsubmit(Model model, QueryVo queryVo)throws Exception{System.out.println(queryVo.getItems());}
1.1.3 接收查询条件
@RequestMapping("/queryitem")public String queryItem(QueryVo queryVo) {System.out.println(queryVo.getItems().getName());System.out.println(queryVo.getItems().getPrice());return null;}
自定义参数绑定
1 需求
在商品修改页面可以修改商品的生产日期,并且根据业务需求自定义日期格式。
2 需求分析
由于日期数据有很多种格式,所以springmvc没办法把字符串转换成日期类型。所以需要自定义参数绑定。前端控制器接收到请求后,找到注解形式的处理器适配器,对RequestMapping标记的方法进行适配,并对方法中的形参进行参数绑定。在springmvc这可以在处理器适配器上自定义Converter进行参数绑定。如果使用mvc:annotation-driven/可以在此标签上进行扩展。
3 自定义Converter
public class DateConverter implements Converter<String, Date> {@Overridepublic Date convert(String source) {SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");try {return simpleDateFormat.parse(source);} catch (ParseException e) {e.printStackTrace();}returnnull;}}
4 配置Converter
<!-- 加载注解驱动 --><mvc:annotation-drivenconversion-service="conversionService"/><!-- 转换器配置 --><beanid="conversionService"class="org.springframework.format.support.FormattingConversionServiceFactoryBean"><property name="converters"><set><beanclass="cn.itcast.springmvc.convert.DateConverter"/></set></property></bean>
1.1.5 配置方式2(了解)
<?xmlversion="1.0"encoding="UTF-8"?><beansxmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:p="http://www.springframework.org/schema/p"xmlns:context="http://www.springframework.org/schema/context"xmlns:dubbo="http://code.alibabatech.com/schema/dubbo"xmlns:mvc="http://www.springframework.org/schema/mvc"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsdhttp://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsdhttp://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd"><!-- 扫描带Controller注解的类 --><context:component-scanbase-package="cn.itcast.springmvc.controller"/><!-- 转换器配置 --><beanid="conversionService"class="org.springframework.format.support.FormattingConversionServiceFactoryBean"><propertyname="converters"><set><beanclass="cn.itcast.springmvc.convert.DateConverter"/></set></property></bean><!-- 自定义webBinder --><beanid="customBinder" class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer"><propertyname="conversionService"ref="conversionService"/></bean><!--注解适配器 --><beanclass="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"><propertyname="webBindingInitializer"ref="customBinder"></property></bean><!-- 注解处理器映射器 --><beanclass="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/><!-- 加载注解驱动 --><!-- <mvc:annotation-driven/> --><!-- 视图解析器 --><beanclass="org.springframework.web.servlet.view.InternalResourceViewResolver"><propertyname="viewClass"value="org.springframework.web.servlet.view.JstlView"/><!-- jsp前缀 --><propertyname="prefix"value="/WEB-INF/jsp/"/><!-- jsp后缀 --><propertyname="suffix"value=".jsp"/></bean></beans>
注意:此方法需要独立配置处理器映射器、适配器,不再使用mvc:annotation-driven/
