溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

使用SpringBoot實現(xiàn)服務(wù)端表單數(shù)據(jù)校驗的示例

發(fā)布時間:2020-10-27 17:51:41 來源:億速云 閱讀:140 作者:Leah 欄目:開發(fā)技術(shù)

本篇文章給大家分享的是有關(guān)使用SpringBoot實現(xiàn)服務(wù)端表單數(shù)據(jù)校驗的示例,小編覺得挺實用的,因此分享給大家學(xué)習,希望大家閱讀完這篇文章后可以有所收獲,話不多說,跟著小編一起來看看吧。

一、實現(xiàn)添加用戶功能

1 創(chuàng)建項目

使用SpringBoot實現(xiàn)服務(wù)端表單數(shù)據(jù)校驗的示例

2 修改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 http://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>
  <java.version>1.7</java.version>
  <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>

3 編寫添加用戶功能

3.1 創(chuàng)建實體類

publicclass Users {
 private String name;
 private String password;
 private Integer age;
 public String getName() {
  returnname;
 }
 publicvoid setName(String name) {
  this.name = name;
 }
 public String getPassword() {
  returnpassword;
 }
 publicvoid setPassword(String password) {
  this.password = password;
 }
 public Integer getAge() {
  returnage;
 }
 publicvoid setAge(Integer age) {
  this.age = age;
 }
 @Override
 public String toString() {
  return"Users [name=" + name + ", password=" + password + ", age=" + age + "]";
 }
 
}

3.2 編寫Controller

/**
 * SpringBoot 表單數(shù)據(jù)校驗
 *
 *
 */
@Controller
publicclass UsersController {
 
 @RequestMapping("/addUser")
 public String showPage(){
  return"add";
 }
 
 /**
  * 完成用戶添加
  */
 @RequestMapping("/save")
 public String saveUser(Users users){
  System.out.println(users);
  return"ok";
 }
}

3.3 編寫頁面add.html ok.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>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>操作成功</title>
</head>
<body>
 OK。。。。
</body>
</html>

二、SpringBoot對表單做數(shù)據(jù)校驗

1 SpringBoot對表單數(shù)據(jù)校驗的技術(shù)特點

1.1 SpringBoot中使用了Hibernate-validate校驗框架

2 SpringBoot表單數(shù)據(jù)校驗步驟

2.1 在實體類中添加校驗規(guī)則

publicclass Users {
 @NotBlank//非空校驗
 private String name;
 @NotBlank//密碼非空校驗
 private String password;
 private Integer age;
 public String getName() {
  returnname;
 }
 publicvoid setName(String name) {
  this.name = name;
 }
 public String getPassword() {
  returnpassword;
 }
 publicvoid setPassword(String password) {
  this.password = password;
 }
 public Integer getAge() {
  returnage;
 }
 publicvoid setAge(Integer age) {
  this.age = age;
 }
 @Override
 public String toString() {
  return"Users [name=" + name + ", password=" + password + ", age=" + age + "]";
 } 
}

2.2 在Controller中開啟校驗

/**
  * 完成用戶添加
  *@Valid開啟對Users對象的數(shù)據(jù)校驗
  *BindingResult:封裝了校驗的結(jié)果
  */
 @RequestMapping("/save")
 public String saveUser(@Valid Users users,BindingResult result){
  if(result.hasErrors()){
   return"add";
  }
  System.out.println(users);
  return"ok";
 }

2.3 在頁面中獲取提示信息

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>添加用戶</title>
</head>
<body>
 <form th:action="@{/save}" method="post">
  用戶姓名:<input type="text" name="name"/><font color="red" th:errors="${users.name}"></font><br/>
  用戶密碼:<input type="password" name="password" /><font color="red" th:errors="${users.password}"></font><br/>
  用戶年齡:<input type="text" name="age" /><font color="red" th:errors="${users.age}"></font><br/>
  <input type="submit" value="OK"/>
 </form>
</body>
</html>

2.4 遇到異常

在jsp當中,如果一個對象根本不存在,那么他仍然可以在jsp頁面進行遍歷,只不過為空,不顯示而已,但是在thymeleaf當中,如果說這個對象不存在,他就會報以下錯誤,解決問題的辦法就是在controller中的方法上的傳遞參數(shù)加上這個對象,以便在thymeleaf視圖層當中,告知這個對象是存在于的

使用SpringBoot實現(xiàn)服務(wù)端表單數(shù)據(jù)校驗的示例

三、解決數(shù)據(jù)校驗時的異常問題

解決異常的方法,在跳轉(zhuǎn)頁面的方法中注入一個對象,來解決問題。要求參數(shù)對象的變量名必須是對象的類名的全稱首字母小寫。

