1. 程式人生 > >SpringMVC(十四)類型轉換器

SpringMVC(十四)類型轉換器

har public property springmvc gpo source 表達 resolv obj

為什麽頁面上輸入‘12’,可以復制給Handler方法對應的參數?

和是因為類型轉換器並不是可以將用戶提交的String,轉換為用戶需要的所有類型,此時,就需要自定義類型轉換器可

案例:自定義日期類型轉換器 要求格式:yyyy/MM/dd

頁面上:

<%--
  Created by IntelliJ IDEA.
  User: mycom
  Date: 2018/3/26
  Time: 11:57
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="
text/html;charset=UTF-8" language="java" isELIgnored="false" %> <html> <head> <title>Title</title> </head> <body> <h2>登錄</h2> <form action="${pageContext.request.contextPath}/first" method="post"> 用戶名:<input type="text" name="name" value="
${name}"/> 年齡:<input type="text" name="age" value="${age}"/> 出生日期:<input type="text" name="birthday"/> <input type="submit" value="提交"> </form> </body> </html>

控制器類

package demo16TypeConverter;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/** * Created by mycom on 2018/3/30. */ @Controller public class TypeController { @ExceptionHandler public ModelAndView doSome(Exception ex, HttpServletRequest request){ ModelAndView mv=new ModelAndView(); mv.addObject("name",request.getAttribute("name")); mv.setViewName("login"); mv.addObject("ex",ex);//保存的數據,在頁面上用EL表達式展示錯誤信息 //判斷異常類型 if(ex instanceof NameException){ mv.setViewName("nameException"); } if(ex instanceof AgeException){ mv.setViewName("ageException"); } return mv; } @RequestMapping("/first") public String doFirst(String name, int age, Date birthday){ System.out.println(name); System.out.println(age); System.out.println(birthday); return "success"; } }

配置文件中

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <context:component-scan base-package="demo16TypeConverter"></context:component-scan>

    <!--視圖解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/error/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>

    <!--配置自定義的轉換器-->
    <bean id="MyConverter" class="demo16TypeConverter.MyConverter"></bean>

    <!--註冊一個轉換器-->
    <bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
        <property name="converters" ref="MyConverter"></property>
    </bean>

    <!--註解驅動-->
    <mvc:annotation-driven conversion-service="conversionService"></mvc:annotation-driven>




</beans>

自定義類型轉化器

package demo16TypeConverter;

import org.springframework.core.convert.converter.Converter;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Pattern;

/**
 * Created by mycom on 2018/3/30.
 */
public class MyConverter implements Converter<String,Date> {

    public Date convert(String str) {
        SimpleDateFormat sdf=getConverter(str);
        try {
            Date date=sdf.parse(str);
            return date;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    private SimpleDateFormat getConverter(String str) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
     //匹配不同的格式
if(Pattern.matches("^\\d{4}-\\d{2}-\\d{2}$",str)){ sdf = new SimpleDateFormat("yyyy-MM-dd"); }else if(Pattern.matches("^\\d{4}/\\d{2}/\\d{2}$",str)){ sdf = new SimpleDateFormat("yyyy/MM/dd"); }else if(Pattern.matches("^\\d{4}\\d{2}\\d{2}$",str)){ sdf = new SimpleDateFormat("yyyyMMdd"); } return sdf; } }

配置文件和頁面還是使用的上面的一種

SpringMVC(十四)類型轉換器