SpringBoot常見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") // 當(dāng)前端屬性為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") // 當(dāng)前端屬性為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;
}當(dāng)請求參數(shù)ID不為test,objectErrors 中有該報錯。
總結(jié)
到此這篇關(guān)于SpringBoot常見get/post請求參數(shù)處理、參數(shù)注解校驗及參數(shù)自定義注解校驗詳解的文章就介紹到這了,更多相關(guān)springboot常見http get post請求參數(shù)處理內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
關(guān)于Spring事務(wù)隔離、傳播屬性與@Transactional注解
這篇文章主要介紹了關(guān)于事務(wù)隔離、Spring傳播屬性與@Transactional注解,如果一組處理步驟或者全部發(fā)生或者一步也不執(zhí)行,我們稱該組處理步驟為一個事務(wù),需要的朋友可以參考下2023-05-05
Spring MVC-@RequestMapping注解詳解
@RequestMapping注解的作用,就是將請求和處理請求的控制器方法關(guān)聯(lián)起來,建立映射關(guān)系。這篇文章主要給大家介紹了關(guān)于SpringMVC中@RequestMapping注解用法,文中通過實例代碼介紹的非常詳細,需要的朋友可以參考下2023-04-04
Spring?Boot?+?Canal?實現(xiàn)數(shù)據(jù)庫實時監(jiān)控
這篇文章主要介紹了Spring?Boot?+?Canal實現(xiàn)數(shù)據(jù)庫實時監(jiān)控,文章圍繞主題展開詳細的內(nèi)容介紹,具有一定的參考價值,需要的小伙伴可以參考一下2022-08-08
MyBatis-Plus更新對象時將字段值更新為null的四種常見方法
MyBatis-Plus 是一個 MyBatis 的增強工具,在簡化開發(fā)、提高效率方面表現(xiàn)非常出色,而,在使用 MyBatis-Plus 更新對象時,默認情況下是不會將字段值更新為 null 的,如果你需要將某些字段的值更新為 null,有幾種方法可以實現(xiàn),本文將介紹幾種常見的方法2024-11-11
如何在java 8 stream表達式實現(xiàn)if/else邏輯
這篇文章主要介紹了如何在java 8 stream表達式實現(xiàn)if/else邏輯,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-04-04

