• Spring MVC 之类型转换(五)


    虽然SpringMVC可以自动绑定多种数据类型,但是有时候有些特殊的数据类型还是会在绑定时发生错误,需要我们自己书写类型转换完成绑定。

    SpringMVC中提供两种绑定方式:以时间转换为例

    1、属性编辑器(传统方式)

    控制器:

     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()定义自己的转换规则

     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 }

    2、类型转换器

    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 }

    类型转换器需要在配置文件中配置:

     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页面:

     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>

    结果显示:

  • 相关阅读:
    发送电子邮件smtplib 摩天居士
    echarts 社区
    echarts 重复渲染警告 There is a chart instance already initialized on the dom
    EasyNVR平台视频流在iOS端显示黑屏,无法正常播放是什么原因?
    EasyNVS云管理平台功能重构:支持新增用户、修改信息等
    EasyNVR平台设备通道均在线,操作出现“网络请求失败”是什么原因?
    EasyNVR前端打包UglifyJsPlugin报错优化
    记录 mysqld 已停止工作 报错情况解决(删除.err文件)
    Fdmemtable 内存表保存图片的例子
    P4769[NOI2018]冒泡排序【组合数学,树状数组】
  • 原文地址:https://www.cnblogs.com/hellokitty1/p/5167125.html
Copyright © 2020-2023  润新知