springmvc的类型转换
默认情况下,springmvc内置的类型转换器只能
将“yyyy/MM/dd”类型的字符串转换为Date类型的日期
情境一:
而现在我们无法得知用
户会输入什么日期格式的数据,所以,内置的类型转换器无法转换其他日期格式的类型
为了方便程序,减少代码量,我们抽离出自己的类型转换器
此种方法也有弊端,就是讲几个类唯一的继承权用在了类型转换器上,但也是没有办法的办法
步骤一:
定义自己的类型转换器 继承一个父接口 Converter<S, T>
s:代表源数据类型
T:代表目标数据类型
package cn.hmy.convertion;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Pattern;
import org.springframework.core.convert.converter.Converter;
public class MyConvertion implements Converter<String, Date>{
public Date convert(String source) {
/*SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");*/
SimpleDateFormat sdf=getDateFormat(source);
try {
return sdf.parse(source);
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
private SimpleDateFormat getDateFormat(String source) {
//进行正则匹配
//2016-12-14
//2016/12/14
//20161214
if(Pattern.matches("^\\d{4}-\\d{2}-\\d{2}$", source)){
return new SimpleDateFormat("yyyy-MM-dd");
}else if(Pattern.matches("^\\d{4}/\\d{2}/\\d{2}$", source)){
return new SimpleDateFormat("yyyy/MM/dd");
}else if(Pattern.matches("^\\d{4}\\d{2}\\d{2}$", source)){
return new SimpleDateFormat("yyyyMMdd");
}else if(Pattern.matches("^\\d{4}年\\d{2}月\\d{2}日$", source)){
return new SimpleDateFormat("yyyy年MM月dd日");
}
return null;
}
}
步骤二、在配置文件中注册自定义类型转化器,将该类交由spring容器管理
<!-- 01.注册自定义的类型转换器 -->
<bean id="myConvertion" class="cn.hmy.convertion.MyConvertion"></bean>
<!--02.注册类型转换器的服务工厂 产生转换对象 -->
<bean id="convertionservice" class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters" ref="myConvertion"></property>
</bean>
<!--03. -->
<mvc:annotation-driven conversion-service="convertionservice"/>
配置完成
情景二:
当我们在前台输入如下信息 ,年龄为string不能装配成后台的int类型转向400错误页面,
面对这种情况我们更想看到的是回到初始页面
解决方案:这种情况就是出现了类型转换异常
我们就采用异常处理机制,其实再出现类型转换异常时,请求就不会再进入处理器方法,而是被我们自定的的异常处理方法所捕获
在处理器类中加入异常处理方法,完成重定向的功能
//当出现类型转换异常时,跳回index.jsp
@ExceptionHandler(TypeMismatchException.class)
public ModelAndView getBack(HttpServletRequest request,Exception ex){
ModelAndView mv=new ModelAndView();
mv.setViewName("/index.jsp");
return mv;
}
情景三:
完成上述操作后,我们现在再来思考一个问题,如果表单上有很多条数据,用户提交失败,重定向后之前所填的数据完全丢失,那用户的内心估计是崩溃的
这是我们就应该来考虑“数据回显”的问题了,最好,我们可以提示出那条数据出错了
下面我们就重新优化异常处理机制
ex.getMessage().contains(birthday)
//当出现类型转换异常时,跳回index.jsp
@ExceptionHandler(TypeMismatchException.class)
public ModelAndView getBack(HttpServletRequest request,Exception ex){
ModelAndView mv=new ModelAndView();
String birthday=request.getParameter("birthday");
String age=request.getParameter("age");
mv.addObject("birthday",birthday);
mv.addObject("age",age);
if(ex.getMessage().contains(birthday)){
mv.addObject("birthdayerror","日期格式不正确");
}
if(ex.getMessage().contains(age)){
mv.addObject("ageerror","年龄格式不正确");
}
mv.setViewName("/index.jsp");
return mv;
}
到此我们的类型转换已经结束