springboot獲取web請求參數

主要內容: 對常用的註解進行解釋說明,並用demo演示具體應用。

參考文章

springboot獲取web請求參數

springboot註解
  1. 獲取請求參數數據 @RequestParam

    這個註解主要用在獲取url中的參數,可以用在Post中,但是建議只在GET請求中使用

@RequestMapping(path = "register", method = RequestMethod.GET)
    public JsonBuilder userRegister(@RequestParam(value = "username") String username,
                                    @RequestParam(value = "password") String password,
                                    @RequestParam(value = "phone") String phone,
                                    @RequestParam(value = "nickname") String nickname,
                                    HttpServletRequest request){

        // 從數據庫查詢有沒有此用戶,有的話返回錯誤,沒有繼續
        // xxx 各種操作
}

不管是 get還是post url中的參數 @RequestParam都可以獲取,但是不能獲取 請求體 中的數據.

  1. 獲取請求體內容(body)數據 @RequestBody ()
    get沒有請求體,主要用在post
    /**
     * 獲取字符串內容
     * @param list
     * @return
     */
    @PostMapping("withBody1")
    public String withBody1(@RequestBody String body){
        return "獲取請求內容數據1:"+body;
    }
    /**
     * 獲取MAP對象
     * @param list
     * @return
     */
    @PostMapping("withBody3")
    public String withBody3(@RequestBody Map<String, String> body){
        return "獲取請求內容數據3:"+body;
    }
    /**
     * 獲取實體
     * @param list
     * @return
     */
    @PostMapping("withBody4")
    public String withBody4(@RequestBody UserInfoModel body){
        return "獲取請求內容數據4:"+body;
    }
    /**
     * 獲取列表
     * @param list
     * @return
     */
    @PostMapping("withBody6")
    public String withBody6(@RequestBody List<Map<String, Object>> list){
        return "獲取請求內容數據6:"+list.toArray().toString();
    }
  1. 獲取路徑參數數據 @PathVariable
    在請求路徑中有動態參數時,可以用pathvariable獲取
    @GetMapping("withPath/{userId}/info")
    public String withPath(@PathVariable String userId){
        return "獲取請求路徑參數"+userId;
    }
  1. 獲取header數據 @RequestHeader
    獲取請求頭中的數據,token等等
    @GetMapping("withHeader")
    public String withHeader(@RequestHeader String token){
        return "獲取請求頭參數"+token;
    }
  1. 獲取cookie數據 @CookieValue
    ** 獲取前端cookie中的數據**
    @GetMapping("withCookie")
    public String withCookie(@CookieValue String token){
        return "獲取cookie參數"+token;
    }
  1. 獲取FORM表單參數
/**
     * 獲取FORM表單數據  通過參數
     * @param formKey1
     * @param formKey2
     * @return
     */
    @PostMapping("withForm1")
    public String withForm1(@RequestParam String formKey1,@RequestParam String formKey2){
        return "獲取FORM表單參數formKey1:"+formKey1+" :formKey2:"+formKey2;
    }
    
    /**
     * 獲取FORM表單數據 通過對象
     * @param userInfo
     * @return
     */
    @PostMapping("withForm2")
    public String withForm2(@ModelAttribute UserInfoModel userInfo){
        return "獲取FORM表單參數:"+userInfo.toString();
    }
  1. 通用方法,可以獲取到所有類型的參數(上面所有都可以獲取
    @PostMapping("withRequest")
    public String withRequest(HttpServletRequest request) throws IOException{
        // 獲取請求參數
        request.getParameter("");
        // 獲取請求頭
        request.getHeader("");
        // 獲取cookie
        request.getCookies();
        // 獲取路徑信息 
        request.getPathInfo();
        // 獲取body流
        request.getInputStream();
        return "其實上面講了那麼多,這個纔是大BOOS";
    }
文件上傳
    /**
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("/image")
    public String uploadImage(@RequestParam MultipartFile file) throws IOException{
        String contentType = file.getContentType();
        if (contentType.equals(MediaType.IMAGE_JPEG_VALUE)
                ||contentType.equals(MediaType.IMAGE_PNG_VALUE)) {
            // 獲取文件流
            InputStream is= file.getInputStream();
            byte[] data = new byte[2048];
            FileOutputStream fis = new FileOutputStream(
                    new File("D:\\liuawei\\springbootbucket\\resources\\upload\\"+file.getOriginalFilename()));
            while(is.read(data)!=-1){
                fis.write(data);
            }
            fis.flush();
            fis.close();
            is.close();
        }else {
            return "error";
        }
        return "success";
    }   
參數校驗
  1. 添加參數校驗框架依賴
<dependency>
    <groupId>org.hibernate.validator</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>6.0.13.Final</version>
</dependency>
  1. 在JavaBean上面配置檢驗規則
    @Min(value=15,message="最小值是15")
    @Max(value=130,message="最大值是130")
    private int age;
    
    @Email(message="必須符合郵件地址")
    private String email;
    
    @Past(message="日期是過去的日期")
    @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")
    private Date birthday;
    
    @NotBlank
    private String remark;
  1. 在請求方法添加@Valid進行校驗
    @GetMapping("validata")
    public String validata(@Valid ValBean bean,BindingResult result){
        if (result.hasErrors()) {
            return "參數校驗失敗";
        }
        return "參數校驗成功";
    }

springboot學習系列文章

springboot學習系列文章

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章