spring boot 常見http get ,post請求引數處理
在定義一個Rest介面時通常會利用GET、POST、PUT、DELETE來實現資料的增刪改查;這幾種方式有的需要傳遞引數,後臺開發人員必須對接收到的引數進行引數驗證來確保程式的健壯性
GET
一般用於查詢資料,採用明文進行傳輸,一般用來獲取一些無關使用者資訊的資料
POST
一般用於插入資料
PUT
一般用於資料更新
DELETE
一般用於資料刪除
一般都是進行邏輯刪除(即:僅僅改變記錄的狀態,而並非真正的刪除資料)
@PathVaribale 獲取url中的資料
@RequestParam 獲取請求引數的值
@GetMapping 組合註解,是 @RequestMapping(method = RequestMethod.GET) 的縮寫
@RequestBody 利用一個物件去獲取前端傳過來的資料
PathVaribale 獲取url路徑的資料
請求URL:
localhost:8080/hello/id 獲取id值
實現程式碼如下:
@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;
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
在瀏覽器中 輸入地址:
localhost:8080/hello/100/hello
輸出:
id:81name:hello
RequestParam 獲取請求引數的值
獲取url引數值,預設方式,需要方法引數名稱和url引數保持一致
localhost:8080/hello?id=1000
@RestController
public class HelloController {
@RequestMapping(value ="/hello",method= RequestMethod.GET)
public String sayHello(@RequestParam Integer id){
return "id:"+id;
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
輸出:
id:100
url中有多個引數時,如:
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;
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
獲取url引數值,執行引數名稱方式
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;
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
輸出:
id:100
注意
不輸入id的具體值,此時返回的結果為null。具體測試結果如下:
id:null
不輸入id引數,則會報如下錯誤:
whitelable Error Page錯誤
GET引數校驗
用法:不輸入id時,使用預設值
具體程式碼如下:
localhost:8080/hello
@RestController
public class HelloController {
@RequestMapping(value="/hello",method= RequestMethod.GET)
//required=false 表示url中可以無id引數,此時就使用預設引數
public String sayHello(@RequestParam(value="id",required = false,defaultValue = "1") Integer id){
return "id:"+id;
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
輸出
id:1
POST JSON引數校驗
常用校驗註解
注意:
接收到的引數預設都是字串型別的
有的註解只能用在String型別的屬性上
@JsonProperty可以實現前端的屬性名和後臺實體類的屬性名不一致問題
校驗方式:
使用@RequestBody @Valid 對JSON引數進行獲取和校驗。
通過BindingResult bindingResult 去獲取校驗結果。
BindingResult 原始碼:
技巧01:利用BindingResult物件的hasErrors方法判斷是否有引數錯誤
技巧02:利用BindingResult物件的getFieldErrors方法獲取所有有引數錯誤的屬性
技巧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;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
對應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
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
自定義註解校驗
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 {};
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
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;
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
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來保持一致
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
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;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
當請求引數ID不為test,objectErrors 中有該報錯。
在定義一個Rest介面時通常會利用GET、POST、PUT、DELETE來實現資料的增刪改查;這幾種方式有的需要傳遞引數,後臺開發人員必須對接收到的引數進行引數驗證來確保程式的健壯性
GET
一般用於查詢資料,採用明文進行傳輸,一般用來獲取一些無關使用者資訊的資料
POST
一般用於插入資料
PUT
一般用於資料更新
DELETE
一般用於資料刪除
一般都是進行邏輯刪除(即:僅僅改變記錄的狀態,而並非真正的刪除資料)
@PathVaribale 獲取url中的資料
@RequestParam 獲取請求引數的值
@GetMapping 組合註解,是 @RequestMapping(method = RequestMethod.GET) 的縮寫
@RequestBody 利用一個物件去獲取前端傳過來的資料
PathVaribale 獲取url路徑的資料
請求URL:
localhost:8080/hello/id 獲取id值
實現程式碼如下:
@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;
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
在瀏覽器中 輸入地址:
localhost:8080/hello/100/hello
輸出:
id:81name:hello