ajax - @ResourceMapping 接受来自 Ajax 请求的 JSON

标签 ajax json spring spring-portlet-mvc

我正在搜索如何在 Spring Portlet MVC 中的 @ResourceMapping 中解释 JSON 参数。当我添加@RequestBody 时,我收到消息:@RequestBody 不受支持...真的卡在了这个上。

我有这个:

View 侧:

<portlet:resourceURL var="getTest" id="ajaxTest" ></portlet:resourceURL>

    <p>
        <button onClick="executeAjaxTest();">Klik mij!</button>
        <button onClick="$('#ajaxResponse').html('');">Klik mij!</button>
    </p>
    <p>
        <h3>Hieronder het antwoord:</h3>
        <h4 id="ajaxResponse"></h4>
    </p>

    <script>
        function executeAjaxTest() {

            var jsonObj = {
                    user: "Korneel",
                    password: "testpassword",
                    type: {
                        testParam: "test",
                    }
                }

            console.debug(JSON.stringify(jsonObj));
            $.ajax({
                dataType: "json",
                contentType:"application/json",
                mimeType: 'application/json',
                url:"<%=getTest%>",
                data:JSON.stringify(jsonObj),
                success : function(data) {
                    $("#ajaxResponse").html(data['testString']);
                }
            });

        }
    </script>

Controller 端:

@ResourceMapping(value="ajaxTest")
    @ResponseBody
    public void ajaxTestMethod(ResourceRequest request, ResourceResponse response) throws IOException, ParseException {

        LOGGER.debug("ajax method");

        JSONObject json = JSONFactoryUtil.createJSONObject();
        json.put("testString", "Ik ben succesvol verstuurd geweest!");
        response.getWriter().write(json.toString());
}

如何使用 spring magic 将此 JSON 数据自动映射到我自己的模型? 注意:这是 Spring Portlet MVC,不是常规的 Spring MVC..

最佳答案

@ResponseBody 注释在 Spring MVC portlet 框架中不支持开箱即用,但您可以自己实现 @ResponseBody 处理。

我们通过实现自定义 View 类型和模型以及 View 解析器来实现。

  1. 实现自定义模型和 View 解析器 (ModelAndViewResolver),比方说 JsonModelAndViewResolver。
  2. 在 resolveModelAndView 方法中,检查 Controller 方法是否有 @ResponseBody 注释(或更具体的条件来识别 JSON 输出 - 例如注释 + 需要支持的 mime 类型)。
  3. 如果是,请返回您的自定义 View 实现 - 比方说 SingleObjectJson View (扩展 AbstractView)。
  4. 将您要序列化的对象传递给 View 实例。
  5. View 会将对象序列化为 JSON 格式并将其写入响应(通过在 renderMergedOutputModel 方法中使用 Jackson、Gson 或其他框架)。
  6. 将新解析器注册为 AnnotationMethodHandlerAdapter.customModelAndViewResolvers。

关于ajax - @ResourceMapping 接受来自 Ajax 请求的 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28302074/

相关文章:

javascript - 无法使用 ajax 响应数据更新 Angular 服务中的变量,并使用 is 进行过滤

php - 插入后检索记录 ID

json - 在 trait Reads 中读取的覆盖方法。

spring - Angular2 通过 Basic Auth 访问 REST 抛出 "Response for preflight has invalid HTTP status code 401"

java - 找不到 Spring MVC 带注释的 Controller

java - 使用 Spring security 和 JWT 在 REST 中使用 <img> 标签访问私有(private)图像

javascript - 使用ajaxForm提交表单而不刷新页面

angularjs - Angular JS 无法在页面/路由更改时呈现社交媒体小部件

Ruby - 迭代解析的 JSON

json - 在 Zend 框架中为 Android/Iphone 应用程序创建 Json Web 服务时使用什么