SpringBoot入门系列~基于注解@Valid的表单数据合法性校验

以网站用户注册为例,校验用户填写的数据是否合法

1、创建用户实体,启动容器生成用户表

复制代码
  1 package com.sun.spring.boot.pojo;
  2 
  3 import javax.persistence.Column;
  4 import javax.persistence.Entity;
  5 import javax.persistence.GeneratedValue;
  6 import javax.persistence.Id;
  7 import javax.persistence.Table;
  8 import javax.validation.constraints.Max;
  9 import javax.validation.constraints.Min;
 10 import javax.validation.constraints.NotNull;
 11 import javax.validation.constraints.Size;
 12 
 13 import org.hibernate.validator.constraints.Email;
 14 import org.hibernate.validator.constraints.NotBlank;
 15 import org.hibernate.validator.constraints.NotEmpty;
 16 
 17 
 18 /**
 19  * 用户基本信息实体Bean
 20  * @ClassName: UserInfoBean  
 21  * @author sunt  
 22  * @date 2017年11月10日 
 23  * @version V1.0
 24  */
 25 @Entity
 26 @Table(name = "T_USER")
 27 public class UserInfoBean {
 28     /**
 29      * 注解说明:
 30      *@NotNull:不能为null,但可以为empty:空字符串也成立
 31      *@NotEmpty:不能为null,而且长度必须大于0 
 32      *@NotBlank:只能作用在String上,不能为null,而且调用trim()后,长度必须大于0 
 33      *@Size(max,min)    限制字符长度必须在min到max之间
 34      */
 35     
 36     
 37     /**
 38      * 用户编码
 39      */
 40     @Id
 41     @GeneratedValue
 42     private Integer id;
 43     
 44     /**
 45      * 用户名
 46      */
 47     @NotEmpty(message = "用户名不能为空")
 48     @Column(name = "F_USER_NAME", length = 15)
 49     @Size(max = 15,min = 3, message = "用户名至少为3位,最大15位")
 50     private String userName;
 51     
 52     /**
 53      * 年龄
 54      */
 55     @NotNull(message = "年龄不能为空")
 56     @Min(value = 18, message = "未年满18周岁无法注册")
 57     @Max(value = 200, message = "请输入合法的年龄")
 58     @Column(name = "F_AGE",length = 50)
 59     private Integer age;
 60     
 61     /**
 62      * 注册邮箱
 63      */
 64     @NotBlank(message = "邮箱不能为空")
 65     @Column(name = "F_EMAIL",length = 30)
 66     @Email(message = "请输入合法的邮箱格式")
 67     private String email;
 68 
 69     public Integer getId() {
 70         return id;
 71     }
 72 
 73     public void setId(Integer id) {
 74         this.id = id;
 75     }
 76 
 77     public String getUserName() {
 78         return userName;
 79     }
 80 
 81     public void setUserName(String userName) {
 82         this.userName = userName;
 83     }
 84 
 85     public Integer getAge() {
 86         return age;
 87     }
 88 
 89     public void setAge(Integer age) {
 90         this.age = age;
 91     }
 92 
 93     public String getEmail() {
 94         return email;
 95     }
 96 
 97     public void setEmail(String email) {
 98         this.email = email;
 99     }
100     
101 }
复制代码

2、常用的校验注解:

复制代码
@Null 被注释的元素必须为 null
@NotNull 被注释的元素必须不为 null
@Min(value) 被注释的元素必须是一个数字,其值必须大于等于指定的最小值
@Max(value) 被注释的元素必须是一个数字,其值必须小于等于指定的最大值
@Size(max, min) 被注释的元素的大小必须在指定的范围内
@Email 被注释的元素必须是电子邮箱地址
@Length 被注释的字符串的大小必须在指定的范围内
@NotEmpty 被注释的字符串的必须非空
@Range 被注释的元素必须在合适的范围内
复制代码

3、创建Dao接口

复制代码
 1 package com.sun.spring.boot.dao;
 2 
 3 import org.springframework.data.jpa.repository.JpaRepository;
 4 import org.springframework.stereotype.Repository;
 5 
 6 import com.sun.spring.boot.pojo.UserInfoBean;
 7 /**
 8  * 用户基本信息dao接口
 9  * @ClassName: IUserInfoDao  
10  * @author sunt  
11  * @date 2017年11月10日 
12  * @version V1.0
13  */
14 @Repository
15 public interface IUserInfoDao extends JpaRepository<UserInfoBean, Integer>{
16 
17 }
复制代码

4、创建Service接口和实现类

复制代码
 1 package com.sun.spring.boot.service;
 2 
 3 import com.sun.spring.boot.pojo.UserInfoBean;
 4 
 5 /**
 6  * 用户基本 信息service接口
 7  * @ClassName: IUserInfoService  
 8  * @author sunt  
 9  * @date 2017年11月10日 
10  * @version V1.0
11  */
12 public interface IUserInfoService {
13 
14     /**
15      * 新增用户
16      * @Title: addUser 
17      * @author sunt  
18      * @date 2017年11月10日
19      * @return void
20      */
21     void addUser(UserInfoBean userInfoBean);
22 }
复制代码
复制代码
 1 package com.sun.spring.boot.service.impl;
 2 
 3 import javax.transaction.Transactional;
 4 
 5 import org.apache.log4j.Logger;
 6 import org.springframework.beans.factory.annotation.Autowired;
 7 import org.springframework.stereotype.Service;
 8 
 9 import com.sun.spring.boot.dao.IUserInfoDao;
