首页 > 编程语言 > 详细

SpringMVC(十四)类型转换器

时间:2018-03-31 23:03:57      阅读:266      评论:0      收藏:0      [点我收藏+]

为什么页面上输入‘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(十四)类型转换器

原文:https://www.cnblogs.com/my-123/p/8681637.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!