自学SpringBoot--05服务端表单数据校验
程序员文章站
2022-05-03 10:24:11
...
Spring Boot 服务端表单数据校验
实现添加用户功能
创建项目
修改pom文件
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.10.RELEASE</version>
</parent>
<groupId>com.bjsxt</groupId>
<artifactId>13-spring-boot-validate</artifactId>
<version>0.0.1-SNAPSHOT</version>
<properties>
<thymeleaf.version>3.0.2.RELEASE</thymeleaf.version>
<thymeleaf-layout-dialect.version>2.0.4</thymeleaf-layout-dialect.version>
</properties>
<dependencies>
<!-- springboot的启动器 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- thymeleaf的启动器 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
</dependencies>
</project>
编写添加用户功能
创建实体
Users
package com.bjsxt.pojo;
public class Users {
private String name;
private String password;
private String age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
@Override
public String toString() {
return "Users [name=" + name + ", password=" + password + ", age=" + age + "]";
}
}
创建Controller
package com.bjsxt.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import com.bjsxt.pojo.Users;
/**
* SpringBoot 表单数据校验
* @author john
*
*/
@Controller
public class UsersController {
@RequestMapping("/addUser")
public String showPage() {
return "add";
}
/**
* 完成用户添加
*/
@RequestMapping("/save")
public String saveUser(Users users) {
System.out.println(users);
return "OK";
}
}
编写页面
add.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>添加用户</title>
</head>
<body>
<form th:action="@{/save}" method="post">
用户姓名:<input type="text" name="name"><br/>
用户密码:<input type="password" name="password"><br/>
用户年龄:<input type="text" name="age"><br/>
<input type="submit" value="OK">
</form>
</body>
</html>
OK.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>操作成功</title>
</head>
<body>
OK!
</body>
</html>
启动类
package com.bjsxt;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
SpringBoot对表单做数据校验
解决数据校验时的异常问题
其他校验规则
下一篇: Springboot 处理异常(三)