Servlet中获取POST请求的参数

在servlet、filter等中获取POST请求的参数

  1. form表单形式提交post方式,可以直接从 request 的 getParameterMap 方法中获取到参数
  2. JSON形式提交post方式,则必须从 request 的 输入流 中解析获取参数,使用apache commons io 解析

maven配置

      <!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
    <dependency>
        <groupId>commons-io</groupId>
        <artifactId>commons-io</artifactId>
        <version>2.6</version>
    </dependency>
    
    <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.1.0</version>
        <scope>provided</scope>
    </dependency>
    
      <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>fastjson</artifactId>
        <version>1.2.50</version>
    </dependency>
      

获取POST请求中的参数

    /**
     * @author tianwyam
     * @description 从POST请求中获取参数
     * @param request
     * @return
     * @throws Exception
     */
    public static Map<String, Object> getParam4Post(HttpServletRequest request) throws Exception {
        
     // 返回参数 Map
<String, Object> params = new HashMap<>(); // 获取内容格式 String contentType = request.getContentType(); if (contentType != null && !contentType.equals("")) { contentType = contentType.split(";")[0]; } // form表单格式 表单形式可以从 ParameterMap中获取 if ("appliction/x-www-form-urlencoded".equalsIgnoreCase(contentType)) { // 获取参数 Map<String, String[]> parameterMap = request.getParameterMap(); if (parameterMap != null) { for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) { params.put(entry.getKey(), entry.getValue()[0]); } } } // json格式 json格式需要从request的输入流中解析获取 if ("application/json".equalsIgnoreCase(contentType)) { // 使用 commons-io中 IOUtils 类快速获取输入流内容 String paramJson = IOUtils.toString(request.getInputStream(), "UTF-8"); Map parseObject = JSON.parseObject(paramJson, Map.class); params.putAll(parseObject); } return params ; }

猜你喜欢

转载自www.cnblogs.com/tianwyam/p/post_param.html