首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >使用Ajax将@RequestBody中的多个变量传递给Spring MVC控制器

使用Ajax将@RequestBody中的多个变量传递给Spring MVC控制器
EN

Stack Overflow用户
提问于 2012-10-15 18:17:45
回答 14查看 260.9K关注 0票数 132

是否有必要包装在支持对象中?我想这样做:

代码语言:javascript
复制
@RequestMapping(value = "/Test", method = RequestMethod.POST)
@ResponseBody
public boolean getTest(@RequestBody String str1, @RequestBody String str2) {}

并像这样使用JSON:

代码语言:javascript
复制
{
    "str1": "test one",
    "str2": "two test"
}

但我不得不使用:

代码语言:javascript
复制
@RequestMapping(value = "/Test", method = RequestMethod.POST)
@ResponseBody
public boolean getTest(@RequestBody Holder holder) {}

然后使用这个JSON:

代码语言:javascript
复制
{
    "holder": {
        "str1": "test one",
        "str2": "two test"
    }
}

对吗?我的另一个选择是将RequestMethod更改为GET并在查询字符串中使用@RequestParam,或者将@PathVariableRequestMethod一起使用。

EN

回答 14

Stack Overflow用户

回答已采纳

发布于 2012-10-15 22:19:33

您是对的,带注释的@RequestBody参数应该包含请求的整个正文并绑定到一个对象,因此您基本上必须使用您的选项。

如果你绝对想要你的方法,有一个自定义的实现,你可以这样做:

假设这是你的json:

代码语言:javascript
复制
{
    "str1": "test one",
    "str2": "two test"
}

你想把它绑定到这里的两个参数上:

代码语言:javascript
复制
@RequestMapping(value = "/Test", method = RequestMethod.POST)
public boolean getTest(String str1, String str2)

首先定义一个自定义注释,比如@JsonArg,其中包含指向所需信息的JSON path:

代码语言:javascript
复制
public boolean getTest(@JsonArg("/str1") String str1, @JsonArg("/str2") String str2)

现在编写一个自定义HandlerMethodArgumentResolver,它使用上面定义的JsonPath来解析实际的参数:

代码语言:javascript
复制
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。有点牵涉其中,但这应该能干净利落地工作。

票数 106
EN

Stack Overflow用户

发布于 2015-11-17 13:17:39

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

代码语言:javascript
复制
@RequestMapping(value = "/Test", method = RequestMethod.POST)
@ResponseBody
public boolean getTest(@RequestBody Map<String, String> json) {
   //json.get("str1") == "test one"
}

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

代码语言:javascript
复制
public boolean getTest(@RequestBody ObjectNode json) {
   //json.get("str1").asText() == "test one"
票数 111
EN

Stack Overflow用户

发布于 2019-03-10 13:59:07

用于传递多个对象、参数、变量等。您可以使用jackson库中的ObjectNode作为您的参数来动态完成此操作。你可以这样做:

代码语言:javascript
复制
@RequestMapping(value = "/Test", method = RequestMethod.POST)
@ResponseBody
public boolean getTest(@RequestBody ObjectNode objectNode) {
   // And then you can call parameters from objectNode
   String strOne = objectNode.get("str1").asText();
   String strTwo = objectNode.get("str2").asText();

   // When you using ObjectNode, you can pas other data such as:
   // instance object, array list, nested object, etc.
}

我希望这能有所帮助。

票数 15
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12893566

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档