JAVA Controller 獲取請求數據的方式匯總


本文不做底層理論知識的匯總,僅將多數獲取數據的方式做應用層面的匯總與驗證。
其中,文件數據的獲取,另文再寫~

其中請求方式,僅測試了 GET 和 POST 方法;

請求頭信息,僅測試了 multipart/form-data 與 application/x-www-form-urlencoded

通過路由獲取

@RequestMapping(value="/test/{id}/{name}", method= {RequestMethod.GET, RequestMethod.POST})
public String test(@PathVariable int id, @PathVariable(name="name") String userName){
    
}

說明:如果 @PathVariable 不使用 name 參數指定名稱,則必須和路由中的一致,否則會拋出異常;所指定的參數值,也不可為空。

傳統方式獲取

@RequestMapping(value="/test1", method= {RequestMethod.GET, RequestMethod.POST})
public String test1(HttpServletRequest request){
    String param1 = request.getParameter("param1"), // url 參數
        form1 = request.getParameter("form1"), //form-data
        //x-www-form-urlencoded
        encoded1 = request.getParameter("encoded1");
        
    String[] params = request.getParameterValues("params"), 
        forms = request.getParameterValues("forms"), 
        encodeds = request.getParameterValues("encodeds");
}

說明:

  • 通過在不同位置添加測試鍵,來讀取數據。結果表明:當請求頭為 form-data 時,GET 和 POST 都能獲取到 url 和 data 中的數據;當請求頭為 x-www-form-urlencoded 時,GET 請求獲取不到 data 中的數據。
  • 數組值獲取,只是使用的方法不同。請求時,參數名為一致。如果用 getParameter 獲取同名參數,則只會返回第一個值。
  • 數組值另外一種形式的獲取,可以在前端中將數組 JSON.stringify()包裝后作為單值發送,后端用 JSON 方式解碼為數組,這通常可用於一些前端多選的操作。

請求參數注解方式獲取

@RequestMapping(value="/test2", method= {RequestMethod.GET, RequestMethod.POST})
public String test2(@RequestParam(name = "name", defaultValue="noname", required=true) String userName){
    // 僅獲取單個值
}

@RequestMapping(value="/test2_1", method= {RequestMethod.GET, RequestMethod.POST})
public String test2_1(@RequestParam Map<String, Object> params) {
    // 獲取集合
}

說明:@RequestParam 注解可以簡單的獲取參數值。但是當請求方法為 GET,請求頭又為 x-www-form-urlencoded 時,獲取不到值。

請求體注解方式獲取

@RequestMapping(value="/test3", method= {RequestMethod.GET, RequestMethod.POST})
public String test3(@RequestBody String body) {
    
}

說明:@RequestBody 注解僅適用於 x-www-form-urlencoded 的請求方式,會將請求參數組合為 & 連接的字符串;如果請求方式為 POST 時,會將 URL 中的參數一起打包進字符串。

特殊注解類

@RequestMapping(value="/test4", method= {RequestMethod.GET, RequestMethod.POST})
public String test4(@RequestHeader(name = "headername", required=false) String headervalue, @CookieValue(name = "cookiename", required=false) String cookievalue){
}

說明:可直接獲取頭信息和 cookie 信息。

對象參數方式獲取

@RequestMapping(value="/test5", method= {RequestMethod.GET, RequestMethod.POST})
public String test5(Person person){
    // person.getId()
    // person.getName()
}

說明:對象參數的形式,可以獲取包含所有與參數類屬性同名的值;例如:{'name': 'Gary'}。但是當請求方法為 GET,請求頭又為 x-www-form-urlencoded 時,獲取不到值。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM