当前位置:   article > 正文

springboot-@valid+@bingdingResult进行controller参数校验_public int register

public int register

项目代码已上传至github:https://github.com/snowlavenderlove/springbootValidator.git

1.创建数据库spring_validator,并建表user,表结构如图

2.通过https://start.spring.io/官网创建项目springbootValidator,项目结构如图,创建项目教程可参考博文:https://blog.csdn.net/qq_37231511/article/details/90669242

3.pom.xml中添加logging/druid/validator依赖,此处放全

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  4. <modelVersion>4.0.0</modelVersion>
  5. <parent>
  6. <groupId>org.springframework.boot</groupId>
  7. <artifactId>spring-boot-starter-parent</artifactId>
  8. <version>1.5.2.RELEASE</version>
  9. <relativePath/> <!-- lookup parent from repository -->
  10. </parent>
  11. <groupId>com.xue</groupId>
  12. <artifactId>springbootValidator</artifactId>
  13. <version>0.0.1-SNAPSHOT</version>
  14. <name>springbootValidator</name>
  15. <description>Demo project for Spring Boot</description>
  16. <properties>
  17. <java.version>1.8</java.version>
  18. <maven-jar-plugin.version>3.0.0</maven-jar-plugin.version>
  19. </properties>
  20. <dependencies>
  21. <dependency>
  22. <groupId>org.springframework.boot</groupId>
  23. <artifactId>spring-boot-starter-data-jpa</artifactId>
  24. </dependency>
  25. <dependency>
  26. <groupId>org.springframework.boot</groupId>
  27. <artifactId>spring-boot-starter-web</artifactId>
  28. </dependency>
  29. <dependency>
  30. <groupId>org.mybatis.spring.boot</groupId>
  31. <artifactId>mybatis-spring-boot-starter</artifactId>
  32. <version>1.3.0</version>
  33. </dependency>
  34. <dependency>
  35. <groupId>mysql</groupId>
  36. <artifactId>mysql-connector-java</artifactId>
  37. <scope>runtime</scope>
  38. </dependency>
  39. <dependency>
  40. <groupId>org.springframework.boot</groupId>
  41. <artifactId>spring-boot-starter-test</artifactId>
  42. <scope>test</scope>
  43. </dependency>
  44. <dependency>
  45. <groupId>commons-logging</groupId>
  46. <artifactId>commons-logging</artifactId>
  47. <version>1.2</version>
  48. </dependency>
  49. <dependency>
  50. <groupId>com.alibaba</groupId>
  51. <artifactId>druid</artifactId>
  52. <version>1.1.17</version>
  53. </dependency>
  54. <dependency>
  55. <groupId>org.hibernate.validator</groupId>
  56. <artifactId>hibernate-validator</artifactId>
  57. <version>6.0.16.Final</version>
  58. </dependency>
  59. <dependency>
  60. <groupId>org.springframework.boot</groupId>
  61. <artifactId>spring-boot-starter-thymeleaf</artifactId>
  62. </dependency>
  63. </dependencies>
  64. <build>
  65. <plugins>
  66. <plugin>
  67. <groupId>org.springframework.boot</groupId>
  68. <artifactId>spring-boot-maven-plugin</artifactId>
  69. </plugin>
  70. </plugins>
  71. </build>
  72. </project>

4.通过generator-mybatis创建代码,教程可见博文:https://blog.csdn.net/qq_37231511/article/details/90692784,创建完后放到项目中如图:

 

5.编辑application.properies文件

 

  1. #mysql
  2. spring.datasource.driver-class-name=com.mysql.jdbc.Driver
  3. spring.datasource.url=jdbc:mysql://127.0.0.1:3306/spring_validator
  4. spring.datasource.username=root
  5. spring.datasource.password=123456
  6. #druid
  7. spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
  8. #dao
  9. mybatis.type-aliases-package==com.xue.repository.dao
  10. mybatis.mapper-locations=classpath*:com/xue/repository/mapper/*.xml

6.在entity下创建包http,并创建UserReqBean和UserResBean,代码分别为:

  1. package com.xue.entity.http;
  2. import javax.validation.constraints.Size;
  3. import org.hibernate.validator.constraints.NotEmpty;
  4. public class UserReqBean {
  5. /**
  6. * 在实体类上写上相关验证信息
  7. */
  8. private Integer id;
  9. @NotEmpty(message = "用户名不能为空!")
  10. private String name;
  11. @Size(min=3,max=10,message = "密码长度在3到10位")
  12. private String pwd;
  13. public Integer getId() {
  14. return id;
  15. }
  16. public void setId(Integer id) {
  17. this.id = id;
  18. }
  19. public String getName() {
  20. return name;
  21. }
  22. public void setName(String name) {
  23. this.name = name == null ? null : name.trim();
  24. }
  25. public String getPwd() {
  26. return pwd;
  27. }
  28. public void setPwd(String pwd) {
  29. this.pwd = pwd == null ? null : pwd.trim();
  30. }
  31. @Override
  32. public String toString() {
  33. return "UserReqBean [id=" + id + ", name=" + name + ", pwd=" + pwd + "]";
  34. }
  35. }
  1. package com.xue.entity.http;
  2. public class UserResBean {
  3. private Integer id;
  4. private String name;
  5. private String pwd;
  6. public Integer getId() {
  7. return id;
  8. }
  9. public void setId(Integer id) {
  10. this.id = id;
  11. }
  12. public String getName() {
  13. return name;
  14. }
  15. public void setName(String name) {
  16. this.name = name == null ? null : name.trim();
  17. }
  18. public String getPwd() {
  19. return pwd;
  20. }
  21. public void setPwd(String pwd) {
  22. this.pwd = pwd == null ? null : pwd.trim();
  23. }
  24. }

 7.创建controller包,新建UserController

  1. package com.xue.controller;
  2. import java.util.List;
  3. import javax.validation.Valid;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.stereotype.Controller;
  6. import org.springframework.validation.BindingResult;
  7. import org.springframework.validation.ObjectError;
  8. import org.springframework.web.bind.annotation.RequestBody;
  9. import org.springframework.web.bind.annotation.RequestMapping;
  10. import org.springframework.web.bind.annotation.ResponseBody;
  11. import com.xue.entity.http.UserReqBean;
  12. import com.xue.entity.http.UserResBean;
  13. import com.xue.service.UserService;
  14. @Controller
  15. public class UserController {
  16. @Autowired
  17. private UserService userService;
  18. @RequestMapping("/loginHtml")
  19. public String loginHtml(){
  20. return "loginHtml";
  21. }
  22. @RequestMapping("/registerHtml")
  23. public String registerHtml(){
  24. return "registerHtml";
  25. }
  26. /**
  27. * 注意的是@Valid 和 BindingResult 是一 一对应的
  28. * 如果有多个@Valid,那么每个@Valid后面都需要添加BindingResult用于接收bean中的校验信息
  29. */
  30. @RequestMapping("/login")
  31. @ResponseBody
  32. public String login(@Valid @RequestBody UserReqBean inparam,BindingResult bingdingResult){
  33. if(bingdingResult.hasErrors()){
  34. List<ObjectError> ls=bingdingResult.getAllErrors();
  35. for (int i = 0; i < ls.size(); i++) {
  36. System.out.println("error:"+ls.get(i));
  37. }
  38. }
  39. UserResBean res = userService.login(inparam);
  40. System.out.println(inparam);
  41. if(null != res){
  42. return "登陆成功,用户名:"+res.getName()+" 密码"+res.getPwd();
  43. }else{
  44. return "登陆失败";
  45. }
  46. }
  47. /**
  48. * 注意的是@Valid 和 BindingResult 是一 一对应的
  49. * 如果有多个@Valid,那么每个@Valid后面都需要添加BindingResult用于接收bean中的校验信息
  50. */
  51. @RequestMapping("/register")
  52. @ResponseBody
  53. public String register(@Valid @RequestBody UserReqBean inparam,BindingResult bingdingResult){
  54. System.out.println("进入入口--------------------------");
  55. if(bingdingResult.hasErrors()){
  56. List<ObjectError> ls=bingdingResult.getAllErrors();
  57. for (int i = 0; i < ls.size(); i++) {
  58. System.out.println("error:"+ls.get(i));
  59. }
  60. }
  61. int result = userService.register(inparam);
  62. if(0 != result){
  63. return "注册成功";
  64. }else{
  65. return "注册失败";
  66. }
  67. }
  68. }

8.创建service包,创建UserService接口与UserServiceImpl实现类,代码分别为

  1. package com.xue.service;
  2. import com.xue.entity.http.UserReqBean;
  3. import com.xue.entity.http.UserResBean;
  4. public interface UserService {
  5. // 增
  6. public int register(UserReqBean user);
  7. // 查
  8. public UserResBean login(UserReqBean user);
  9. }

 

  1. package com.xue.service.Impl;
  2. import java.util.HashMap;
  3. import java.util.Map;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.stereotype.Service;
  6. import com.xue.entity.http.UserReqBean;
  7. import com.xue.entity.http.UserResBean;
  8. import com.xue.entity.model.User;
  9. import com.xue.repository.dao.UserMapper;
  10. import com.xue.service.UserService;
  11. @Service
  12. public class UserServiceImpl implements UserService {
  13. @Autowired
  14. private UserMapper userMapper;
  15. @Override
  16. public int register(UserReqBean data) {
  17. int result = 0;
  18. User user = new User();
  19. user.setName(data.getName());
  20. user.setPwd(data.getPwd());
  21. try {
  22. result = userMapper.insertUser(user);
  23. } catch (Exception e) {
  24. // TODO Auto-generated catch block
  25. e.printStackTrace();
  26. }
  27. return result;
  28. }
  29. @Override
  30. public UserResBean login(UserReqBean data) {
  31. UserResBean res = null;
  32. res = new UserResBean();
  33. User user = null;
  34. Map<String,Object> params = new HashMap<String,Object>();
  35. params.put("name", data.getName());
  36. params.put("pwd", data.getPwd());
  37. try {
  38. user = userMapper.selectUser(params);
  39. } catch (Exception e) {
  40. // TODO Auto-generated catch block
  41. e.printStackTrace();
  42. }
  43. if(null != user){
  44. res.setName(user.getName());
  45. res.setPwd(user.getPwd());
  46. return res;
  47. }
  48. return res;
  49. }
  50. }

9.编辑UserMapper.java,在代码最后添加

  1. int insertUser(User user);
  2. User selectUser(Map<String,Object> inparams);

 10.编辑UserMapper.xml,在代码最后添加

  1. <select id="selectUser" parameterType="com.xue.entity.model.User" resultMap="BaseResultMap">
  2. select name,pwd from user where name =#{name} and pwd = #{pwd}
  3. </select>
  4. <insert id="insertUser" parameterType="com.xue.entity.model.User">
  5. insert into user(name,pwd) values(#{name},#{pwd})
  6. </insert>

 11.代码到此结束,最终项目结构为

12.通过后台接口测试软件输入正常的数据进行测试register接口

 13.通过后台接口测试软件输入不符合规则的数据进行测试register接口,如图:后台打印出了信息

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/714014
推荐阅读
相关标签
  

闽ICP备14008679号