SpringMVC中数据转换
SpringMVC中接收到的数据都是String形式,然后再根据反射机制将String转换成对应的类型。如果此时想接收一个Date类型,那么我们可以定义一个转换器来完成。
例如,我们有下面的Emp类:
package org.lyk.vo; import java.util.Date; public class Emp
{
private Integer empno;
private String ename;
private Double sal;
private Date hiredate; public Date getHiredate()
{
return hiredate;
}
public void setHiredate(Date hiredate)
{
this.hiredate = hiredate;
}
public Integer getEmpno()
{
return empno;
}
public void setEmpno(Integer empno)
{
this.empno = empno;
}
public String getEname()
{
return ename;
}
public void setEname(String ename)
{
this.ename = ename;
}
public Double getSal()
{
return sal;
}
public void setSal(Double sal)
{
this.sal = sal;
} @Override
public String toString()
{
return "Emp [empno=" + empno + ", ename=" + ename + ", sal=" + sal + ", hiredate=" + hiredate + "]";
} }
其中hiredate是日期类型。
下面是前端页面代码:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://" + request.getServerName() + ":"
+ request.getServerPort() + path + "/";
%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>"> <title>My JSP 'insert.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
--> </head> <body>
<form action="pages/emp/echo.action" method="post">
员工编号:<input name="empno" value="192"><br>
姓名:<input name="ename" value="刘远奎"><br>
薪水:<input name="sal" value="66.9"><br>
雇佣日期:<input name="hiredate" value="2015-10-12"/>
<input type="submit" value="提交">
</form>
</body>
</html>
下面是Spring的Action代码:
package org.lyk.servlet; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import org.lyk.vo.Dept;
import org.lyk.vo.Emp;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView; @Controller
@RequestMapping("/pages/emp/*")
public class EmpServlet
{
@RequestMapping
public ModelAndView echo(Emp emp,HttpServletRequest request,HttpServletResponse response)
{
System.out.println(request.getSession().getId());
request.getServletContext(); ModelAndView mav = new ModelAndView("/pages/emp/show.jsp");
System.out.println("*********Emp:" + emp);
mav.addObject("msg", emp.toString());
return mav;
}
}
上面的代码可以在设置Emp的empno、ename、sal的时候都没有问题,但是通过后台输出发现hiredate的值为null。如果想要SpringMVC给我们做转换,则主要专门写一个String到Date的转换代码。
package org.lyk.convertor;
//org.lyk.convertor.StringToDateConvertor
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.convert.converter.Converter; public class StringToDateConvertor implements Converter<String,Date>
{
private static final Logger logger = LoggerFactory.getLogger(StringToDateConvertor.class);
@Override
public Date convert(String dateInString)
{
logger.info("dateInString:" + dateInString);
SimpleDateFormat sdf = null;
if(dateInString != null && !"".equals(dateInString))
{
if(dateInString.matches("\\d{4}-\\d{2}-\\d{2}"))
{
sdf = new SimpleDateFormat("yyyy-MM-dd");
}else if(dateInString.matches("\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}"))
{
sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
}else if(dateInString.matches("\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}\\.\\d{3}"))
{
sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
}
else
{
logger.info("传入的日期参数格式有误!!!");
return null;
}
} logger.info("sdf:" + sdf); try
{
return sdf.parse(dateInString);
} catch (ParseException e)
{
e.printStackTrace();
return null;
} } }
然后配置上Sping的applicationContext.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd"> <context:annotation-config/>
<context:component-scan base-package="org.lyk"/> <!-- 第三步: 将conversionService配置到SpringMVC中 -->
<mvc:annotation-driven conversion-service="conversionService"/>
<mvc:default-servlet-handler/> <!-- 第一步: 给Spring容器注入String到Date的转换器 -->
<bean name="dateConvert" class="org.lyk.convertor.StringToDateConvertor"/> <!-- 第二部: 将该转换器注入到conversionService里 -->
<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<property name="converters">
<set>
<ref bean="dateConvert"/>
</set>
</property>
</bean>
</beans>
运行程序,后台输出结果.

