栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用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中注册即可。有点涉及,但这应该可以正常工作。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/407822.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号