Spring Boot 与 Kotlin 验证web表单信息

在做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 实战》

全科龙婷

参考资料

点赞
收藏

评论区

加载中...

相关推荐

MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1

文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s

Oracle 分组与拼接字符串同时使用

SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(

MySQL部分从库上面因为大量的临时表tmp_table造成慢查询

背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_

皕杰报表之UUID

​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为

手写Java HashMap源码

HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22

2020年前端实用代码段,为你的工作保驾护航

有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )