zoukankan      html  css  js  c++  java
  • 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     }

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

    欢迎各位转载。 注意:转载请注明出处。
  • 相关阅读:
    rabbitmqctl常用命令-3
    Count and Say
    Spiral Matrix II
    Minimum Path Sum
    Plus One
    Rotate Image
    Permutations
    Search a 2D Matrix
    Binary Tree Level Order Traversal II
    Binary Tree Level Order Traversal
  • 原文地址:https://www.cnblogs.com/Summer7C/p/4719802.html
Copyright © 2011-2022 走看看