springMVC——数据校验(后台校验 hibernate validate).
Posted zjc364259451
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了springMVC——数据校验(后台校验 hibernate validate).相关的知识,希望对你有一定的参考价值。
数据校验(后台校验 hibernate validate)
1、首先要导入jar包
2、在相应的实体类中加入注解
package com.zhiyou100.zjc.bean; import javax.validation.constraints.Pattern; import org.hibernate.validator.constraints.Length; import org.hibernate.validator.constraints.NotEmpty; public class User @NotEmpty(message = "用户名不为空") private String username; @Length(min = 6,max = 18,message = "密码长度在6~18之间") private String password; @Pattern(regexp = "/^1([38][0-9]|4[579]|5[0-3,5-9]|6[6]|7[0135678]|9[89])\\\\d8$/",message = "手机号格式不正确") private String phone; public String getUsername() return username; public void setUsername(String username) this.username = username; public String getPassword() return password; public void setPassword(String password) this.password = password; public String getPhone() return phone; public void setPhone(String phone) this.phone = phone;
下图为各个注解的意思:
3、在控制层接受参数时
package com.zhiyou100.zjc.controller; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.validation.Valid; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.validation.FieldError; import org.springframework.web.bind.annotation.RequestMapping; import com.zhiyou100.zjc.bean.User; @Controller public class UserController @RequestMapping("login")//如果没有登录,那么访问该请求地址是被打倒登录界面 //@Valid:校验该参数对象 //BindingResult:封装所有的验证错误信息 public String login(@Valid User user,BindingResult br,Model model) if(br.hasErrors()) //判断有没有错误信息 List<FieldError> fieldErrors = br.getFieldErrors();//等到所有的错误信息 Map<String, Object> errormsg = new HashMap<String, Object>(); for(FieldError errors:fieldErrors) //getField()得到错误的字段 getDefaultMessage()得到错误的提示信息 errormsg.put(errors.getField(), errors.getDefaultMessage()); System.out.println(errors.getField()+"----"+errors.getDefaultMessage()); model.addAttribute("msg", errormsg); return "forward:index.jsp"; return "list";
前端代码
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <form action="login" method="post"> 用户名:<input type="text" name="username"/>$msg.username <br> 密码:<input type="text" name="password">$msg.password <br> 电话:<input type="text" name="phone">$msg.phone <br> <input type="submit" value="登录"> </form> </body> </html>
点击登录时,测试效果
以上是关于springMVC——数据校验(后台校验 hibernate validate).的主要内容,如果未能解决你的问题,请参考以下文章