【问题标题】:@ResourceMapping that accepts JSON from Ajax request@ResourceMapping 接受来自 Ajax 请求的 JSON
【发布时间】:2015-04-02 20:03:05
【问题描述】:

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

我有这个:

查看面:

<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>

控制器端:

@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 魔法将这个 JSON 数据自动映射到我自己的模型? 注意:它是 Spring Portlet MVC,而不是常规 Spring MVC..

【问题讨论】:

    标签: ajax json spring spring-portlet-mvc


    【解决方案1】:

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

    我们通过实现自定义视图类型和模型以及视图解析器来做到这一点。

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

    【讨论】:

      【解决方案2】:

      你需要像这样构建你的 json 对象:

      var jsonObj = {
                      user: "Korneel",
                      password: "testpassword",
                      "type.testParam" : "test"
                  };
      
      $.ajax({
                  dataType: "json",
                  contentType:"application/json",
                  mimeType: 'application/json',
                  url:"<%=getTest%>",
                  data:jsonObj,
                  success : function(data) {
                      $("#ajaxResponse").html(data['testString']);
                  }
              });
      

      在你的控制器中你应该使用@ModelAttribute注解:

      @ModelAttribute(value = "jsonObj")
      public JsonObjCommand obtenerJsonObjCommand() {
          JsonObjCommand jsonObjCommand = new JsonObjCommand();
          return jsonObjCommand;
      }
      
      @ResourceMapping(value = "ajaxTest")
      public void ajaxTestMethod(
              ResourceRequest request,
              ResourceResponse response,
              @ModelAttribute(value = "jsonObj") JsonObjCommand jsonObjCommand)
              throws IOException, ParseException {
          LOGGER.debug("USER: " + jsonObjCommand.getUser());
          LOGGER.debug("Password: " + jsonObjCommand.getPassword());
          LOGGER.debug("TestParam: " + jsonObjCommand.getType().getTestParam());
          LOGGER.debug("ajax method");
      
          JSONObject json = JSONFactoryUtil.createJSONObject();
          json.put("testString", "Ik ben succesvol verstuurd geweest!");
          response.getWriter().write(json.toString());
      }
      

      别忘了你的豆子:

      public class JsonObjCommand {
      
      private String user;
      private String password;
      private TypeJson type;
      
      public String getUser() {
          return user;
      }
      public void setUser(String user) {
          this.user = user;
      }
      public String getPassword() {
          return password;
      }
      public void setPassword(String password) {
          this.password = password;
      }
      public TypeJson getType() {
          return type;
      }
      public void setType(TypeJson type) {
          this.type = type;
      }
      
      }
      
      public class TypeJson {
      
      private String testParam;
      
      public String getTestParam() {
          return testParam;
      }
      
      public void setTestParam(String testParam) {
          this.testParam = testParam;
      }
      
      }
      

      【讨论】:

        【解决方案3】:

        根据文档,@RequestBody 仅在 Servlet 环境中受支持,而不是 Portlet 环境(@ResponseBody 相同)。因此,您似乎无法使用该功能。

        【讨论】:

          猜你喜欢
          • 2020-12-21
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-07-31
          • 1970-01-01
          • 2018-10-15
          • 2020-12-20
          • 2017-07-16
          相关资源
          最近更新 更多