【SpringMVC】数据类型转换以及Spring编码过滤器

当我们提交表单时,需要使用日期时,SpringMVC能否直接将Sring类型转换为Date类型呢?

答案是不能的,所以我们需要去实现类型转换

首先我们创建index.jsp写好表单

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>表单提交</title>
  </head>
  <body>
  		<form action="${pageContext.request.contextPath}/add.action" method="POST">
		<table border="2" align="center">
			<tr>
				<th>姓名</th>
				<td><input type="text" name="username"/></td>				
			</tr>
			<tr>
				<th>性别</th>
				<td>
					<input type="radio" name="gender" value="男"/>男
					<input type="radio" name="gender" value="女" checked/>女
				</td>	
			</tr>
			<tr>
				<th>入职时间</th>
				<td>
					<input type="text" name="hiredate" value="2017-11-25"/>
				</td>				
			</tr>
			<tr>
				<td colspan="2" align="center">
					<input type="submit" value="提交"/>
				</td>
			</tr>
		</table>
	</form>
  		
  </body>
</html>


配置好web.xml,在这配置两个,一个注册SpringMVC核心控制器,另一个设置Spring编码过滤器

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
	<!-- 注册SpringMVC框架核心控制器 -->
	<servlet>
		<!-- 默认去WEB-INF下面找DispatcherServlet-servlet.xml文件 -->
		<servlet-name>DispatcherServlet</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<!-- 通知DispatcherServlet去指定的目录下加载springmvc.xml配置文件 -->
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:springmvc.xml</param-value>
		</init-param>
	</servlet>
	
	<servlet-mapping>
		<servlet-name>DispatcherServlet</servlet-name>
		<url-pattern>*.action</url-pattern>
	</servlet-mapping>
	
	<!-- 设置SpringMVC编码过滤器 -->
	<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>
	

</web-app>

然后在springmvc-test3.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:context="http://www.springframework.org/schema/context"
      xmlns:aop="http://www.springframework.org/schema/aop"
      xmlns:tx="http://www.springframework.org/schema/tx"
	  xmlns:mvc="http://www.springframework.org/schema/mvc"
		
      xsi:schemaLocation="
	
	  http://www.springframework.org/schema/beans 
	  http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
	  
	  http://www.springframework.org/schema/context
      http://www.springframework.org/schema/context/spring-context-3.0.xsd
 	  
	  http://www.springframework.org/schema/aop 
	  http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
	  
	  http://www.springframework.org/schema/tx
      http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
    
      http://www.springframework.org/schema/mvc
      http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
        
      ">
		
		<!-- 注册Action -->
		<bean name="/add.action" class="cn.qblank.date.EmpAction"></bean> 
		<!-- 映射器 -->
		<bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"></bean>
      
</beans>

然后写好对应的EmpAction类继承AbstractCommandController

@SuppressWarnings("deprecation")
public class EmpAction extends AbstractCommandController{
	//org.springframework.web.servlet.mvc.AbstractCommandController能够以实体的形式,收集客户端参数
	public EmpAction(){
		//将表单参数封装进去
		this.setCommandClass(Emp.class);
	}
	
	/**
	 * 自定义类型转换器,将String->Date类型(格式yyyy-MM-dd)
	 */
	@Override
	protected void initBinder(HttpServletRequest request,
			ServletRequestDataBinder binder) throws Exception {
		//向springmvc内部注入一个自定义的类型转换器
		//参数一:将String转成什么类型的字节码
		//参数二:自定义转换规则
		//true表示该日期字段可以为空
		binder.registerCustomEditor(Date.class, 
				new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true));
	}
	/**
	 * obj表示封装后的实体
	 * error表示封装时产生的异常
	 */
	@Override
	protected ModelAndView handle(HttpServletRequest request,
			HttpServletResponse response, Object obj, BindException error)
			throws Exception {
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.addObject("message","添加成功");
		Emp emp = (Emp) obj;
		System.out.println(emp.getUsername()+":" + emp.getGender()+":" + emp.getHiredate().toLocaleString());
		//将对象封转到ModelAndView中
		modelAndView.addObject("emp",emp);
		//设置跳转页面
		modelAndView.setViewName("/jsp/success.jsp");
		return modelAndView;
	}
	
}


然后在success.jsp中显示表单数据

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib prefix="f" uri="http://java.sun.com/jsp/jstl/fmt" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>成功页面</title>
  </head>
  
  <body>
  		<h3>成功</h3>
  		${message}
  		${emp.username}
  		${emp.gender}
  		<!-- 
			1)fmt:formatDate 来源于 http://java.sun.com/jsp/jstl/fmt
			2)fmt:formatDate作用是格式化日期的显示,例如:2015年5月10日 星期日
			3)value表示需要格式化的值
			4)type表示显示日期,时间,都显示
			  type=date表示只显示日期
			  type=time表示只显示时间
			  type=both表示日期时间均显示
			5)dateStyle表示显示日期的格式:short/medium/default/long/full
		-->
  		<f:formatDate 
  			value="${emp.hiredate}"
  			type="date"
  			dateStyle="full"
  		/>
  </body>
</html>



最后注意在主文件springmvc.xml中引入子文件

<import resource="cn/qblank/date/springmvc-test3.xml"/>


结果如下:





  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值