------------吾亦无他,唯手熟尔,谦卑若愚,好学若饥-------------
之前博客的配置日期类型转换器,他是全局的,如果只是一个处理器中使用怎么办?
引出@InitBinder注解
案例:
1.在处理器中:
package cn.dawn.day22initbinder; 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.SimpleDateFormat; import java.util.Date; /** * Created by Dawn on 2018/3/31. */ @Controller public class FirstController { /*第一种*/ /*@InitBinder*/ /*第二种*/ @InitBinder("birthday") public void initBinder(WebDataBinder binder){ System.out.println("1111111111"); SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd"); binder.registerCustomEditor(Date.class,new CustomDateEditor(sdf,true)); } /*initbinder*/ @RequestMapping("/initbinderFirst") public String initbinderFirst(String username, Integer userage, Date birthday) throws Exception { System.out.println("2222222222"); System.out.println(username); System.out.println(userage); System.out.println(birthday); return "success"; } }
此处需要重点解释一波,这样就可以日期类型转换器变成局部的了,俩个方法执行顺序正如输出的那样一个是1,一个是2,@InitBinder注解它加参数是说只匹配birthday,如果不加,下面那个方法有三个参数,上面的方法就执行三次,System.out.print("11111111")三次
2.自己的xml配置文件:
<?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="cn.dawn.day22initbinder"></context:component-scan> <!--视图解析器--> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/day22/"></property> <property name="suffix" value=".jsp"></property> </bean> </beans>
3.修改web.xml配置文件的中央调度器的上下问配置位置为上面的那个xml
4.jsp页面:
4.1login.jsp
<%@ page pageEncoding="UTF-8" contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %> <html> <head> <title>Title</title> </head> <body> <h2>登录</h2> <form action="${pageContext.request.contextPath}/initbinderFirst" method="post"> 用户名:<input name="username" value="${username}"> 年龄:<input name="userage"> 生日:<input name="birthday"> <input type="submit" value="登录"/> </form> </body> </html>
4.2success.jsp页面
<%@ page language="java" pageEncoding="utf-8" isELIgnored="false" %> <html> <body> <%--<img src="image/1.jpg">--%> <h2>Success!</h2> </body> </html>
5.启动tomcat,访问login.jsp,发现只有yyyy-MM-dd可以转换成功,说明它已经和springmvc默认的不同了,同样的问题,兼容性不好,所以,下一篇博客为大家做进一步的优化