技术经验谈 技术经验谈
首页
  • 最佳实践

    • 抓包
    • 数据库操作
  • ui

    • 《JavaScript教程》
    • 《JavaScript高级程序设计》
    • 《ES6 教程》
    • 《Vue》
    • 《React》
    • 《TypeScript 从零实现 axios》
    • 《Git》
    • TypeScript
    • JS设计模式总结
  • 总纲
  • 整体开发框架
  • 技术文档
  • GitHub技巧
  • Nodejs
  • 博客搭建
  • 学习
  • 面试
  • 心情杂货
  • 实用技巧
  • 友情链接
关于
收藏
  • 分类
  • 标签
  • 归档
GitHub (opens new window)

hss01248

一号线程序员
首页
  • 最佳实践

    • 抓包
    • 数据库操作
  • ui

    • 《JavaScript教程》
    • 《JavaScript高级程序设计》
    • 《ES6 教程》
    • 《Vue》
    • 《React》
    • 《TypeScript 从零实现 axios》
    • 《Git》
    • TypeScript
    • JS设计模式总结
  • 总纲
  • 整体开发框架
  • 技术文档
  • GitHub技巧
  • Nodejs
  • 博客搭建
  • 学习
  • 面试
  • 心情杂货
  • 实用技巧
  • 友情链接
关于
收藏
  • 分类
  • 标签
  • 归档
GitHub (opens new window)
  • 日志体系

  • springboot

    • springboot中controller层实现通用的透明代理
    • dns解析优化
    • cloudflare dns解析配置和https代理配置
    • springboo中使用requestParam注解接收jsonBody里的参数
  • ruoyi-vue-pro

  • IT工具链
  • java学习路线和视频链接--尚硅谷
  • JDK动态代理原理和应用
  • jvm一图流
  • linux运维
  • spring boot笔记
  • spring-cloud学习资料和路线
  • springcloud alibaba
  • Springcloud学习笔记
  • 从java编译原理到Android aop
  • 大数据
  • 操作系统原理一图流
  • 汇编语言一图流
  • 泛型
  • 网关
  • 面试题精讲
  • java
  • springboot
hss01248
2024-01-24

springboo中使用requestParam注解接收jsonBody里的参数

# springboo中使用requestParam注解接收jsonBody里的参数

# 需求

请求接口统一使用post json

有很多时候,只有一两个参数,比如id之类的,不想给这个也定义一个bean来接受,期望使用@RequestParam来直接接收.

# 实现

使用filter, 解析json里的数据,放置到HttpServletRequest的reqeust param map中

因为HttpServletRequest的reqeust param map是不可更改的,因此需要构建一个新的HttpServletRequest

代码如下:

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.hutool.log.StaticLog;
import org.springframework.stereotype.Component;
import org.springframework.util.StreamUtils;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

@Component
public class AppendParametersFilter implements Filter {
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        Map<String, String[]> additionalParams = new HashMap<>();

        HttpServletRequest request1 = (HttpServletRequest) request;
        String contentType = request1.getHeader("Content-Type");

        if(contentType.contains("json")){
            String read = StreamUtils.copyToString(request.getInputStream(), Charset.forName("UTF-8"));
            StaticLog.warn("resolveArgument json---> "+contentType+"\n"+read);
            //转换json
            JSONObject jsonObject = JSONUtil.parseObj(read);
            if (jsonObject != null) {
                //这里有一个可能性就是比如get请求,参数是拼接在URL后面,但是如果我们还是去读流里面的数据就会读取不到
                //Map<String, String[]> parameterMap = request.getParameterMap();
                //o1 = parameterMap.get(parameterName);
                Set<Map.Entry<String, Object>> entries = jsonObject.entrySet();
                for (Map.Entry<String, Object> entry : entries) {
                    //No modifications are allowed to a locked ParameterMap
                    additionalParams.put(entry.getKey(),new String[]{entry.getValue()+""});
                }
            }
        }

        EnhancedHttpRequest enhancedHttpRequest = new EnhancedHttpRequest((HttpServletRequest) request, additionalParams);

        // pass the request along the filter chain
        chain.doFilter(enhancedHttpRequest, response);
    }

    @Override
    public void destroy() {	}
    @Override
    public void init(FilterConfig filterConfig) throws ServletException { }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56

新的reqeust:

import java.util.Collections;
import java.util.Enumeration;
import java.util.Map;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

public class EnhancedHttpRequest extends HttpServletRequestWrapper
{
    private final Map<String, String[]> modifiableParameters;
    private Map<String, String[]> allParameters = null;

    /**
     * Create a new request wrapper that will merge additional parameters into
     * the request object without prematurely reading parameters from the
     * original request.
     *
     * @param request
     * @param additionalParams
     */
    public EnhancedHttpRequest (final HttpServletRequest request,
                                final Map<String, String[]> additionalParams)
    {
        super(request);
        modifiableParameters = new TreeMap<>();
        modifiableParameters.putAll(additionalParams);
    }

    @Override
    public String getParameter(final String name)
    {
        String[] strings = getParameterMap().get(name);
        if (strings != null)
        {
            return strings[0];
        }
        return super.getParameter(name);
    }

    @Override
    public Map<String, String[]> getParameterMap()
    {
        if (allParameters == null)
        {
            allParameters = new TreeMap<>();
            allParameters.putAll(super.getParameterMap());
            allParameters.putAll(modifiableParameters);
        }
        //Return an unmodifiable collection because we need to uphold the interface contract.
        return Collections.unmodifiableMap(allParameters);
    }

    @Override
    public Enumeration<String> getParameterNames()
    {
        return Collections.enumeration(getParameterMap().keySet());
    }

    @Override
    public String[] getParameterValues(final String name)
    {
        return getParameterMap().get(name);
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65

于是,就能和普通get请求一样去取参数了:

    @RequestMapping(value = "/extraInfo", method = RequestMethod.POST)
    public BaseBean extraInfo(@RequestParam String path){
      ....
    }
1
2
3
4

# 另外一种方式:

定义map来接收,然后取参数,但终究不是那么方便:

    
    public BaseBean getAll(int tabId) {
					.....
        return BaseBean.success(maps);
    }

    @PostMapping("/getAll2")
    public BaseBean getAll2(@RequestBody Map<String,Object> map ) {
        int tabId = (int) map.get("tabId");
        return getAll(tabId);
    }
1
2
3
4
5
6
7
8
9
10
11
编辑 (opens new window)
上次更新: 2024/02/18, 17:27:05
cloudflare dns解析配置和https代理配置
ruoyi-vue-pro-oauth2支持不同客户端同时登录

← cloudflare dns解析配置和https代理配置 ruoyi-vue-pro-oauth2支持不同客户端同时登录→

最近更新
01
截图后的自动压缩工具
12-27
02
图片视频文件根据exif批量重命名
12-27
03
chatgpt图片识别描述功能
02-20
更多文章>
Theme by Vdoing | Copyright © 2020-2025 | 粤ICP备20041795号
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式