註解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();
@Override
public boolean supportsParameter(MethodParameter methodParameter) {
return methodParameter.hasParameterAnnotation(JsonArg.class);
}
@Nullable
@Override
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
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {
resolvers.add(new JsonPathArgumentResolver());
}
}
複製程式碼