溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

SpringBoot常見get/post請求參數(shù)處理的方法

發(fā)布時間:2022-03-14 13:36:13 來源:億速云 閱讀:2105 作者:iii 欄目:開發(fā)技術(shù)

這篇文章主要介紹了SpringBoot常見get/post請求參數(shù)處理的方法的相關(guān)知識,內(nèi)容詳細易懂,操作簡單快捷,具有一定借鑒價值,相信大家閱讀完這篇SpringBoot常見get/post請求參數(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ù)值,默認(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中有多個參數(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時,使用默認(rèn)值

    具體代碼如下:

    localhost:8080/hello

    @RestController
    public class HelloController {
        @RequestMapping(value="/hello",method= RequestMethod.GET)
        //required=false 表示url中可以無id參數(shù),此時就使用默認(rèn)參數(shù)
        public String sayHello(@RequestParam(value="id",required = false,defaultValue = "1") Integer id){
            return "id:"+id;
        }
    }

    輸出

    id:1

    POST JSON參數(shù)校驗

    常用校驗注解

    SpringBoot常見get/post請求參數(shù)處理的方法

    注意:

    接收到的參數(shù)默認(rèn)都是字符串類型的

    有的注解只能用在String類型的屬性上

    @JsonProperty可以實現(xiàn)前端的屬性名和后臺實體類的屬性名不一致問題

    校驗方式:

    使用@RequestBody @Valid 對JSON參數(shù)進行獲取和校驗。

    通過BindingResult bindingResult 去獲取校驗結(jié)果。

    BindingResult 源碼:

    SpringBoot常見get/post請求參數(shù)處理的方法

    技巧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 中有該報錯。

    關(guān)于“SpringBoot常見get/post請求參數(shù)處理的方法”這篇文章的內(nèi)容就介紹到這里,感謝各位的閱讀!相信大家對“SpringBoot常見get/post請求參數(shù)處理的方法”知識都有一定的了解,大家如果還想學(xué)習(xí)更多知識,歡迎關(guān)注億速云行業(yè)資訊頻道。

    向AI問一下細節(jié)

    免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

    AI