转换器和格式化

说明

  SpringMVC的数据绑定并非没有限制,有案例表明,在SpringMVC如何正确绑定数据方面是杂乱无章的,比如在处理日期映射到Date对象上
  为了能够让SpringMVC进行正确地数据绑定,我们需要用到Converter和Formatter来协助SpringMVC完成。   

举例:

  我们知道HTTP表单中的所有请求参数都是String类型的,而且日期时间数据没有特定的形式1997-3-20,1997:03:20乃至20/03/1997对于我们人来说都是正确的形式都应该可以映射到Date对象上,但对于计算机来说都是陌生的,我们就要构建一种桥梁,来让计算机正确绑定数据。

  Converter和Formatter都可以用于将一种对象类型转换成另一种对象类型

区别:

  Converter是通用元件,可以在应用程序的任意层使用。
  Formatter是专用元件,专门为Web层设计。

Converter

说明

   Converter转换器可以进行格式转换,这是一种通用的元件。下面我们要实现的效果是:

  
  按照图示所示的日期格式让SpringMVC可以识别并转换成Date对象

编写Converter步骤:

1.编写一个实现了org.springframework.core.convert.converter.Converter接口的Java类。

  1. public class MyConverter implements Converter<String,Date> {
  2. //<源类型,目标类型>
  3. private String dataPattern;
  4. public MyConverter(String dataPattern)
  5. {
  6. this.dataPattern=dataPattern;
  7. System.out.println("DataPattern is"+dataPattern);
  8. }
  9. public Date convert(String s) {
  10. try {
  11. SimpleDateFormat simpleDateFormat= new SimpleDateFormat(dataPattern);
  12. simpleDateFormat.setLenient(false);
  13. //设置日期/时间的解析是否不严格,为false表示严格
  14.  
  15. return simpleDateFormat.parse(s);
  16. } catch (ParseException e) {
  17. e.printStackTrace();
  18. }
  19. return null;
  20. }
  21. }

2.在SpringMVC的配置文件中编写一个ConversionService bean.

说明:

  Bean的类名称必须是org.springframework.context.support.ConversionServiceFactoryBean.
  这个Bean必须包含一个converters属性,它将列出在应用程序中用到的所有定制Converter.

  1. <bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
  2. <property name="converters">
  3. <list>
  4. <bean class="converter.MyConverter">
  5. <constructor-arg type="java.lang.String" value="MM-dd-yyyy"/>
  6. </bean>
  7. </list>
  8. </property>
  9. </bean>

3.要给annotation-driven元素的conversion-service属性赋bean名称

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:context="http://www.springframework.org/schema/context"
  5. 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.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
  7. http://www.springframework.org/schema/mvc
  8. http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
  9. ">
  10. <context:component-scan base-package="controller"/>
  11. <context:component-scan base-package="Service"/>
  12. <!--
  13. <mvc:annotation-driven>元素注册用于支持基于注解的控制器的请求处理方法的Bean对象。
  14. 详解:https://my.oschina.net/HeliosFly/blog/205343
  15. -->
  16. <mvc:annotation-driven conversion-service="conversionService"/>
  17.  
  18. <bean id="viewResolver"
  19. class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  20. <property name="prefix" value="/WEB-INF/view/"/>
  21. <property name="suffix" value=".jsp"/>
  22. </bean>
  23.  
  24. <bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
  25. <property name="converters">
  26. <list>
  27. <bean class="converter.MyConverter">
  28. <constructor-arg type="java.lang.String" value="MM-dd-yyyy"/>
  29. </bean>
  30. </list>
  31. </property>
  32. </bean>
  33. </beans>

其余代码

1.编写控制器

  1. package controller;
  2.  
  3. import domain.Employee;
  4. import org.apache.commons.logging.Log;
  5. import org.apache.commons.logging.LogFactory;
  6. import org.springframework.stereotype.Controller;
  7. import org.springframework.ui.Model;
  8. import org.springframework.validation.BindingResult;
  9. import org.springframework.validation.FieldError;
  10. import org.springframework.web.bind.annotation.ModelAttribute;
  11. import org.springframework.web.bind.annotation.RequestMapping;
  12.  
  13. /**
  14. * Created by zy on 17-3-3.
  15. */
  16. @Controller
  17. public class EmployeeController {
  18. private static final Log logger = LogFactory.getLog(EmployeeController.class);
  19.  
  20. @RequestMapping("employ_input")
  21. public String inputEmployee(Model model)
  22. {
  23. model.addAttribute("employee",new Employee());
  24. return "EmployeeForm";
  25. }
  26. @RequestMapping("employ_save")
  27. public String saveEmployee(@ModelAttribute Employee employee,BindingResult bindingResult,Model model)
  28. {
  29. if(bindingResult.hasErrors())
  30. {
  31. FieldError fieldError = bindingResult.getFieldError();
  32. logger.info("Code:" +fieldError.getCode()+",field"+fieldError.getField());
  33. return "EmployeeForm";
  34. }
  35. model.addAttribute("employee",employee);
  36. return "EmployeeForm";
  37. }
  38. }

2.编写视图

  1. <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
  2. <%@ page contentType="text/html;charset=UTF-8" language="java" %>
  3. <html>
  4. <head>
  5. <title>EmployeeInput</title>
  6. </head>
  7. <body>
  8. <form:form commandName="employee" action="employ_save" method="post">
  9. <legend>Add Employee</legend>
  10. <p>
  11. <label for="firstName"></label>
  12. <form:input path="firstName" tabindex="1"/>
  13. </p>
  14. <p>
  15. <label for="lastName"></label>
  16. <form:input path="lastName" tabindex="2"/>
  17. </p>
  18. <p>
  19. <form:errors path="birthDate" cssClass="error"/>
  20. </p>
  21. <p>
  22. <label for="birthDate">出生日期</label>
  23. <form:input path="birthDate" tabindex="3"/>
  24. </p>
  25. <p>
  26. <input type="submit" value="Add Employee">
  27. </p>
  28. </form:form>
  29. </body>
  30. </html>

Formatter

说明

  Formatter就像Converter一样,也是将一种类型转换成另外一种类型。但是,Formatter的源类型必须是String,而Converter则适用于任意的源类型。
  Formatter更适合在Web层使用,处理表单输入,始终应该选择Formatter,而不是Converter。

编写Formatter

1.编写一个实现了org.springframework.format.Formatter接口的Java类。

2.在SpringMVC的配置文件中编写一个ConversionService bean.

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:context="http://www.springframework.org/schema/context"
  5. 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.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
  7. http://www.springframework.org/schema/mvc
  8. http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
  9. ">
  10. <context:component-scan base-package="controller"/>
  11. <context:component-scan base-package="Service"/>
  12. <!--
  13. <mvc:annotation-driven>元素注册用于支持基于注解的控制器的请求处理方法的Bean对象。
  14. 详解:https://my.oschina.net/HeliosFly/blog/205343
  15. -->
  16. <mvc:annotation-driven conversion-service="conversionService"/>
  17.  
  18. <bean id="viewResolver"
  19. class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  20. <property name="prefix" value="/WEB-INF/view/"/>
  21. <property name="suffix" value=".jsp"/>
  22. </bean>
  23. <!--需要配置此项来扫描Formatter-->
  24. <context:component-scan base-package="formatter"/>
  25. <bean id="formatterConversionService"
  26. class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
  27. <property name="formatters">
  28. <set>
  29. <bean class="formatter.DateFormatter">
  30. <constructor-arg type="java.lang.String"
  31. value="MM-dd-yyyy"/>
  32. </bean>
  33. </set>
  34. </property>
  35. </bean>
  36. </beans>

选择Converter还是Formatter

在SpringMVC应用程序中当然是Formatter更合适~\(≧▽≦)/~啦啦啦

