省掉bean自定义spring mvc注解注入json值
生活随笔
收集整理的這篇文章主要介紹了
省掉bean自定义spring mvc注解注入json值
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
注解hello(@JsonArg String msg)直接獲取body{"msg": "ok!"}中的ok!,不用定義一個bean來接收沒有的字段。
JsonPathArgumentResolver.java
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.tianxia.server.util.Requests; import org.springframework.core.MethodParameter; import org.springframework.lang.Nullable; import org.springframework.web.bind.support.WebDataBinderFactory; import org.springframework.web.context.request.NativeWebRequest; import org.springframework.web.method.support.HandlerMethodArgumentResolver; import org.springframework.web.method.support.ModelAndViewContainer;import javax.servlet.http.HttpServletRequest; import java.io.BufferedReader; import java.io.IOException;public class JsonPathArgumentResolver implements HandlerMethodArgumentResolver {private static final String JSONBODYATTRIBUTE = "JSON_REQUEST_BODY";private static final ObjectMapper objectMapper = new ObjectMapper();public boolean supportsParameter(MethodParameter methodParameter) {return methodParameter.hasParameterAnnotation(JsonArg.class);}public Object resolveArgument(MethodParameter methodParameter, @Nullable ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, @Nullable WebDataBinderFactory webDataBinderFactory) throws Exception {String jsonBody = getRequestBody(nativeWebRequest);JsonNode rootNode = objectMapper.readTree(jsonBody);JsonNode node = rootNode.path(methodParameter.getParameterName());if (node.toString().equals("")) return null;return objectMapper.readValue(node.toString(), methodParameter.getParameterType());}private String getRequestBody(NativeWebRequest webRequest){HttpServletRequest servletRequest = webRequest.getNativeRequest(HttpServletRequest.class);String jsonBody = (String) webRequest.getAttribute(JSONBODYATTRIBUTE, NativeWebRequest.SCOPE_REQUEST);if (jsonBody == null){jsonBody = Requests.readBody(servletRequest);webRequest.setAttribute(JSONBODYATTRIBUTE, jsonBody, NativeWebRequest.SCOPE_REQUEST);}return jsonBody;}}復制代碼WebConfig.java
public class WebConfig implements WebMvcConfigurer {public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {resolvers.add(new JsonPathArgumentResolver());} } 復制代碼總結
以上是生活随笔為你收集整理的省掉bean自定义spring mvc注解注入json值的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 我们用5分钟写了一个跨多端项目
- 下一篇: 使用百度API进行关键点识别