绑定简单数据类型

1 需求

打开商品编辑页面,展示商品信息。

2 需求分析

编辑商品信息,需要根据商品id查询商品信息,然后展示到页面。

请求的url:/itemEdit.action

参数:id(商品id)

响应结果:商品编辑页面,展示商品详细信息。

3 Service

  1. @Override
  2. public Items getItemById(int id) {
  3. Items items = itemMapper.getItemById(id);
  4. returnitems;
  5. }

4 Controller参数绑定

要根据id查询商品数据,需要从请求的参数中把请求的id取出来。Id应该包含在Request对象中。可以从Request对象中取id。

  1. @RequestMapping("/itemEdit")
  2. public ModelAndView itemEdit(HttpServletRequest request) {
  3. //从Request中取id
  4. String strId = request.getParameter("id");
  5. Integer id = null;
  6. //如果id有值则转换成int类型
  7. if (strId != null && !"".equals(strId)) {
  8. id = newInteger(strId);
  9. } else {
  10. //出错
  11. returnnull;
  12. }
  13. Items items = itemService.getItemById(id);
  14. //创建ModelAndView
  15. ModelAndView modelAndView = new ModelAndView();
  16. //向jsp传递数据
  17. modelAndView.addObject("item", items);
  18. //设置跳转的jsp页面
  19. modelAndView.setViewName("editItem");
  20. return modelAndView;
  21. }

如果想获得Request对象只需要在Controller方法的形参中添加一个参数即可。Springmvc框架会自动把Request对象传递给方法。

5 默认支持的参数类型

处理器形参中添加如下类型的参数处理适配器会默认识别并进行赋值。

1) HttpServletRequest

通过request对象获取请求信息

2) HttpServletResponse

通过response处理响应信息

3) HttpSession

通过session对象得到session中存放的对象

4) Model/ModelMap

ModelMap是Model接口的实现类,通过Model或ModelMap向页面传递数据,如下:

  1. //调用service查询商品信息
  2. Items item = itemService.findItemById(id);
  3. model.addAttribute("item", item);

页面通过${item.XXXX}获取item对象的属性值。

