解決httpServletRequest.getParameter獲取不到參數


用httpServletRequest.getParameter接收post請求參數,發送端content Type必須設置為application/x-www-form-urlencoded;否則會接收不到

    @RequestMapping(value = "/a2")
    @ResponseBody
    public String hello3(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
        String string = httpServletRequest.getParameter("json");
        System.out.println(string);
        return "hahah";
    }

 用@RequestBody接收請求可以用任意類型的content Type

    @RequestMapping(value = "/a")
    @ResponseBody
    public void hello1(@RequestBody String string) {
        System.out.println(string);
    }

application/x-www-form-urlencoded通過表單提交,在sevlet實現中,mutipart/form-data和application/x-www-form-urlencoded會被特殊處理,請求參數將被放置於request.paramter,這是一個map。我們可以從map中獲取參數進行驗證,或者其他攔截需求,map的獲取類似hibernate的延遲加載,當調用request.getparamter()方法,servlet才會從請求流中讀取請求參數加載入map。InputStream也會存有這份數據,但如果這份數據被讀取,那么到了controller層將無法讀出數據,同樣,攔截之后到達controller層時請求數據已經被加載入了controller層方法實參,實參對象需要有set方法,框架會以反射的方式調用屬性的set方法注入數據,數據只會被注入到已有的屬性。

當以application/json的content-type傳送數據,被傳送的對象只需被json序列化。當以application/x-www-form-urlencoded的方式傳送數據。請求的內容需要以..=..&..=..的格式提交,在請求體內內容將會以”&”和“ = ”進行拆分。

 


免責聲明!

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



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