spring?boot常見get?、post請求參數(shù)處理、參數(shù)注解校驗、參數(shù)自定義注解校驗問題解析
spring boot 常見http get ,post請求參數(shù)處理
在定義一個Rest接口時通常會利用GET、POST、PUT、DELETE來實現(xiàn)數(shù)據(jù)的增刪改查;這幾種方式有的需要傳遞參數(shù),后臺開發(fā)人員必須對接收到的參數(shù)進行參數(shù)驗證來確保程序的健壯性
GET
一般用于查詢數(shù)據(jù),采用明文進行傳輸,一般用來獲取一些無關(guān)用戶信息的數(shù)據(jù)
POST
一般用于插入數(shù)據(jù)
PUT
一般用于數(shù)據(jù)更新
DELETE
一般用于數(shù)據(jù)刪除
一般都是進行邏輯刪除(即:僅僅改變記錄的狀態(tài),而并非真正的刪除數(shù)據(jù))
@PathVaribale 獲取url中的數(shù)據(jù)
@RequestParam 獲取請求參數(shù)的值
@GetMapping 組合注解,是 @RequestMapping(method = RequestMethod.GET) 的縮寫
@RequestBody 利用一個對象去獲取前端傳過來的數(shù)據(jù)
PathVaribale 獲取url路徑的數(shù)據(jù)
請求URL:localhost:8080/hello/id 獲取id值
實現(xiàn)代碼如下:
@RestController
public class HelloController {
@RequestMapping(value="/hello/{id}/{name}",method= RequestMethod.GET)
public String sayHello(@PathVariable("id") Integer id,@PathVariable("name") String name){
return "id:"+id+" name:"+name;
}
}在瀏覽器中
輸入地址:localhost:8080/hello/100/hello
輸出:id:81name:hello
RequestParam 獲取請求參數(shù)的值
獲取url參數(shù)值,默認方式,需要方法參數(shù)名稱和url參數(shù)保持一致localhost:8080/hello?id=1000
@RestController
public class HelloController {
@RequestMapping(value="/hello",method= RequestMethod.GET)
public String sayHello(@RequestParam Integer id){
return "id:"+id;
}
}輸出:
id:100
url中有多個參數(shù)時,如:localhost:8080/hello?id=98&&name=helloworld具體代碼如下:
@RestController
public class HelloController {
@RequestMapping(value="/hello",method= RequestMethod.GET)
public String sayHello(@RequestParam Integer id,@RequestParam String name){
return "id:"+id+ " name:"+name;
}
}獲取url參數(shù)值,執(zhí)行參數(shù)名稱方式localhost:8080/hello?userId=1000
@RestController
public class HelloController {
@RequestMapping(value="/hello",method= RequestMethod.GET)
public String sayHello(@RequestParam("userId") Integer id){
return "id:"+id;
}
}輸出:
id:100
注意
不輸入id的具體值,此時返回的結(jié)果為null。具體測試結(jié)果如下:id:null不輸入id參數(shù),則會報如下錯誤:whitelable Error Page錯誤
GET參數(shù)校驗
用法:不輸入id時,使用默認值具體代碼如下:localhost:8080/hello
@RestController
public class HelloController {
@RequestMapping(value="/hello",method= RequestMethod.GET)
//required=false 表示url中可以無id參數(shù),此時就使用默認參數(shù)
public String sayHello(@RequestParam(value="id",required = false,defaultValue = "1") Integer id){
return "id:"+id;
}
}輸出
id:1
POST JSON參數(shù)校驗
常用校驗注解

注意:
接收到的參數(shù)默認都是字符串類型的
有的注解只能用在String類型的屬性上
@JsonProperty可以實現(xiàn)前端的屬性名和后臺實體類的屬性名不一致問題
校驗方式:
使用@RequestBody @Valid 對JSON參數(shù)進行獲取和校驗。
通過BindingResult bindingResult 去獲取校驗結(jié)果。
BindingResult 源碼:

