spring?boot常見get?、post請求參數(shù)處理、參數(shù)注解校驗(yàn)、參數(shù)自定義注解校驗(yàn)問題解析
spring boot 常見http get ,post請求參數(shù)處理
在定義一個(gè)Rest接口時(shí)通常會利用GET、POST、PUT、DELETE來實(shí)現(xiàn)數(shù)據(jù)的增刪改查;這幾種方式有的需要傳遞參數(shù),后臺開發(fā)人員必須對接收到的參數(shù)進(jìn)行參數(shù)驗(yàn)證來確保程序的健壯性
GET
一般用于查詢數(shù)據(jù),采用明文進(jìn)行傳輸,一般用來獲取一些無關(guān)用戶信息的數(shù)據(jù)
POST
一般用于插入數(shù)據(jù)
PUT
一般用于數(shù)據(jù)更新
DELETE
一般用于數(shù)據(jù)刪除
一般都是進(jìn)行邏輯刪除(即:僅僅改變記錄的狀態(tài),而并非真正的刪除數(shù)據(jù))
@PathVaribale 獲取url中的數(shù)據(jù)
@RequestParam 獲取請求參數(shù)的值
@GetMapping 組合注解,是 @RequestMapping(method = RequestMethod.GET) 的縮寫
@RequestBody 利用一個(gè)對象去獲取前端傳過來的數(shù)據(jù)
PathVaribale 獲取url路徑的數(shù)據(jù)
請求URL:localhost:8080/hello/id 獲取id值
實(shí)現(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ù)值,默認(rèn)方式,需要方法參數(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中有多個(gè)參數(shù)時(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的具體值,此時(shí)返回的結(jié)果為null。具體測試結(jié)果如下:id:null不輸入id參數(shù),則會報(bào)如下錯誤:whitelable Error Page錯誤
GET參數(shù)校驗(yàn)
用法:不輸入id時(shí),使用默認(rèn)值具體代碼如下:localhost:8080/hello
@RestController public class HelloController { @RequestMapping(value="/hello",method= RequestMethod.GET) //required=false 表示url中可以無id參數(shù),此時(shí)就使用默認(rèn)參數(shù) public String sayHello(@RequestParam(value="id",required = false,defaultValue = "1") Integer id){ return "id:"+id; } }
輸出
id:1
POST JSON參數(shù)校驗(yàn)
常用校驗(yàn)注解
注意:
接收到的參數(shù)默認(rèn)都是字符串類型的
有的注解只能用在String類型的屬性上
@JsonProperty可以實(shí)現(xiàn)前端的屬性名和后臺實(shí)體類的屬性名不一致問題
校驗(yàn)方式:
使用@RequestBody @Valid 對JSON參數(shù)進(jìn)行獲取和校驗(yàn)。
通過BindingResult bindingResult 去獲取校驗(yàn)結(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實(shí)體類代碼:
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時(shí)可以用@JsonProperty來保持一致 private String name; ....省略get set方法
自定義注解校驗(yàn)
1、定義一個(gè)校驗(yàn)注解
代碼如下:
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、定義一個(gè)約束校驗(yàn)
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、實(shí)體類中使用
public class User2 { @NotEmpty(message = "ID不能為空") @NotBlank(message = "ID不能為空喲") //自定義校驗(yàn)注解-校驗(yàn)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時(shí)可以用@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 中有該報(bào)錯。
到此這篇關(guān)于spring boot常見get 、post請求參數(shù)處理、參數(shù)注解校驗(yàn)、參數(shù)自定義注解校驗(yàn)的文章就介紹到這了,更多相關(guān)spring boot參數(shù)注解校驗(yàn)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
SpringBoot線程池和Java線程池的使用和實(shí)現(xiàn)原理解析
這篇文章主要介紹了SpringBoot線程池和Java線程池的用法和實(shí)現(xiàn)原理,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-04-04java利用StringTokenizer分割字符串的實(shí)現(xiàn)
利用java.util.StringTokenizer的方法,可以將一個(gè)字符串拆分為一系列的標(biāo)記,本文就來介紹一下java利用StringTokenizer分割字符串的實(shí)現(xiàn),感興趣的可以了解一下2023-10-10Mybatis-Plus通過SQL注入器實(shí)現(xiàn)批量插入的實(shí)踐
本文主要介紹了Mybatis-Plus通過SQL注入器實(shí)現(xiàn)批量插入的實(shí)踐,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-08-08spring源碼閱讀--aop實(shí)現(xiàn)原理講解
這篇文章主要介紹了spring源碼閱讀--aop實(shí)現(xiàn)原理講解,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-09-09使用IDEA向Gitee提交SpringBoot項(xiàng)目進(jìn)行遠(yuǎn)程管理
本文主要介紹了使用IDEA向Gitee提交SpringBoot項(xiàng)目進(jìn)行遠(yuǎn)程管理,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-01-01