SpringMVC:学习笔记(6)——转换器和格式化的更多相关文章

  1. springmvc学习笔记(简介及使用)

    springmvc学习笔记(简介及使用) 工作之余, 回顾了一下springmvc的相关内容, 这次也为后面复习什么的做个标记, 也希望能与大家交流学习, 通过回帖留言等方式表达自己的观点或学习心得. ...

  2. SpringMVC学习笔记之二(SpringMVC高级参数绑定)

    一.高级参数绑定 1.1 绑定数组 需求:在商品列表页面选中多个商品,然后删除. 需求分析:功能要求商品列表页面中的每个商品前有一个checkbok,选中多个商品后点击删除按钮把商品id传递给Cont ...

  3. springmvc学习笔记(18)-json数据交互

    springmvc学习笔记(18)-json数据交互 标签: springmvc springmvc学习笔记18-json数据交互 springmvc进行json交互 环境准备 加入json转换的依赖 ...

  4. 史上最全的SpringMVC学习笔记

    SpringMVC学习笔记---- 一.SpringMVC基础入门,创建一个HelloWorld程序 1.首先,导入SpringMVC需要的jar包. 2.添加Web.xml配置文件中关于Spring ...

  5. springmvc学习笔记--REST API的异常处理

    前言: 最近使用springmvc写了不少rest api, 觉得真是一个好框架. 之前描述的几篇关于rest api的文章, 其实还是不够完善. 比如当遇到参数缺失, 类型不匹配的情况时, 直接抛出 ...

  6. springmvc学习笔记---面向移动端支持REST API

    前言: springmvc对注解的支持非常灵活和飘逸, 也得web编程少了以往很大一坨配置项. 另一方面移动互联网的到来, 使得REST API变得流行, 甚至成为主流. 因此我们来关注下spring ...

  7. SpringMVC:学习笔记(8)——文件上传

    SpringMVC--文件上传 说明: 文件上传的途径 文件上传主要有两种方式: 1.使用Apache Commons FileUpload元件. 2.利用Servlet3.0及其更高版本的内置支持. ...

  8. springmvc学习笔记(常用注解)

    springmvc学习笔记(常用注解) 1. @Controller @Controller注解用于表示一个类的实例是页面控制器(后面都将称为控制器). 使用@Controller注解定义的控制器有如 ...

  9. springmvc学习笔记(13)-springmvc注解开发之集合类型參数绑定

    springmvc学习笔记(13)-springmvc注解开发之集合类型參数绑定 标签: springmvc springmvc学习笔记13-springmvc注解开发之集合类型參数绑定 数组绑定 需 ...

随机推荐

  1. RPMforge(Repoforge)源

    centos使用rpmforge-release 时间:2017-10-09 09:48:29      阅读:536      评论:0      收藏:0      [点我收藏+] 标签:rpmf ...

  2. @Cache(usage = CacheConcurrencyStrategy.READ_WRITE)什么意思??

    从hibernate2.1开始ehcache已经作为hibernate的默认缓存方案(二级缓存方案 sessionfactory级别), 在项目中有针对性的使用缓存将对性能的提升右很大的帮助. 要使用 ...

  3. Android 混淆完全解析

    1.http://blog.csdn.net/jddkdd2/article/details/8858909

  4. 视频采集接口camera link 在8148中的应用

    (1)应用背景 (2)camera link 简介 (3)camera link 与8148 (4)camera link 应用实例 ---------------------author:pkf - ...

  5. Oracle数据迁移expdp/impdp

    Oracle数据迁移expdp/impdp目的:指导项目侧自行进行简单的数据泵迁移工作. 本文实验环境:Oracle 11.2.0.4,利用数据库自带的scott示例用户进行试验测试. 1.首先需要创 ...

  6. virtualbox 虚拟机硬盘扩容

    转自: http://jingyan.baidu.com/article/425e69e6aeede8be14fc1675.html

  7. 更改centos 7 的默认启动为命令界面

    vi /etc/inittab 可以看到这样两行: # To set a default target, run:# systemctl set-default TARGET.target 故: su ...

  8. 巧妙使用JQuery Clone 添加多行数据,并更新到数据库的实现代码

    web前端代码: <%@ Page Language="C#" AutoEventWireup="true" CodeFile="BatchAd ...

  9. 集合 Vector ArrayList 集合一

    集合是存储对象的,与对象数组不同,集合可以自动的扩大自己的容量,像StringBuffer一样,存储的对象类型可以不一致,(object数组). 方法: add();remove();get();se ...

  10. Android 自定义键盘车牌号输入

    参考资料 :https://github.com/winterPei/LicensePlateUtil 自定义优化代码: https://gitee.com/anan9303/LicensePlate ...