SpringBoot 接收 单个String入参之解决方案

场景:

  在做接口时,有的时候,接口入参只需要一个参数,如果将一个参数封装成一个对象很麻烦,故有了以下方式:

思路:

  spring自带的参数解析器貌似是不具备这个能力的,所有自定义

方式方法:

  1.定义一个注解

复制代码
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface RequestSingleParam {
    String value();

    boolean required() default true;

    String defaultValue() default "";
}
复制代码

  2.定义解析器

复制代码
public class RequestSingleParamHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {
    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.hasParameterAnnotation(RequestSingleParam.class);
    }


    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
                                  NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        RequestSingleParam requestSingleParam = parameter.getParameterAnnotation(RequestSingleParam.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 = requestSingleParam.value();
        return jsonObject.get(value);
    }

}
复制代码

  3.修改Springboot启动类(a.继承WebMvcConfigurerAdapter;b.重写addArgumentResolvers()方法)

复制代码
@SpringBootApplication
@EnableWebMvc
public class SpringbootDemoApplication extends WebMvcConfigurerAdapter {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootDemoApplication.class, args);
    }

    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers){
        argumentResolvers.add(new RequestSingleParamHandlerMethodArgumentResolver());
        super.addArgumentResolvers(argumentResolvers);
    }
}
复制代码

  4.在Controller中应用 

  调用接口方,传参如: {“name”:"张三"},Controller中就能获取到"张三”

    @RequestMapping(value = "/test",method = RequestMethod.POST)
    public void test(@RequestSingleParam(value = "name") String name){
            System.out.println(name);
    }

  

 

posted @ 2021-01-21 00:57  牧之丨  阅读(624)  评论(0编辑  收藏  举报