如何解决使用Ajax将@RequestBody中的多个变量传递给Spring MVC控制器
你是正确的,@ RequestBody带注释的参数应该可以容纳请求的整个内容并绑定到一个对象,因此你基本上必须使用选项。
如果你绝对想要你的方法,则可以执行一个自定义实现:
说这是你的json:
{
"str1": "test one",
"str2": "two test"
}
并且你想要将其绑定到此处的两个参数:
@RequestMapping(value = "/Test", method = RequestMethod.POST)
public boolean getTest(String str1, String str2)
首先@JsonArg使用JSON路径(如所需信息的路径)定义一个自定义批注say(说):
public boolean getTest(@JsonArg("/str1") String str1, @JsonArg("/str2") String str2)
现在编写一个Custom HandlerMethodArgumentResolver,它使用上面定义的JsonPath来解析实际参数:
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.io.IOUtils;
import org.springframework.core.MethodParameter;
import org.springframework.http.server.ServletServerHttpRequest;
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 com.jayway.jsonpath.JsonPath;
public class JsonPathArgumentResolver implements HandlerMethodArgumentResolver{
private static final String JSONBODYATTRIBUTE = "JSON_REQUEST_BODY";
@Override
public boolean supportsParameter(MethodParameter parameter) {
return parameter.hasParameterAnnotation(JsonArg.class);
}
@Override
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
String body = getRequestBody(webRequest);
String val = JsonPath.read(body, parameter.getMethodAnnotation(JsonArg.class).value());
return val;
}
private String getRequestBody(NativeWebRequest webRequest){
HttpServletRequest servletRequest = webRequest.getNativeRequest(HttpServletRequest.class);
String jsonBody = (String) servletRequest.getAttribute(JSONBODYATTRIBUTE);
if (jsonBody==null){
try {
String body = IOUtils.toString(servletRequest.getInputStream());
servletRequest.setAttribute(JSONBODYATTRIBUTE, body);
return body;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return "";
}
}
现在,只需在Spring MVC中注册即可。有点涉及,但这应该可以正常工作。
解决方法
是否需要包装支持对象?我想做这个:
@RequestMapping(value = "/Test",method = RequestMethod.POST)
@ResponseBody
public boolean getTest(@RequestBody String str1,@RequestBody String str2) {}
并使用这样的JSON:
{
"str1": "test one","str2": "two test"
}
但是我必须使用:
@RequestMapping(value = "/Test",method = RequestMethod.POST)
@ResponseBody
public boolean getTest(@RequestBody Holder holder) {}
然后使用以下JSON:
{
"holder": {
"str1": "test one","str2": "two test"
}
}
那是对的吗?我的另一种选择是将更RequestMethod改为GET并@RequestParam在查询字符串中使用或@PathVariable与一起使用RequestMethod。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。