SpringMVC(十五)InitBinder

InitBinder  也是可以作为日期转化的一种手段,他是面向局部的

定义一个类

package demo17InitBinder;

import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by mycom on 2018/3/31.
 */
@Controller
public class FirstController {


    /*这个方法是用来处理指定属性的格式的,也可以不指定属性,不指定的话就是对所有属性都要匹配一次
    * 比如:现在有三个属性,那么这个方法没有指定那个属性,这个方法就会走三次
    * */
    @InitBinder("birthday")
    public void initBinder(WebDataBinder binder){
        /*指定一种格式是正确的*/
        DateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        //用WebDataBinder类中的registerCustomEditor方法将格式进行绑定,并允许为空
        binder.registerCustomEditor(Date.class,new CustomDateEditor(sdf,true));
    }

    @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="demo17InitBinder"></context:component-scan>

    <!--视图解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/error/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>
    <!--注解驱动-->
    <mvc:annotation-driven></mvc:annotation-driven>



</beans>

页面上

<%--
  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}/second" 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>

成功页面

<%--
  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>
  ${username}登录成功!
</body>
</html>

还有一种方式是自定义的的属性编辑器 需要继承一个类   PropertiesEditor

那么再定义一个类

package demo17InitBinder;

import org.springframework.beans.propertyeditors.PropertiesEditor;

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

/**
 * Created by mycom on 2018/3/31.
 */
public class MyDateEditor  extends PropertiesEditor {
    /**
     * 重写方法
     * @param str  从网页上传过来的参数,判断他是否符合要求
     * @throws IllegalArgumentException
     */
    @Override
    public void setAsText(String str) throws IllegalArgumentException {
        /*使用一个方法定义几种格式*/
        SimpleDateFormat sdf=getDate(str);
        /*声明一个空的日期变量*/
        Date date=null;
        try {
            /*将传过来的参数转成日期类型*/
            date=sdf.parse(str);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        setValue(date);
    }
    
    /*
    * 定义参数的格式
    * */
    private SimpleDateFormat getDate(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;
    }
}

在控制器中

package demo17InitBinder;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;



/**
 * Created by mycom on 2018/3/31.
 */
@Controller
public class MultiController {

    @InitBinder("birthday")
    public void initBinder(WebDataBinder binder){
        System.out.println("1111111111");
        DateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        /*在这里传入的参数发生了改变,第二个参数是new 一个我们自己定义的类*/
        binder.registerCustomEditor(Date.class,new MyDateEditor());
    }

    @RequestMapping("/second")
    public String doFirst(String name, int age, Date birthday){
        System.out.println("wwqeeqweqqqqqqqqqqqqq");
        System.out.println(name);
        System.out.println(age);
        System.out.println(birthday);
        return "success";
    }
}

页面和配置文件不变还是第一种的那个

posted @ 2018-03-31 22:40  明渃筱曦  阅读(193)  评论(0)    收藏  举报