使用Model和ModelMap的效果一样,如果直接使用Model,springmvc会实例化ModelMap。

  1. 原来为 table,需要自己转换一下
  2. {"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则方法可以改造成:

  1. @RequestMapping("/itemEdit")
  2. public String itemEdit(HttpServletRequest request, Model model) {
  3. //从Request中取id
  4. String strId = request.getParameter("id");
  5. Integer id = null;
  6. //如果id有值则转换成int类型
  7. if (strId != null&& !"".equals(strId)) {
  8. id = newInteger(strId);
  9. } else {
  10. //出错
  11. returnnull;
  12. }
  13. Items items = itemService.getItemById(id);
  14. //创建ModelAndView
  15. //ModelAndView modelAndView = new ModelAndView();
  16. //向jsp传递数据
  17. //modelAndView.addObject("item", items);
  18. model.addAttribute("item", items);
  19. //设置跳转的jsp页面
  20. //modelAndView.setViewName("editItem");
  21. //return modelAndView;
  22. return "editItem";
  23. }

6 绑定简单类型

当请求的参数名称和处理器形参名称一致时会将请求参数与形参进行绑定。从Request取参数的方法可以进一步简化。

  1. @RequestMapping("/itemEdit")
  2. public String itemEdit(Integer id, Model model) {
  3. Items items = itemService.getItemById(id);
  4. //向jsp传递数据
  5. model.addAttribute("item", items);
  6. //设置跳转的jsp页面
  7. return "editItem";
  8. }

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:默认值,表示如果请求中没有同名参数时的默认值

定义如下:

  1. public String editItem(@RequestParam(value="item_id",required=true) String id) {
  2. }

形参名称为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属性一致。

页面定义如下;

  1. <input type="text" name="name"/>
  2. <input type="text" name="price"/>

Pojo定义:

03 参数绑定 - 图1

请求的参数名称和pojo的属性名称一致,会自动将请求参数赋值给pojo的属性。

  1. @RequestMapping("/updateitem")
  2. public String updateItem(Items items) {
  3. itemService.updateItem(items);
  4. return"success";
  5. }
  1. 原来为 table,需要自己转换一下
  2. {"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中加入:

  1. <filter>
  2. <filter-name>CharacterEncodingFilter</filter-name>
  3. <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
  4. <init-param>
  5. <param-name>encoding</param-name>
  6. <param-value>utf-8</param-value>
  7. </init-param>
  8. </filter>
  9. <filter-mapping>
  10. <filter-name>CharacterEncodingFilter</filter-name>
  11. <url-pattern>/*</url-pattern>
  12. </filter-mapping>

以上可以解决post请求乱码问题。

对于get请求中文参数出现乱码解决方法有两个:

修改tomcat配置文件添加编码与工程编码一致,如下:

  1. <Connector URIEncoding="utf-8" connectionTimeout="20000"
  2. port="8080" protocol="HTTP/1.1" redirectPort="8443"/>

另外一种方法对参数进行重新编码:

  1. String userName = new String(request.getParamter("userName").getBytes("ISO8859-1"),"utf-8")

ISO8859-1是tomcat默认编码,需要将tomcat编码后的内容按utf-8编码

绑定包装pojo

1需求

使用包装的pojo接收商品信息的查询条件。

2 需求分析

包装对象定义如下:

  1. Public class QueryVo {
  2. private Items items;
  3. }

页面定义:

  1. <input type="text" name="items.name" />
  2. <input type="text" name="items.price" />

Controller方法定义如下:

  1. public String useraddsubmit(Model model, QueryVo queryVo)throws Exception{
  2. System.out.println(queryVo.getItems());
  3. }

1.1.3 接收查询条件

  1. @RequestMapping("/queryitem")
  2. public String queryItem(QueryVo queryVo) {
  3. System.out.println(queryVo.getItems().getName());
  4. System.out.println(queryVo.getItems().getPrice());
  5. return null;
  6. }

自定义参数绑定

1 需求

在商品修改页面可以修改商品的生产日期,并且根据业务需求自定义日期格式。

2 需求分析

由于日期数据有很多种格式,所以springmvc没办法把字符串转换成日期类型。所以需要自定义参数绑定。前端控制器接收到请求后,找到注解形式的处理器适配器,对RequestMapping标记的方法进行适配,并对方法中的形参进行参数绑定。在springmvc这可以在处理器适配器上自定义Converter进行参数绑定。如果使用mvc:annotation-driven/可以在此标签上进行扩展。

3 自定义Converter

  1. public class DateConverter implements Converter<String, Date> {
  2. @Override
  3. public Date convert(String source) {
  4. SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  5. try {
  6. return simpleDateFormat.parse(source);
  7. } catch (ParseException e) {
  8. e.printStackTrace();
  9. }
  10. returnnull;
  11. }
  12. }

4 配置Converter

  1. <!-- 加载注解驱动 -->
  2. <mvc:annotation-drivenconversion-service="conversionService"/>
  3. <!-- 转换器配置 -->
  4. <beanid="conversionService"
  5. class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
  6. <property name="converters">
  7. <set>
  8. <beanclass="cn.itcast.springmvc.convert.DateConverter"/>
  9. </set>
  10. </property>
  11. </bean>

1.1.5 配置方式2(了解)

  1. <?xmlversion="1.0"encoding="UTF-8"?>
  2. <beansxmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:p="http://www.springframework.org/schema/p"
  4. xmlns:context="http://www.springframework.org/schema/context"
  5. xmlns:dubbo="http://code.alibabatech.com/schema/dubbo"xmlns:mvc="http://www.springframework.org/schema/mvc"
  6. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
  7. http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
  8. http://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd
  9. http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
  10. <!-- 扫描带Controller注解的类 -->
  11. <context:component-scanbase-package="cn.itcast.springmvc.controller"/>
  12. <!-- 转换器配置 -->
  13. <beanid="conversionService"
  14. class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
  15. <propertyname="converters">
  16. <set>
  17. <beanclass="cn.itcast.springmvc.convert.DateConverter"/>
  18. </set>
  19. </property>
  20. </bean>
  21. <!-- 自定义webBinder -->
  22. <beanid="customBinder" class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer">
  23. <propertyname="conversionService"ref="conversionService"/>
  24. </bean>
  25. <!--注解适配器 -->
  26. <beanclass="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
  27. <propertyname="webBindingInitializer"ref="customBinder"></property>
  28. </bean>
  29. <!-- 注解处理器映射器 -->
  30. <beanclass="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/>
  31. <!-- 加载注解驱动 -->
  32. <!-- <mvc:annotation-driven/> -->
  33. <!-- 视图解析器 -->
  34. <beanclass="org.springframework.web.servlet.view.InternalResourceViewResolver">
  35. <propertyname="viewClass"
  36. value="org.springframework.web.servlet.view.JstlView"/>
  37. <!-- jsp前缀 -->
  38. <propertyname="prefix"value="/WEB-INF/jsp/"/>
  39. <!-- jsp后缀 -->
  40. <propertyname="suffix"value=".jsp"/>
  41. </bean>
  42. </beans>

注意:此方法需要独立配置处理器映射器、适配器,不再使用mvc:annotation-driven/