1. 程式人生 > >SpringBoot 接收 單個String入參之解決方案

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);
    }