<?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:context="http://www.springframework.org/schema/context"xmlns:mvc="http://www.springframework.org/schema/mvc"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd"><context:component-scan base-package="com.chentianyu.controller" /><bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"><property name="prefix" value="/admin/" /><property name="suffix" value=".jsp" /></bean><mvc:default-servlet-handler /><mvc:annotation-driven /><!--ajax和日期都要用它--></beans>
你不知道用户会输入什么样子的,所以我们可以限制选择
<form action="${pageContext.request.contextPath}/myDate">
日期:<input type="date" name="myDate" /><br>
<input type="submit" value="提交">
</form>
package com.chentianyu.controller;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.Date;
@Controller
public class MyDateAction {
/**
* 日期:<input type="date" name="myDate" /><br>
* @return
*/
@RequestMapping("/myDate")
public String myDate(@DateTimeFormat(pattern = "yyyy-MM-dd"/*将字符串转为日期注入进去*/) Date myDate){
System.out.println(myDate);
return "show";
}
}
使用格式刷
package com.chentianyu.controller;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import java.text.SimpleDateFormat;
import java.util.Date;
@Controller
public class MyDateAction {
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
/**
* 日期:<input type="date" name="myDate" /><br>
* @return
*/
@RequestMapping("/myDate")
public String myDate(@DateTimeFormat(pattern = "yyyy-MM-dd"/*将字符串转为日期注入进去*/) Date myDate){
System.out.println(myDate);
System.out.println(sf.format(myDate));
return "show";
}
}
package com.chentianyu.controller;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import java.text.SimpleDateFormat;
import java.util.Date;
@Controller
public class MyDateAction {
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
/**
* 日期:<input type="date" name="myDate" /><br>
* @return
*/
@RequestMapping("/myDate")
public String myDate(@DateTimeFormat(pattern = "yyyy-MM-dd"/*将字符串转为日期注入进去*/) Date myDate){
System.out.println(myDate);
System.out.println(sf.format(myDate));
return "show";
}
}
这种写法的弊端:注入多个日期就得重复的使用**@DateTimeFormat(pattern = "yyyy-MM-dd")**,我们希望有个全局的代码:所有的日期全都自动转化
