从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对象。

posted @ 2021-07-15 09:12  钟小嘿  阅读(9163)  评论(1编辑  收藏  举报