1)日期的提交处理
<h1>日期</h1><br>
<form action="${pageContext.request.contextPath}/date.action">
日期<input type="date" name="myDate"><br>
<input type="submit" value="提交">
</form>
A.单个日期处理
要使用注解@DateTimeFormat,此注解必须搭配springmvc.xml文件中的mvc:annotationdriven标签
<!-- 注解驱动-->
<mvc:annotation-driven></mvc:annotation-driven>
@RequestMapping("/date.action")
public String date(
@DateTimeFormat(pattern = "yyyy-MM-dd")
Date myDate){
SimpleDateFormat sdf = new SimpleDateFormat();
String date = sdf.format(myDate);
System.out.println(date);
return "main";
}
B.类中全局日期处理
注册一个注解,用来解析本类中所有的日期类型,自动转换.
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
@InitBinder
public void initBinder(WebDataBinder dataBinder){
dataBinder.registerCustomEditor(Date.class, new CustomDateEditor(sdf, true));
}
@RequestMapping("/date.action")
public String date(Date myDate){
System.out.println(sdf.format(myDate));
return "main";
}
2)日期的显示处理
在页面上显示好看的日期,必须使用JSTL.
步骤:
A)添加依赖jstl
<dependency>
<groupId>org.glassfish.web</groupId>
<artifactId>jakarta.servlet.jsp.jstl</artifactId>
<version>2.0.0</version>
</dependency>
<dependency>
<groupId>jakarta.servlet.jsp.jstl</groupId>
<artifactId>jakarta.servlet.jsp.jstl-api</artifactId>
<version>2.0.0</version>
</dependency>
B)在页面上导入标签库
如果是单个日期对象,直接转为好看的格式化的字符串进行显示.
如果是list中的实体类对象的成员变量是日期类型,则必须使用jstl进行显示.
<%--导入jstl核心标签库--%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--导入jstl格式化标签库--%>
<%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%--引入jstl核心标签库--%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--引入jstl格式化标签库--%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<h1>单个日期信息</h1>
${date}
<h1>学生信息</h1>
<table width="500px" border="1">
<tr>
<th>姓名</th>
<th>生日</th>
</tr>
<c:forEach items="${stuList}" var="stu">
<tr>
<td>${stu.name}</td>
<td><fmt:formatDate value="${stu.birthday}" pattern="yyyy-MM-dd"></fmt:formatDate></td>
</tr>
</c:forEach>
</table>
C)使用标签显示数据
姓名 | 生日 |
---|---|
${stu.name} | ${stu.birthday}------ |