在springboot 1.5當中,參數(shù)變量必須是對象類的名稱首字母小寫,但是在springboot2.0以上,已經(jīng)很大程度上優(yōu)化了這個問題,變量名稱隨便寫,因為在跳轉(zhuǎn)頁面的時候,將該對象放入到Model當中傳遞,他的key 就是對象的類的全程首字母大寫(默認),在thymeleaf當中取出這個值的時候,他的key為對象的類的全程首字母大寫,與參數(shù)的變量名無任何關(guān)系 如果非要更改Model當中的key值,一下有詳解

代碼

/**
  * 解決異常的方式??梢栽谔D(zhuǎn)頁面的方法中注入一個Uesrs對象。
  * 注意:由于springmvc會將該對象放入到Model中傳遞。key的名稱會使用該對象的駝峰式的命名規(guī)則來作為key。
  * 參數(shù)的變量名需要與對象的名稱相同。將首字母小寫。
  *
  * @param users
  * @return
  */
 @RequestMapping("/addUser")
 public String showPage( Users users){
  return"add";
 }
/**
  * 完成用戶添加
  *@Valid開啟對Users對象的數(shù)據(jù)校驗
  *BindingResult:封裝了校驗的結(jié)果
  */
 @RequestMapping("/save")
 public String saveUser( @Valid Users users,BindingResult result){
  if(result.hasErrors()){
   return"add";
  }
  System.out.println(users);
  return"ok";
 }
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>添加用戶</title>
</head>
<body>
 <form th:action="@{/save}" method="post">
  用戶姓名:<input type="text" name="name"/><font color="red" th:errors="${users.name}"></font><br/>
  用戶密碼:<input type="password" name="password" /><font color="red" th:errors="${users.password}"></font><br/>
  用戶年齡:<input type="text" name="age" /><font color="red" th:errors="${users.age}"></font><br/>
  <input type="submit" value="OK"/>
 </form>
</body>
</html>

如果參數(shù)的名稱需要做改變

 /**
  *
  * 如果想為傳遞的對象更改名稱,可以使用@ModelAttribute("aa")這表示當前傳遞的對象的key為aa。
  * 那么我們在頁面中獲取該對象的key也需要修改為aa
  * @param users
  * @return
  */
 @RequestMapping("/addUser")
 public String showPage(@ModelAttribute("aa") Users users){
  return"add";
 }
/**
  * 完成用戶添加
  *@Valid開啟對Users對象的數(shù)據(jù)校驗
  *BindingResult:封裝了校驗的結(jié)果
  */
 @RequestMapping("/save")
 public String saveUser(@ModelAttribute("aa") @Valid Users users,BindingResult result){
  if(result.hasErrors()){
   return"add";
  }
  System.out.println(users);
  return"ok";
 }
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>添加用戶</title>
</head>
<body>
 <form th:action="@{/save}" method="post">
  用戶姓名:<input type="text" name="name"/><font color="red" th:errors="${aa.name}"></font><br/>
  用戶密碼:<input type="password" name="password" /><font color="red" th:errors="${aa.password}"></font><br/>
  用戶年齡:<input type="text" name="age" /><font color="red" th:errors="${aa.age}"></font><br/>
  <input type="submit" value="OK"/>
 </form>
</body>
</html>

四、其他校驗規(guī)則

@NotBlank: 判斷字符串是否為null或者是空串(去掉首尾空格)。

@NotEmpty: 判斷字符串是否null或者是空串。

@Length: 判斷字符的長度(最大或者最小)

@Min: 判斷數(shù)值最小值

@Max: 判斷數(shù)值最大值

@Email: 判斷郵箱是否合法

補充知識:控制Configuration是否生效,使用Springboot中@ConditionalOnProperty注解

介紹

@ConditionalOnProperty注解的作用是來控制Configuration是否生效

通過其兩個屬性name以及havingValue來實現(xiàn)的,其中name用來從application.properties中讀取某個屬性值。

matchIfMissing來控制默認值

如果值不為空,則將該值與havingValue指定的值進行比較,如果一樣則返回true;否則返回false。

如果返回值為false,則該configuration不生效;為true則生效。

使用

shardingjdbc中可以控制是否啟用,這樣可以針對某個配置來啟動數(shù)據(jù)源,完全不影響代碼實現(xiàn),想完成這個功能就要用到Stringboot提供的注解@ConditionalOnProperty

使用SpringBoot實現(xiàn)服務(wù)端表單數(shù)據(jù)校驗的示例

因為默認是true,所以使用可以忽略,但是如果不需要使用,禁用則需要增加配置

spring.shardingsphere.enabled=false 

以上就是使用SpringBoot實現(xiàn)服務(wù)端表單數(shù)據(jù)校驗的示例,小編相信有部分知識點可能是我們?nèi)粘9ぷ鲿姷交蛴玫降?。希望你能通過這篇文章學(xué)到更多知識。更多詳情敬請關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI