如果你是使用
@RequestMapping("/myDate")public String myDate(Date myDate, HttpServletRequest request){System.out.println(myDate);System.out.println(sf.format(myDate));request.setAttribute("mydate",sf.format(myDate));return "show";}
的话取出来显示的不再是日期,而是字符串,虽然简单而且好看,但是你改变了日期的类型
实体类
package com.chentianyu.pojo;import java.util.Date;public class Student {private String name;private Date birthday;public Student() {}public Student(String name, Date birthday) {this.name = name;this.birthday = birthday;}public String getName() {return name;}public void setName(String name) {this.name = name;}public Date getBirthday() {return birthday;}public void setBirthday(Date birthday) {this.birthday = birthday;}@Overridepublic String toString() {return "Student{" +"name='" + name + '\'' +", birthday=" + birthday +'}';}}
<%@ page contentType="text/html;charset=UTF-8" language="java" %><html><head><title>Title</title></head><body><a href="${pageContext.request.contextPath}/list">显示集合中对象的日期成员</a></body></html>
package com.chentianyu.controller;
import com.chentianyu.pojo.Student;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
@Controller
public class MyDateAction {
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
@RequestMapping("/list")
public String list(HttpServletRequest request) throws ParseException {
Student stu1 = new Student("张三",sf.parse("2000-10-01"));
Student stu2 = new Student("李四",sf.parse("2000-08-08"));
Student stu3 = new Student("王五",sf.parse("2000-11-11"));
List<Student> list = new ArrayList<>();
list.add(stu1);
list.add(stu2);
list.add(stu3);
request.setAttribute("list",list);
return "show";
}
}
循环遍历,我们都需要jstl,jstl依赖
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2022/4/26
Time: 17:38
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%--导入jstl核心标签库--%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--导入jstl格式化标签库--%>
<%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<html>
<head>
<title>show页面</title>
</head>
<body>
<%-- <p>单个日期显示:${myDate}</p>--%>
<table width="800px" border="1">
<tr>
<th>姓名</th>
<th>生日</th>
</tr>
<c:forEach items="${list}" var="stu">
<tr>
<td>${stu.name}</td>
<td>${stu.birthday}</td>
</tr>
</c:forEach>
</table>
</body>
</html>
看看能不能做日期的显示:
能不能显示的好看一点,比如显示的是年月日
<td>${stu.birthday}--<fmt:formatDate value="${stu.birthday}" pattern="yyyy-MM-dd"></fmt:formatDate> </td>
这样就可以显示出来
