springMVC数据格式化

本文详细介绍了如何在SpringMVC框架中实现日期格式化,包括实体类中使用@DateTimeFormat注解指定日期格式,以及在控制器中处理日期格式异常,确保数据正确性和用户体验。

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";
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值