前端传一个String类型参数,后端接收的三种方法
前端传参时,参数放在路径上http://localhost:8080/test?name=justin,参数加注解@RequestParam String name特点:容易涉及到安全问题使用Map接收@RequestBody Map<String,String> map结论:推荐使用第二种
·
- 前端传参时,参数放在路径上
http://localhost:8080/test?name=justin
,后端接收参数加注解@RequestParam String name
特点:借助@RequestParam可接收Get请求,Post请求url上的参数,容易涉及到安全问题 - 使用Map接收
@RequestBody Map<String,String> map
特点:借助swagger生成接口文档时,无法获取参数名 - 借助自定义注解+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);
}
更多推荐
已为社区贡献1条内容
所有评论(0)