zoukankan      html  css  js  c++  java
  • 从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对象。

    就是这么简单,你学废了吗?感觉有用的话,给笔者点个赞吧 !
  • 相关阅读:
    mybatis调用oracle存储过程
    java heap space
    汉字转拼音
    Go调用cpp类方式一
    ETCD节点故障恢复
    goroutine 加 channel 代替递归调用,突破递归调用的层级限制
    vscode debug golang
    mysql分组和去重同时使用
    github、gitlab 管理多个ssh key
    Qt连接MySQL
  • 原文地址:https://www.cnblogs.com/zys2019/p/15011609.html
Copyright © 2011-2022 走看看