Spring MVC 之類型轉換(五)

雖然SpringMVC能夠自動綁定多種數據類型,可是有時候有些特殊的數據類型仍是會在綁定時發生錯誤,須要咱們本身書寫類型轉換完成綁定。javascript

SpringMVC中提供兩種綁定方式: 以時間轉換爲例

一、屬性編輯器(傳統方式)html

控制器:java

 1 @RequestMapping(value="/login.do")
 2     public String login(UserBean user){
 3         log.info(user.getUsername());
 4         log.info(user.getBirthday());
 5         return "index";
 6     }
 7  // 自定義一個屬性編輯器,用於轉換時間類型
 8 @InitBinder
 9     public void converterStringDate(WebDataBinder  binder){
10         binder.registerCustomEditor(Date.class, new DateEditor());
11     } 

能夠經過重寫PropertyEditorSupport中的setAsText()定義本身的轉換規則jquery

 1 package com.cy.springannotation.controller;
 2 
 3 import java.beans.PropertyEditorSupport;
 4 import java.text.ParseException;
 5 import java.text.SimpleDateFormat;
 6 import java.util.Date;
 7 
 8 public class DateEditor extends PropertyEditorSupport {
 9     
10     @Override
11     public void setAsText(String text) throws IllegalArgumentException {
12                 Date date = null;
13                 try {
14                     if(text.contains("-")){
15                         SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
16                         date = sf.parse(text);
17                     }else {
18                         SimpleDateFormat sf = new SimpleDateFormat("dd/MM/yyyy");
19                         date = sf.parse(text);
20                     }
21                 } catch (ParseException e) {
22                     e.printStackTrace();
23                 }
24                 this.setValue(date);
25     }
26 
27 }

二、類型轉換器spring

Converter是Spring3提供的新的類型轉換,相對於屬性轉換器更強大,能夠把任意類型轉換,而不是侷限於String類型。
 
控制器:
1 @RequestMapping(value="/login.do")
2     public String login(UserBean user){
3         log.info(user.getUsername());
4         log.info(user.getBirthday());
5         return "index";
6     }
7      

 

全局類型轉換器
 1 package com.cy.springannotation.controller;
 2 
 3 import java.text.ParseException;
 4 import java.text.SimpleDateFormat;
 5 import java.util.Date;
 6 
 7 import org.springframework.core.convert.converter.Converter;
 8 /**
 9  * 全局類型轉換器
10  * @author acer
11  *
12  */
13 public class DateConvert  implements Converter<String, Date>{
14     @Override
15     public Date convert(String text) {
16         Date date = null;
17         try {
18             if(text.contains("-")){
19                 SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
20                 date = sf.parse(text);
21             }else {
22                 SimpleDateFormat sf = new SimpleDateFormat("dd/MM/yyyy");
23                 date = sf.parse(text);
24             }
25             
26         } catch (ParseException e) {
27             e.printStackTrace();
28         }
29         return date;
30     }
31 
32 }

類型轉換器須要在配置文件中配置:mvc

 1 <!--開啓註解  -->    
 2 <mvc:annotation-driven conversion-service="tc" />
 3 
 4 <!--類型轉換器工廠  -->
 5 
 6 <bean id="tc" class="org.springframework.context.support.ConversionServiceFactoryBean">
 7     <property name="converters">
 8         <list>
 9             <bean class="com.cy.springannotation.controller.DateConvert" />
10         </list>
11     </property>
12 </bean>

 

 

共同的jsp頁面:app

 1 <%@ page language="java" import="java.util.*" pageEncoding="utf-8" contentType="text/html; charset=utf-8"%>
 2 <%
 3 String path = request.getContextPath();
 4 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
 5 %>
 6 
 7 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
 8 <html>
 9   <head>
10     <base href="<%=basePath%>">
11     <title>登陸頁面</title>
12    <script type="text/javascript" src="<%=basePath%>js/jquery-2.1.4.js"></script>
13    <script type="text/javascript">
14      
15    
16    </script>
17   </head>
18   <body>
19   <form action="login.do" method="post">
20     <table>
21        <tr>
22            <td>用戶名:</td>
23            <td><input type="text" name="username"/></td>
24        </tr>
25        <tr>
26            <td>出生日期</td>
27            <td><input type="text" name="birthday"/></td>
28        </tr>
29        <tr>
30            <td colspan="2"> <input type="submit" value="提交"/> </td>
31        </tr>
32     </table>
33   </form>
34   </body>
35 </html>

 

結果顯示:jsp

相關文章
相關標籤/搜索