SpringMVC中数据转换的更多相关文章
- SpringMVC的数据转换,格式化和数据校验
在SpringMVC中,根据请求方法签名不同,将请求消息中的消息以一定的方式转换并绑定到请求方法的参数中,在请求信息到达真正调用处理方法的这一段时间内,SpringMVC还会完成很多其他的 ...
- SpringMVC 之数据转换和国际化
1. 数据绑定流程 SpringMVC 主框架将 ServletRequest 对象及目标方法的入参实例传递给 WebDataBinderFactory 实例,以创建 DataBinder 实例对象; ...
- Springmvc中ajax与jason应用
Springmvc中ajax与jason应用 相关依赖包 json数据转换的jar包 jackson-annotations-2.5.4 jackson-core-2.5.4 jackson-data ...
- SpringMVC的数据转换&&数据格式化&&数据校验
1 SpringMVC的数据绑定流程 SpringMVC将ServletRequest对象及目标方法的入参实例传递给WebDataBinderFactory实例,以创建DataBinder实例对象. ...
- SpringMvc中的数据校验
SpringMvc中的数据校验 Hibernate校验框架中提供了很多注解的校验,如下: 注解 运行时检查 @AssertFalse 被注解的元素必须为false @AssertTrue 被注解的元素 ...
- 【Spring】SpringMVC中浅析Date类型数据的传递
在控制器中加入如下代码: @InitBinder public void initBinder(ServletRequestDataBinder bin){ SimpleDateFormat sdf ...
- 详解SpringMVC中GET请求
GET请求概述 GET请求,请求的数据会附加在URL之后,以?分割URL和传输数据,多个参数用&连接.URL的编码格式采用的是ASCII编码,而不是uniclde,所有的非ASCII字符都要编 ...
- SpringMVC中使用Interceptor拦截器
SpringMVC 中的Interceptor 拦截器也是相当重要和相当有用的,它的主要作用是拦截用户的请求并进行相应的处理.比如通过它来进行权限验证,或者是来判断用户是否登陆,或者是像12306 那 ...
- 如何在springMVC 中对REST服务使用mockmvc 做测试
如何在springMVC 中对REST服务使用mockmvc 做测试 博客分类: java 基础 springMVCmockMVC单元测试 spring 集成测试中对mock 的集成实在是太棒了!但 ...
随机推荐
- 先装VS2008之后,又装了2013,然后启动VS2008提示“Tools Version”有问题?
这个网上资料一搜很多,我就是按照下面这个链接去解决的,删除 “14.0” 整个键值文件夹之后重启VS2008就好了, 注意:上面第一张图是我在网上找的08和10版本弹出的错误,我自己弹出的是提示14. ...
- .net生成条形码
1..net 标准库(.net standard 2.0) Nuget添加引用:ZXing.Net生成条形码,ZXing.Net.Bindings.ImageSharp生成图片 public stat ...
- UCS2-little endian转码(utf16)
public static void readFile(){ BufferedReader in = null; try { in = new BufferedReader(new InputStre ...
- python 函数中使用全局变量
python 函数中如果需要使用全局变量,需要使用 global + 变量名 进行声明, 如果不声明,那么就是重新定义一个局部变量,并不会改变全局变量的值 n [1]: a = 3 In [2]: d ...
- IntelliJ IDEA优秀插件(编程通用)
一.IntelliJ IDEA开发 最近大部分开发IDE工具都切换到了,所以也花了点心思去找了相关的插件.这里整理的适合各种语言开发的通用插件,也排除掉IntelliJ IDEA自带的常用插件了(有些 ...
- 二:maven构建module
通常情况下,我们一个项目是需要分多个模块的,这是我们用maven管理项目就需要构建一个多模块的项目: 通常的结构是一个模块中有一个主项目,下面包含多个子项目,如果是web项目则子项目中有一个是java ...
- Manjaro Linux执行某些命令缺少libtinfo.so.5问题
Manjaro默认有libtinfo.so.6而没有libtinfo.so.5,软件如果需要可执行以下命令安装: sudo pacman -S ncurses5-compat-libs #或 sudo ...
- 可方便扩展的JIRA Rest Web API的封装调用
JIRA是一个缺陷跟踪管理系统,被广泛应用于缺陷跟踪.客户服务.需求收集.流程审批.任务跟踪.项目跟踪和敏捷管理等工作领域,当我们需要把第三方业务系统集成进来时,可以调用他的API. JIRA本身的A ...
- 本地搭建https服务
首先确保机器上安装了openssl和openssl-devel npm install openssl npm install openssl-devel (安装报错 导致我没安装成功,但是也还是配置 ...
- 使用sqlyog连接到服务器数据库,实现可视化数据操作。(完美解决版。)《亲测!!!!》
服务器中的表 select Host ,User ,Select_priv ,Insert_priv ,Update_priv ,Delete_priv ,Create_priv ,Drop_pr ...