栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Spring boot中,Post请求string类型参数接收不到的问题

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Spring boot中,Post请求string类型参数接收不到的问题

问题:post请求,只有一两个参数时,不想再定义一个对象进行接收,直接使用String是接收不到的。

1、定义一个注解:@RequestJson

@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface RequestJson {

    String value();

}

2、注解的具体实现:

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.framework.annotation.RequestJson;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;


@Component
public class RequestJsonMethodArgumentResolver implements HandlerMethodArgumentResolver {
    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.hasParameterAnnotation(RequestJson.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        RequestJson requestJson = parameter.getParameterAnnotation(RequestJson.class);
        HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
        BufferedReader reader = request.getReader();
        StringBuilder sb = new StringBuilder();
        char[] buf = new char[1024];
        int rd;
        while ((rd = reader.read(buf)) != -1) {
            sb.append(buf, 0, rd);
        }
        JSONObject jsonObject = JSONObject.parseObject(sb.toString());
        String value = requestJson.value();
        if (jsonObject == null) {
            return null;
        }
        return jsonObject.get(value);
    }
}

3、注册到配置文件中去

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

	@Autowired
    private RequestJsonMethodArgumentResolver requestJsonMethodArgumentResolver;
    
	@Override
    public void addArgumentResolvers(List argumentResolvers) {
        argumentResolvers.add(requestJsonMethodArgumentResolver);
    }
}

END;

Controller层方法:

	@ApiOperation("测试RequestJson注解")
    @PostMapping("/test")
    public R test(@RequestJson("name")@NotBlank(message = "不能为空") String name, @RequestJson("sex")Integer sex){
        return R.ok(name+"----"+sex);
    }

参数:

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/932848.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号