Springmvc入门(五)数据验证以及转发和重定向

作为登录页面,注册页面这种具备表单信息提交的内容,都需要经过验证,判断,以往手工if,else判断用户是不是输出了密码等内容,当然前端也会进行用户输入的判断。

字符格式转换,比如日期输出格式转为YYYY-MM-DD,以及数字转换,百分数,货币等。

@NumberFormat(style = Style.NUMBER)注解 ,字符转换 Style.NUMBER数字,Style.CURRENCY货币,Style.PERCENT百分数

@DateTimeFormat(pattern = "YYYY-MM-DD HH:mm:DD")字符串的格式

虽然spring只有这两个转换的,但是hibernate Validator 提供了 JSR 303 规范中所有内置 constraint 的实现,除此之外还有一些附加的 constraint。

@Valid    被注释的元素是一个对象,需要检查此对象的所有字段值
@Null    被注释的元素必须为 null
@NotNull    被注释的元素必须不为 null
@AssertTrue    被注释的元素必须为 true
@AssertFalse    被注释的元素必须为 false
@Min(value)    被注释的元素必须是一个数字,其值必须大于等于指定的最小值
@Max(value)    被注释的元素必须是一个数字,其值必须小于等于指定的最大值
@DecimalMin(value)    被注释的元素必须是一个数字,其值必须大于等于指定的最小值
@DecimalMax(value)    被注释的元素必须是一个数字,其值必须小于等于指定的最大值
@Size(max, min)    被注释的元素的大小必须在指定的范围内
@Digits (integer, fraction)    被注释的元素必须是一个数字,其值必须在可接受的范围内
@Past    被注释的元素必须是一个过去的日期
@Future    被注释的元素必须是一个将来的日期
@Pattern(value)    被注释的元素必须符合指定的正则表达式


修改pojo类,对pojo类的属性进行一些必要的验证


import java.util.Date;

import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.format.annotation.NumberFormat;
import org.springframework.format.annotation.NumberFormat.Style;

public class User {
	
	@NotNull(message="id不能为空") //message的内容就是当出现为空的时候输出的错误信息
	@NumberFormat(style = Style.PERCENT)
	private Integer id;
	@NotNull(message="password不能为空")
	private String password;
	@DateTimeFormat(pattern = "YYYY-MM-DD HH:mm:DD")
	private Date date;

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public Date getDate() {
		return date;
	}

	public void setDate(Date date) {
		this.date = date;
	}

	@Override
	public String toString() {
		return "User [id=" + id + ", password=" + password + "]";
	}

}

修改登录的请求方法

        @RequestMapping(value = "/login", method = RequestMethod.POST)
	public String loginAction(@Validated User user,BindingResult bindingResult) {
		if(bindingResult.hasErrors()) {
			System.out.println(bindingResult.getFieldError());//验证有错误就输出错误信息
			return "forward:/register.jsp";
		}
		return "success";
	}

forward:转发,springmvc默认请求方法处理完都是转发到页面。

重定向:redirect 

        @RequestMapping("/testRedirect")
	public String testRedirect() {
		return "redirect:/index.jsp";
	}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值