技巧01:利用BindingResult對象的hasErrors方法判斷是否有參數(shù)錯誤
技巧02:利用BindingResult對象的getFieldErrors方法獲取所有有參數(shù)錯誤的屬性
技巧03:利用錯誤屬性對象的getDefaultMessage去獲取錯誤提示信息
@RequestMapping(value = "/demo5",produces = MediaType.TEXT_PLAIN_VALUE)
@ResponseBody
public String test5(@RequestBody @Valid User user , BindingResult bindingResult){
if(bindingResult.hasErrors()){
List<ObjectError> objectErrors = bindingResult.getAllErrors();
System.out.println(objectErrors.toString());
for(ObjectError objectError: objectErrors){
System.out.println("objectError = " + objectError.getObjectName());
System.out.println("objectError = " + objectError.getDefaultMessage());
System.out.println("objectError = " + objectError.getCode());
System.out.println("objectError = " + objectError.getArguments());
}
}
String str = user.toString();
return str;
}對應(yīng)User實體類代碼:
public class User {
@NotEmpty(message = "ID不能為空")
@NotBlank(message = "ID不能為空喲")
private String id;
@Min(value = 18)
@Max(value = 30)
private Integer age;
@NotEmpty(message = "昵稱不能為空")
@NotBlank(message = "昵稱不能為空喲")
@JsonProperty("nickname") // 當前端屬性為nick后臺接收對象的屬性為nickName時可以用@JsonProperty來保持一致
private String name;
....省略get set方法自定義注解校驗
1、定義一個校驗注解
代碼如下:
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.*;
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.PARAMETER, ElementType.FIELD})
@Constraint(validatedBy = MyFormValidatorClass.class)
public @interface MyFormValidator {
String value();
String message() default "name can be test";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}2、定義一個約束校驗
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.lang.annotation.Annotation;
public class MyFormValidatorClass implements ConstraintValidator<MyFormValidator, Object>, Annotation {
private String values;
@Override
public void initialize(MyFormValidator myFormValidator) {
this.values = myFormValidator.value();
}
@Override
public boolean isValid(Object value, ConstraintValidatorContext context) {
if("test".equals((String)value)){
return true;
}
return false;
}
@Override
public Class<? extends Annotation> annotationType() {
return null;
}
}3、實體類中使用
public class User2 {
@NotEmpty(message = "ID不能為空")
@NotBlank(message = "ID不能為空喲")
//自定義校驗注解-校驗id是否為test
@MyFormValidator(value = "abc",message = "dd")
private String id;
@Min(value = 18)
@Max(value = 30)
private Integer age;
@NotEmpty(message = "昵稱不能為空")
@NotBlank(message = "昵稱不能為空喲")
@JsonProperty("nickname") // 當前端屬性為nick后臺接收對象的屬性為nickName時可以用@JsonProperty來保持一致4、測試代碼:
@RequestMapping(value = "/demo6",produces = MediaType.TEXT_PLAIN_VALUE)
@ResponseBody
public String test6(@RequestBody @Valid User2 user , BindingResult bindingResult){
if(bindingResult.hasErrors()){
List<ObjectError> objectErrors = bindingResult.getAllErrors();
System.out.println(objectErrors.toString());
for(ObjectError objectError: objectErrors){
System.out.println("objectError = " + objectError.getObjectName());
System.out.println("objectError = " + objectError.getDefaultMessage());
System.out.println("objectError = " + objectError.getCode());
System.out.println("objectError = " + objectError.getArguments());
}
}
String str = user.toString();
return str;
}當請求參數(shù)ID不為test,objectErrors 中有該報錯。
到此這篇關(guān)于spring boot常見get 、post請求參數(shù)處理、參數(shù)注解校驗、參數(shù)自定義注解校驗的文章就介紹到這了,更多相關(guān)spring boot參數(shù)注解校驗內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
SpringBoot線程池和Java線程池的使用和實現(xiàn)原理解析
這篇文章主要介紹了SpringBoot線程池和Java線程池的用法和實現(xiàn)原理,本文通過實例代碼給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-04-04
java利用StringTokenizer分割字符串的實現(xiàn)
利用java.util.StringTokenizer的方法,可以將一個字符串拆分為一系列的標記,本文就來介紹一下java利用StringTokenizer分割字符串的實現(xiàn),感興趣的可以了解一下2023-10-10
Mybatis-Plus通過SQL注入器實現(xiàn)批量插入的實踐
本文主要介紹了Mybatis-Plus通過SQL注入器實現(xiàn)批量插入的實踐,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-08-08
使用IDEA向Gitee提交SpringBoot項目進行遠程管理
本文主要介紹了使用IDEA向Gitee提交SpringBoot項目進行遠程管理,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-01-01

