在做web开发的时候,我们需要验证表单,确认用户提交的信息是安全的,比如用户名不能超过多少位,密码不能少于多少位等等。
那么如何在Spring Boot 与 Kotlin中验证表单信息?
在springmvc工程中,需要检查表单信息,表单信息验证主要通过注解的形式。
表单验证
下面我们在之前《Spring Boot 与 kotlin 使用Thymeleaf模板引擎渲染web视图》项目的基础上,增加表单验证。
build.gradle 文件增加依赖
1compile "org.hibernate:hibernate-validator" 2compile "org.apache.tomcat.embed:tomcat-embed-el"
完整的build.gradle文件
1group 'name.quanke.kotlin' 2version '1.0-SNAPSHOT' 3 4buildscript { 5 ext.kotlin_version = '1.2.10' 6 ext.spring_boot_version = '1.5.4.RELEASE' 7 repositories { 8 mavenCentral() 9 } 10 dependencies { 11 classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" 12 classpath("org.springframework.boot:spring-boot-gradle-plugin:$spring_boot_version") 13 14// Kotlin整合SpringBoot的默认无参构造函数,默认把所有的类设置open类插件 15 classpath("org.jetbrains.kotlin:kotlin-noarg:$kotlin_version") 16 classpath("org.jetbrains.kotlin:kotlin-allopen:$kotlin_version") 17 } 18} 19 20apply plugin: 'kotlin' 21apply plugin: "kotlin-spring" // See https://kotlinlang.org/docs/reference/compiler-plugins.html#kotlin-spring-compiler-plugin 22apply plugin: 'org.springframework.boot' 23 24jar { 25 baseName = 'chapter11-5-5-service' 26 version = '0.1.0' 27} 28repositories { 29 mavenCentral() 30} 31 32 33dependencies { 34 compile "org.jetbrains.kotlin:kotlin-stdlib-jre8:$kotlin_version" 35 compile "org.springframework.boot:spring-boot-starter-web:$spring_boot_version" 36 compile "org.springframework.boot:spring-boot-starter-thymeleaf:$spring_boot_version" 37 compile "org.hibernate:hibernate-validator" 38 compile "org.apache.tomcat.embed:tomcat-embed-el" 39 40 testCompile "org.springframework.boot:spring-boot-starter-test:$spring_boot_version" 41 testCompile "org.jetbrains.kotlin:kotlin-test-junit:$kotlin_version" 42 43} 44 45compileKotlin { 46 kotlinOptions.jvmTarget = "1.8" 47} 48compileTestKotlin { 49 kotlinOptions.jvmTarget = "1.8" 50}
创建UserForm类
1import javax.validation.constraints.Min 2import javax.validation.constraints.NotNull 3import javax.validation.constraints.Size 4 5/** 6 * Created by http://quanke.name on 2018/1/12. 7 * https://stackoverflow.com/questions/36515094/kotlin-and-valid-spring-annotation 8 * https://stonesoupprogramming.com/2017/06/21/spring-bean-validation-example-jsr-303-in-kotlin/ 9 */ 10data class UserForm(@get:NotNull(message = "{name.required}") @get:Size(min = 2, max = 5,message = "{name.size}") var name: String? = "", @get:Min(18) var age: Int? = 0) 11
如果是Spring boot 可以不增加 @get注解,如果使用kotlin 语言实现必须加@get
这个实体类,在2个属性:name,age.它们各自有验证的注解:
- @Size(min=2, max=5) name的长度为2-30个字符
- @NotNull 不为空
- @Min(18)age不能小于18
创建WebController
1import name.quanke.kotlin.chaper11_5_5.entity.UserForm 2import org.springframework.stereotype.Controller 3import org.springframework.validation.Errors 4import org.springframework.web.bind.annotation.GetMapping 5import org.springframework.web.bind.annotation.PostMapping 6import org.springframework.web.servlet.config.annotation.ViewControllerRegistry 7import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter 8import javax.validation.Valid 9 10 11/** 12 * Created by http://quanke.name on 2018/1/12. 13 */ 14 15@Controller 16class WebController : WebMvcConfigurerAdapter() { 17 override fun addViewControllers(registry: ViewControllerRegistry?) { 18 registry!!.addViewController("/results").setViewName("results") 19 } 20 21 @GetMapping("/") 22 fun index(userForm: UserForm): String { 23 return "index" 24 } 25 26 @PostMapping("/") 27 fun checkPersonInfo(@Valid userForm: UserForm, errors: Errors): String { 28 29 val result: String = when { 30 //Test for errors 31 errors.hasErrors() -> "index" 32 else -> { 33 //Otherwise proceed to the next page 34 "redirect:/results" 35 } 36 } 37 return result 38 39 } 40}
创建form表单src/main/resources/templates/index.html
1<!DOCTYPE html> 2<html xmlns:th="http://www.w3.org/1999/xhtml"> 3<head lang="en"> 4 <title>quanke.name</title> 5 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> 6</head> 7<body> 8 9<h1>Form</h1> 10<form action="#" th:action="@{/}" th:object="${userForm}" method="post"> 11 <table> 12 <tr> 13 <td>Name:</td> 14 <td><input type="text" th:field="*{name}" /></td> 15 <td th:if="${#fields.hasErrors('name')}" th:errors="*{name}">Name Error</td> 16 </tr> 17 <tr> 18 <td>Age:</td> 19 <td><input type="text" th:field="*{age}" /></td> 20 <td th:if="${#fields.hasErrors('age')}" th:errors="*{age}">Age Error</td> 21 </tr> 22 <tr> 23 <td><button type="submit">Submit</button></td> 24 </tr> 25 </table> 26</form> 27</body> 28</html>
成功页面src/main/resources/templates/results.html
1<!DOCTYPE html> 2<html> 3<head> 4 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> 5 <title>quanke</title> 6</head> 7<body> 8<h1>quanke.name</h1> 9Congratulations! You are old enough to sign up for this site 10</body> 11</html>
在src/main/resources/目录下增加ValidationMessages.properties文件
1# \u8FD9\u91CC\u8981\u6CE8\u610F\u7F16\u7801\u95EE\u9898 2name.required=\u540D\u5B57\u4E0D\u80FD\u4E3A\u7A7A 3name.size=\u540D\u5B57\u957F\u5EA6\u8FD4\u56DE\u53EA\u80FD\u662F2-5
Spring Boot 启动
1import org.springframework.boot.SpringApplication 2import org.springframework.boot.autoconfigure.SpringBootApplication 3 4 5/** 6 * Created by http://quanke.name on 2018/1/9. 7 */ 8 9@SpringBootApplication 10class Application 11 12fun main(args: Array<String>) { 13 SpringApplication.run(Application::class.java, *args) 14}
更多Spring Boot 和 kotlin相关内容,欢迎关注《Spring Boot 与 kotlin 实战》