xml配置
<bean class="org.springframework.format.support.FormattingConversionServiceFactoryBean"></bean>
实体类
@Component
public class User {
public User(String name, String pass) {
super();
this.name = name;
this.pass = pass;
}
public User() {
super();
}
private String name;
private String pass;
//要求输入的格式
@DateTimeFormat(pattern ="yyyy/mm/dd")
private Date birthday;
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPass() {
return pass;
}
public void setPass(String pass) {
this.pass = pass;
}
}
jsp页面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib prefix="from" uri="http://www.springframework.org/tags/form"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<from:form action="dateformat" method="post" commandName="user">
用户名:<from:input path="name"/>
<br/>
密码:<from:password path="pass"/>
<br/>
时间:<from:input path="birthday"/>
<br/>
<input type="submit" value="确认"/>
</from:form>
</body>
</html>
控制器
@Controller
public class DateFormatcontroller {
@RequestMapping(value = "/dateformat",method = RequestMethod.GET)
public String FormatDate(Map<String,Object> map) {
map.put("user",new User());
return "fomat";
}
@RequestMapping(value = "/dateformat",method = RequestMethod.POST)
public String FormatDates(User user) {
System.out.println(user.getBirthday());
return "hello";
}
}
birthday的输入格式是yyyy/mm/dd如果输入的不是这个格式,那么会报400错误,想要解决这个,就在控制器中添加
@Controller
public class DateFormatcontroller {
@RequestMapping(value = "/dateformat",method = RequestMethod.GET)
public String FormatDate(Map<String,Object> map) {
map.put("user",new User());
return "fomat";
}
@RequestMapping(value = "/dateformat",method = RequestMethod.POST)
public String FormatDates(User user,BindingResult result) {
//相当于一个try_catch将异常捕获
if(result.getErrorCount()>0) {
for (ObjectError error: result.getAllErrors()) {
System.out.println(error.getObjectName() + ":" + error.getCode()+ "-->" + error.getDefaultMessage());
}
System.out.println(user.getBirthday());
}
return "hello";
}
}
本文详细介绍了如何在SpringMVC框架中实现日期格式化,包括实体类中使用@DateTimeFormat注解指定日期格式,以及在控制器中处理日期格式异常,确保数据正确性和用户体验。
515

被折叠的 条评论
为什么被折叠?



