由于开发中一般使用参数提交方式是json格式,对于单个参数的传递使用无法接收只能自定义参数解析器处理
springmvc的自定义参数解析器实现HandlerMethodArgumentResolver接口并且实现下面两个方法
第一个方法是 是否解析改参数 如果返回true 代表需要处理 则会调用resolveArgument方法进行解析
自定义参数注解(标识注解位置PARAMETER,以及运行时期)
实现supportsParameter方法 如果方法中包含该注解返回true
将参数从流中读取出来保存到request请求体中,这样第二次参数解析调用就直接从请求体中获取即可
public class JsonPathArgumentResolver implements HandlerMethodArgumentResolver {
private static final String JSON_REQUEST_BODY = "JSON_REQUEST_BODY";
@Override
public boolean supportsParameter(MethodParameter methodParameter) {
return methodParameter.hasParameterAnnotation(JsonParam.class);
}
@Override
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest webRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
String body = getRequestBody(webRequest);
Object val = null;
try {
if (StringUtil.isNotBlank(body)) {
JSONObject jsonObject = JSONObject.parseObject(body);
val = jsonObject.get(parameter.getParameterAnnotation(JsonParam.class).value());
}
if (parameter.getParameterAnnotation(JsonParam.class).required() && val == null) {
throw new RuntimeException(parameter.getParameterAnnotation(JsonParam.class).value() + "不能为空");
}
} catch (Exception exception) {
if (parameter.getParameterAnnotation(JsonParam.class).required()) {
/*返回*/
throw exception;
}
}
return val;
}
private String getRequestBody(NativeWebRequest webRequest) {
HttpServletRequest servletRequest = webRequest.getNativeRequest(HttpServletRequest.class);
String jsonBody = (String) servletRequest.getAttribute(JSON_REQUEST_BODY);
if (jsonBody == null) {
try {
jsonBody = IOUtils.toString(servletRequest.getInputStream());
servletRequest.setAttribute(JSON_REQUEST_BODY, jsonBody);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return jsonBody;
}
}
然后需要装载自定义的参数解析器
最后使用的时候只需要在参数前加上自定义的注解即可获取到传递的json值