Spring中的转换器:Converter

配置spring的配置文件:

 1 <bean id="conversionService"
 2         class="org.springframework.context.support.ConversionServiceFactoryBean">
 3         <property name="converters">
 4             <list>
 5                 <bean class="app06a.converter.StringToDateConverter">
 6                     <constructor-arg type="java.lang.String" value="MM-dd-yyyy"/>
 7                 </bean>
 8             </list>
 9         </property>
10     </bean>
11     <mvc:annotation-driven conversion-service="conversionService"/>

这样配置好了之后,就可以创建一个Converter的装换器类来写一个转换器的实现。这里我们写的转换器是把String类型转换为Date类型的。日期格式为value后面的。

 1 public class StringToDateConverter implements Converter<String,Date>{
 2     private String datePattern;
 3     public StringToDateConverter(String datePattern){
 4         this.datePattern=datePattern;
 5         System.out.println("instiating"+datePattern);
 6     }
 7     @Override
 8     public Date convert(String s) {
 9         SimpleDateFormat dateformat=new SimpleDateFormat();
10         dateformat.setLenient(false);
11         try {
12             return dateformat.parse(s);
13         } catch (ParseException e) {
14             throw new IllegalArgumentException("invailed date"+datePattern+"\"");
15         }
16     }
17 }

然后实现了Converer<S,T>接口。

这样,若是日期输入错误,则会返回之前输入的页面,页面上也会出现提示:

 1 @RequestMapping(value="/employee_input")
 2     public String inputEmployee(Model model){
 3         model.addAttribute("employee",new Employee());
 4         return "EmployeeForm";
 5     }
 6     
 7     @RequestMapping(value="/employee_save")
 8     public String saveEmployee(@ModelAttribute Employee employee,BindingResult bindresult,Model model){
 9         if(bindresult.hasErrors()){
10             FieldError fielderror=bindresult.getFieldError();
11             return "EmployeeForm";
12         }
13         model.addAttribute("employee",employee);
14         return "EmployeeDetails";
15     }

 

==========================================================

转载于:https://www.cnblogs.com/Summer7C/p/4719802.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值