springmvc自定义参数解析器
生活随笔
收集整理的這篇文章主要介紹了
springmvc自定义参数解析器
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
由于開發中一般使用參數提交方式是json格式,對于單個參數的傳遞使用無法接收只能自定義參數解析器處理
springmvc的自定義參數解析器實現HandlerMethodArgumentResolver接口并且實現下面兩個方法
第一個方法是 是否解析改參數 如果返回true 代表需要處理 則會調用resolveArgument方法進行解析
自定義參數注解(標識注解位置PARAMETER,以及運行時期)
實現supportsParameter方法 如果方法中包含該注解返回true
將參數從流中讀取出來保存到request請求體中,這樣第二次參數解析調用就直接從請求體中獲取即可
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;}}然后需要裝載自定義的參數解析器
最后使用的時候只需要在參數前加上自定義的注解即可獲取到傳遞的json值
總結
以上是生活随笔為你收集整理的springmvc自定义参数解析器的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 42.(leaflet之家)leafle
- 下一篇: mysql一个字段为空时使用另一个字段排