1. 前端传参时,参数放在路径上http://localhost:8080/test?name=justin,后端接收参数加注解@RequestParam String name
    特点:借助@RequestParam可接收Get请求,Post请求url上的参数,容易涉及到安全问题
  2. 使用Map接收@RequestBody Map<String,String> map
    特点:借助swagger生成接口文档时,无法获取参数名
  3. 借助自定义注解+WebMvcConfigurer自定义参数解析器
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface RequestSingleParam {

    String value();

    boolean required() default true;

    String defaultValue() default "";
}
/**
 * @author 
 * @Date 2021/12/28 11:09
 * @description  接口入参只需要一个参数,如果将一个参数封装成一个对象很麻烦
 *               spring自带的参数解析器不具备这个能力的,所有自定义
 */
public class RequestSingleParamResolver 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);
    }
}
/**
 * @author 
 * @Date 2021/12/28 11:14
 * @description 注册自定义解析器
 */
@Configuration
public class RequestSingleParamAdapter implements WebMvcConfigurer {

    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {
        resolvers.add(new RequestSingleParamResolver());
    }
}
@PostMapping("/getPlats")
    @ApiOperation(value = "获取平台列表", notes = "获取平台列表")
    public CommonResult<List<PlatVo>> getPlats(@RequestSingleParam(required = false,value = "name") String name)
    {
        return accApplyService.getPlats(name);
    }
Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