從request中獲取請求json格式的參數信息


有時可能不能使用注解的方式獲取post請求中的json數據,而又需要獲取請求的參數如何處理?

所有的請求都存在於HttpServletRequest對象中,那么只需要在此對象中獲取即可:

@RequestMapping("/user")
public class UserController {

    //獲取參數
    public static JSONObject getParameters(HttpServletRequest request) throws IOException {
        BufferedReader streamReader = new BufferedReader(new InputStreamReader(request.getInputStream(), "UTF-8"));
        StringBuilder responseStrBuilder = new StringBuilder();
        String inputStr;
        while ((inputStr = streamReader.readLine()) != null)
            responseStrBuilder.append(inputStr);
        JSONObject jsonObject = JSONObject.parseObject(responseStrBuilder.toString());
        return jsonObject;
    }

    @PostMapping("/param")
    public void getParam(HttpServletRequest request) throws IOException {
        getParameters(request);
    }

}

關鍵部分是代碼中獲取參數的地方,從request對象中獲取流,再轉成json字符串。

不只限於controller中,其他地方也可以使用此方法獲取,前提是先得到request對象。


免責聲明!

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



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