10 import com.sun.spring.boot.pojo.UserInfoBean;
11 import com.sun.spring.boot.service.IUserInfoService;
12 /**
13  * 用户service实现
14  * @ClassName: UserInfoServiceImpl  
15  * @author sunt  
16  * @date 2017年11月10日 
17  * @version V1.0
18  */
19 @Service
20 public class UserInfoServiceImpl implements IUserInfoService {
21 
22     private Logger logger = Logger.getLogger(UserInfoServiceImpl.class);
23     
24     @Autowired
25     private IUserInfoDao userInfoDao;
26     
27     @Override
28     @Transactional
29     public void addUser(UserInfoBean userInfoBean) {
30         logger.info("-------->添加用户操作...");
31         userInfoDao.save(userInfoBean);
32     }
33 
34 }
复制代码

5、创建Controller:跳转到用户注册页面方法和提交表单保存数据的方法

复制代码
 1 package com.sun.spring.boot.controller;
 2 
 3 import javax.validation.Valid;
 4 
 5 import org.springframework.beans.factory.annotation.Autowired;
 6 import org.springframework.validation.BindingResult;
 7 import org.springframework.web.bind.annotation.PostMapping;
 8 import org.springframework.web.bind.annotation.RequestMapping;
 9 import org.springframework.web.bind.annotation.RestController;
10 import org.springframework.web.servlet.ModelAndView;
11 
12 import com.sun.spring.boot.pojo.UserInfoBean;
13 import com.sun.spring.boot.service.IUserInfoService;
14 
15 /**
16  * 用户操作Controller
17  * @ClassName: UserInfoController  
18  * @author sunt  
19  * @date 2017年11月10日 
20  * @version V1.0
21  */
22 @RestController
23 @RequestMapping(value = "/user")
24 public class UserInfoController {
25 
26     @Autowired
27     private IUserInfoService userInfoService;
28     
29     /**
30      * 跳转到添加用户页面
31      * @Title: toAddUser 
32      * @author sunt  
33      * @date 2017年11月10日
34      * @return ModelAndView
35      */
36     @RequestMapping(value = "/toAddUser")
37     public ModelAndView toAddUser() {
38         ModelAndView modelAndView = new ModelAndView();
39         modelAndView.setViewName("addUser");
40         return modelAndView;
41     }
42     
43     /**
44      * 添加用户
45      * @Title: addUser 
46      * @author sunt  
47      * @date 2017年11月10日
48      * @return String
49      */
50     @PostMapping(value = "/addUser")
51     public String addUser(@Valid UserInfoBean bean, BindingResult bindingResult) {
52         
53         if(bindingResult.hasErrors()) {
54             return bindingResult.getFieldError().getDefaultMessage();
55         }
56         
57         try {
58             userInfoService.addUser(bean);
59             return "新增用户成功!";
60         } catch (Exception e) {
61             e.printStackTrace();
62             return "注册用户异常!";
63         }
64     }
65 }
复制代码

6、创建注册模板页面:addUser.ftl

复制代码
 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4 <meta charset="UTF-8">
 5 <title>用户注册</title>
 6 <script type="text/javascript" src="/jquery-1.7.1.min.js"></script>
 7 <script type="text/javascript">
 8     $(function() {
 9         //异步提交
10         $('#js-add-user').on('click', function() {
11             $.post('/user/addUser',{
12                 userName : $('#userName').val(),
13                 age : $('#age').val(),
14                 email : $('#email').val()
15             },function(resData) {
16                 alert(resData);
17             });
18         });
19     });
20 </script>
21 </head>
22 <body>
23     <center>
24         <h2>用户注册</h2>
25             用户名:<input type="text" name="userName" id="userName"/><br />
26             年      龄:<input type="text" name="age" id="age" ><br />
27             邮      箱:<input type="text" name="email" id="email" ><br />
28             <input type="button" id="js-add-user" value="提交">
29     </center>
30 </body>
31 </html>
复制代码

7、浏览器访问:http://127.0.0.1:8088/user/toAddUser

输入非法内容进行验证,最后验证成功查询数据库表中的数据是否正确

 

  8、svn地址:svn://gitee.com/SunnySVN/SpringBoot

如果svn检出代码有问题参考这边博客说明:http://www.cnblogs.com/sunny1009/articles/7806047.html

 

posted @   sunny1009  阅读(421)  评论(0)    收藏  举报
编辑推荐:
· 如何反向绘制出 .NET程序 异步方法调用栈
· 领域驱动设计实战:聚合根设计与领域模型实现
· 突破Excel百万数据导出瓶颈:全链路优化实战指南
· 如何把ASP.NET Core WebApi打造成Mcp Server
· Linux系列:如何用perf跟踪.NET程序的mmap泄露
阅读排行:
· .NET周刊【5月第1期 2025-05-04】
· Python 3.14 新特性盘点,更新了些什么?
· 聊聊 ruoyi-vue ,ruoyi-vue-plus ,ruoyi-vue-pro 谁才是真正的
· 物联网之对接MQTT最佳实践
· Redis 连接池耗尽的一次异常定位

喜欢请打赏

扫描二维码打赏

了解更多

点击右上角即可分享
微信分享提示