1. 程式人生 > 程式設計 >SpringBoot結合JSR303對前端資料進行校驗的示例程式碼

SpringBoot結合JSR303對前端資料進行校驗的示例程式碼

一、校驗分類

資料的校驗一般分為**前端校驗後端校驗**

二、前端校驗

前端校驗是最為明顯的,先說一下:

① HTML

非空校驗HTML5 新增的屬性required="true",一旦沒有填寫就輸入框就顯示紅色,具體使用如:

<input type="text" id="name" name="name" required="true"/>

② JS

同時在提交表單傳送 Ajax請求 的時候,來個 onSubmit 函式,具體例如(使用點 EasyUI ):

function submitData(){
		$("#fm").form("submit",{
			url:"/admin/film/save",onSubmit:function(){
				var content=CKEDITOR.instances.content.getData();
				if(content==""){
					$.messager.alert("系統提示","內容不能為空!");
					return false;
				}
				return $(this).form("validate");
			},success:function(result){
				var result=eval('('+result+')');
				if(result.success){
					$.messager.alert("系統提示","儲存成功!");
					resetValue();
				}else{
					$.messager.alert("系統提示","儲存失敗!");
				}
				
			}
		});
	}

但我們都知道,這是防君子不防小人的做法,使用者可以使用 F12,檢視原始碼,修改關鍵部位的程式碼,
如把 required="true" 刪除掉,就可以提交表單了。
所以前端作用雖然明顯,但是資料處理方面,真正用處並不大。

三、後端校驗

前面說了那麼多,就是為了引出 後端校驗 這一話題。資料是否提交到資料庫中去,就看後端的程式碼了。
後端校驗,主要實施在 JavaBean、Controller 中。下面列舉一個簡單的例子,從程式碼中說明一切。

① 程式碼結構圖

SpringBoot結合JSR303對前端資料進行校驗的示例程式碼

② entity

實體屬性部位空,一般使用如 @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應<150") // 數字
	@Min(value = 1,message = "age應>1") // 數字
	@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

其實也沒什麼程式碼,這就是 JPA 的強大之處

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 #為了以後訪問專案不用寫埠號
 context-path: / #為了以後訪問專案不用寫專案名
spring:
 datasource:
  driver-class-name: com.mysql.jdbc.Driver
  url: jdbc:mysql://localhost:3306/springboot
  username: root
  password: 123
 jpa:
  hibernate:
   ddl-auto: update #資料庫同步程式碼
  show-sql: true   #dao操作時,顯示sql語句

⑦ POM

使用 SpringBoot Starter 匯入 JPA、MySQL

SpringBoot結合JSR303對前端資料進行校驗的示例程式碼

使用 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 進入介面測試站點

SpringBoot結合JSR303對前端資料進行校驗的示例程式碼

什麼都沒有填寫,直接點選Try it out!,可以看到返回給前端的 JSON 資料,這時候資料的資料是沒有改動的,一條sql 語句都沒有執行

SpringBoot結合JSR303對前端資料進行校驗的示例程式碼

當然還可以進行其他測試,這裡就省略了

到此這篇關於SpringBoot結合JSR303對前端資料進行校驗的示例程式碼的文章就介紹到這了,更多相關SpringBoot JSR303校驗內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!