使用 Ajax 将@RequestBody 中的多个变量传递给 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"
    }
}

那是对的吗? My other option would be to change the RequestMethod to GET and use @RequestParam in query string or use @PathVariable with either RequestMethod

原文由 NimChimpsky 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.1k
2 个回答

你是对的,@RequestBody 注释参数应该包含请求的整个主体并绑定到一个对象,所以你基本上必须选择你的选项。

如果您绝对想要您的方法,那么您可以执行自定义实现:

说这是你的 json:

 {
    "str1": "test one",
    "str2": "two test"
}

并且您想将其绑定到此处的两个参数:

 @RequestMapping(value = "/Test", method = RequestMethod.POST)
public boolean getTest(String str1, String str2)

首先定义一个自定义注解,比如 @JsonArg ,其中的 JSON 路径类似于您想要的信息的路径:

 public boolean getTest(@JsonArg("/str1") String str1, @JsonArg("/str2") String str2)

现在编写一个自定义 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 注册它。有点复杂,但这应该可以正常工作。

原文由 Biju Kunjummen 发布,翻译遵循 CC BY-SA 3.0 许可协议

虽然 @RequestBody 必须映射到单个对象,但该对象可以是 Map ,因此这为您提供了实现目标的好方法(无需编写一次性支持对象):

 @RequestMapping(value = "/Test", method = RequestMethod.POST)
@ResponseBody
public boolean getTest(@RequestBody Map<String, String> json) {
   //json.get("str1") == "test one"
}

如果你想要一个完整的 JSON 树,你也可以绑定到 Jackson 的 ObjectNode

 public boolean getTest(@RequestBody ObjectNode json) {
   //json.get("str1").asText() == "test one"

原文由 Kong 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题