springmvc自定义参数解析器
生活随笔
收集整理的這篇文章主要介紹了
springmvc自定义参数解析器
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
由于開(kāi)發(fā)中一般使用參數(shù)提交方式是json格式,對(duì)于單個(gè)參數(shù)的傳遞使用無(wú)法接收只能自定義參數(shù)解析器處理
springmvc的自定義參數(shù)解析器實(shí)現(xiàn)HandlerMethodArgumentResolver接口并且實(shí)現(xiàn)下面兩個(gè)方法
第一個(gè)方法是 是否解析改參數(shù) 如果返回true 代表需要處理 則會(huì)調(diào)用resolveArgument方法進(jìn)行解析
自定義參數(shù)注解(標(biāo)識(shí)注解位置PARAMETER,以及運(yùn)行時(shí)期)
實(shí)現(xiàn)supportsParameter方法 如果方法中包含該注解返回true
將參數(shù)從流中讀取出來(lái)保存到request請(qǐng)求體中,這樣第二次參數(shù)解析調(diào)用就直接從請(qǐng)求體中獲取即可
public class JsonPathArgumentResolver implements HandlerMethodArgumentResolver {private static final String JSON_REQUEST_BODY = "JSON_REQUEST_BODY";@Overridepublic boolean supportsParameter(MethodParameter methodParameter) {return methodParameter.hasParameterAnnotation(JsonParam.class);}@Overridepublic 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;}}然后需要裝載自定義的參數(shù)解析器
最后使用的時(shí)候只需要在參數(shù)前加上自定義的注解即可獲取到傳遞的json值
總結(jié)
以上是生活随笔為你收集整理的springmvc自定义参数解析器的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 42.(leaflet之家)leafle
- 下一篇: QT 关于颜色的总结