SpringBoot結(jié)合JSR303對前端數(shù)據(jù)進(jìn)行校驗(yàn)的示例代碼
一、校驗(yàn)分類
數(shù)據(jù)的校驗(yàn)一般分為**前端校驗(yàn)
、后端校驗(yàn)
**
二、前端校驗(yàn)
前端校驗(yàn)是最為明顯的,先說一下:
① HTML
非空校驗(yàn)
如 HTML5
新增的屬性required="true"
,一旦沒有填寫就輸入框就顯示紅色,具體使用如:
<input type="text" id="name" name="name" required="true"/>
② JS
同時(shí)在提交表單發(fā)送 Ajax請求
的時(shí)候,來個(gè) onSubmit
函數(shù),具體例如(使用點(diǎn) EasyUI ):
function submitData(){ $("#fm").form("submit",{ url:"/admin/film/save", onSubmit:function(){ var content=CKEDITOR.instances.content.getData(); if(content==""){ $.messager.alert("系統(tǒng)提示","內(nèi)容不能為空!"); return false; } return $(this).form("validate"); }, success:function(result){ var result=eval('('+result+')'); if(result.success){ $.messager.alert("系統(tǒng)提示","保存成功!"); resetValue(); }else{ $.messager.alert("系統(tǒng)提示","保存失??!"); } } }); }
但我們都知道,這是防君子不防小人的做法,用戶可以使用 F12
,查看源碼,修改關(guān)鍵部位的代碼,
如把 required="true"
刪除掉,就可以提交表單了。
所以前端作用雖然明顯,但是數(shù)據(jù)處理方面,真正用處并不大。
三、后端校驗(yàn)
前面說了那么多,就是為了引出 后端校驗(yàn)
這一話題。數(shù)據(jù)是否提交到數(shù)據(jù)庫中去,就看后端的代碼了。
后端校驗(yàn),主要實(shí)施在 JavaBean、Controller 中。下面列舉一個(gè)簡單的例子,從代碼中說明一切。
① 代碼結(jié)構(gòu)圖
② entity
實(shí)體屬性部位空,一般使用如 @NotEmpty(message="請輸入用戶名!")
,這樣既不能為 空
,也不能為null
package com.cun.entity; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; import javax.validation.constraints.Max; import javax.validation.constraints.Min; import javax.validation.constraints.NotNull; import javax.validation.constraints.Null; import javax.validation.constraints.Size; import org.hibernate.validator.constraints.Email; import org.hibernate.validator.constraints.NotBlank; import io.swagger.annotations.ApiModelProperty; @Entity @Table(name = "t_person") public class Person { @Id @GeneratedValue @ApiModelProperty(value = "用戶id") private Integer id; @NotBlank(message = "用戶名不能為空") // 為""/''都不行 @Size(min = 2, max = 30, message = "2<長度<30") @Column(length = 50) @ApiModelProperty(value = "用戶名") private String userName; @NotNull(message = "用戶密碼不能為空") @Column(length = 50) @ApiModelProperty(value = "用戶密碼") private String password; @Max(value = 150, message = "age應(yīng)<150") // 數(shù)字 @Min(value = 1, message = "age應(yīng)>1") // 數(shù)字 @NotNull(message = "年齡不能為空") @ApiModelProperty(value = "用戶年齡") private Integer age; @NotNull(message = "郵箱不為空") @Email(message = "郵件格式不對") @Column(length = 100) @ApiModelProperty(value = "用戶郵箱") private String email; // 使用 JPA 必備 public Person() { super(); } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } }
③ dao
其實(shí)也沒什么代碼,這就是 JPA 的強(qiáng)大之處
package com.cun.dao; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import com.cun.entity.Person; public interface PersonDao extends JpaRepository<Person, Integer>, JpaSpecificationExecutor<Person> { }
④ Service、ServiceImpl (省略)
⑤ Controller
package com.cun.controller; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.validation.BindingResult; import org.springframework.validation.ObjectError; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.cun.dao.PersonDao; import com.cun.entity.Person; import springfox.documentation.swagger2.annotations.EnableSwagger2; @RestController @RequestMapping("/person") @EnableSwagger2 public class PersonController { @Autowired private PersonDao personDao; @PostMapping("/insert") public Map<String, Object> insertPerson(@Valid Person person, BindingResult bindingResult) { Map<String, Object> map = new HashMap<String, Object>(); if (bindingResult.hasErrors()) { List<ObjectError> errorList = bindingResult.getAllErrors(); List<String> mesList=new ArrayList<String>(); for (int i = 0; i < errorList.size(); i++) { mesList.add(errorList.get(i).getDefaultMessage()); } map.put("status", false); map.put("error", mesList); } else { map.put("status", true); map.put("msg", "添加成功"); personDao.save(person); } return map; } }
⑥ yml
server: port: 80 #為了以后訪問項(xiàng)目不用寫端口號 context-path: / #為了以后訪問項(xiàng)目不用寫項(xiàng)目名 spring: datasource: driver-class-name: com.mysql.jdbc.Driver url: jdbc:mysql://localhost:3306/springboot username: root password: 123 jpa: hibernate: ddl-auto: update #數(shù)據(jù)庫同步代碼 show-sql: true #dao操作時(shí),顯示sql語句
⑦ POM
使用 SpringBoot Starter 導(dǎo)入 JPA、MySQL
使用 Swagger 演示
<!-- swagger生成接口API --> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.7.0</version> </dependency> <!-- 接口API生成html文檔 --> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.6.1</version> </dependency>
四、演示
輸入 http://localhost/swagger-ui.html 進(jìn)入接口測試站點(diǎn)
什么都沒有填寫,直接點(diǎn)擊Try it out!
,可以看到返回給前端的 JSON
數(shù)據(jù),這時(shí)候數(shù)據(jù)的數(shù)據(jù)是沒有改動的,一條sql
語句都沒有執(zhí)行
當(dāng)然還可以進(jìn)行其他測試,這里就省略了
到此這篇關(guān)于SpringBoot結(jié)合JSR303對前端數(shù)據(jù)進(jìn)行校驗(yàn)的示例代碼的文章就介紹到這了,更多相關(guān)SpringBoot JSR303校驗(yàn)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- Springboot集成JSR303參數(shù)校驗(yàn)的方法實(shí)現(xiàn)
- Spring Boot利用JSR303實(shí)現(xiàn)參數(shù)驗(yàn)證的方法實(shí)例
- SpringBoot使用jsr303校驗(yàn)的實(shí)現(xiàn)
- Spring中使用JSR303請求約束判空的實(shí)現(xiàn)
- SpringBoot后端進(jìn)行數(shù)據(jù)校驗(yàn)JSR303的使用詳解
- springboot接口參數(shù)校驗(yàn)JSR303的實(shí)現(xiàn)
- springboot整合JSR303參數(shù)校驗(yàn)與全局異常處理的方法
- springboot整合JSR303校驗(yàn)功能實(shí)現(xiàn)代碼
- SpringMVC中的JSR303與攔截器的使用方法
相關(guān)文章
java基本教程之Thread中start()和run()的區(qū)別 java多線程教程
這篇文章主要介紹了Thread中start()和run()的區(qū)別,Thread類包含start()和run()方法,它們的區(qū)別是什么?下面將對此作出解答2014-01-01packages思維及使用Java添加Android平臺特定實(shí)現(xiàn)
這篇文章主要為大家介紹了packages思維及使用Java添加Android平臺特定實(shí)現(xiàn)在Flutter框架里的體現(xiàn)和運(yùn)用詳解,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-12-12springboot+vue實(shí)現(xiàn)阿里云oss上傳的示例代碼
文件上傳是常用的功能,本文主要介紹了springboot+vue實(shí)現(xiàn)阿里云oss上傳的示例代碼,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2024-06-06SpringBoot整合Mybatis使用Druid數(shù)據(jù)庫連接池
這篇文章主要介紹了SpringBoot整合Mybatis使用Druid數(shù)據(jù)庫連接池,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-03-03Java基礎(chǔ)教程之八大基本數(shù)據(jù)類型
這篇文章主要給大家介紹了關(guān)于Java基礎(chǔ)教程之八大基本數(shù)據(jù)類型的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧2019-06-06SpringBoot項(xiàng)目中org.junit.jupiter.api.Test報(bào)錯問題及解決
這篇文章主要介紹了SpringBoot項(xiàng)目中org.junit.jupiter.api.Test報(bào)錯問題及解決方案,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-11-11