我该如何使通过AJAX一个JSON视图/响应使用Spring MVC基于注解的控制器的portlet?注解、我该、视图、控制器

2023-09-10 16:09:42 作者:你是嫌我太萌了吗∧

我花了最近六小时冲刷谷歌和计算器对于这个问题的答案。我原本是一个PHP开发人员,所以和我一起承担 - 返回一个JSON阵列从一个PHP控制器是微不足道的。

I've spent the last six hours scouring Google and stackoverflow for an answer to this question. I'm originally a PHP developer, so bear with me - returning a JSON array from a PHP controller is trivial.

我使用Spring MVC的3.0,我只是想从我的Spring MVC控制器返回一个JSON对象回一些JavaScript。看来,有没有简单的方法使用portlet(https://jira.springsource.org/browse/SPR-7344),以目前做到这一点。解决方案我已经看到了建议创建另一个DispatcherServlet的作用是提供了JSON的反应,但我还没有找到这样的证据充分的例子。如果有人知道做到这一点(preferably与注解)的好办法,请大家告诉!

I'm using Spring MVC 3.0, and I simply want to return a JSON object back to some Javascript from my Spring MVC Controller. It seems that there is no easy way to currently do this using a portlet (https://jira.springsource.org/browse/SPR-7344). Solutions I have seen suggest creating another DispatcherServlet that serves up JSON responses, but I have yet to find a well-documented example of this. If anyone knows a good way to accomplish this (preferably with annotations), please do tell!

推荐答案

我最终找到一个解决方法,从一个Spring MVC的portlet控制器返回JSON。以下是我做到了。

I ended up finding a workaround to return "JSON" from a Spring MVC portlet controller. Here's how I did it.

在我的控制器:

@ResourceMapping("ajaxTest")
public void ajaxHandler(ResourceRequest request, ResourceResponse response)
        throws IOException {
    OutputStream outStream = response.getPortletOutputStream();
    StringBuffer buffer = new StringBuffer();

    Map<String, String> testMap = new HashMap<String, String>();
    testMap.put("foo", "bar");

    String test = new JSONObject(testMap).toString();
    buffer.append(test);

    outStream.write(buffer.toString().getBytes());
}

在view.jsp的

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

<script type="text/javascript">
  $.get('<%= ajaxtest %>', function(response) {
    var json = eval('(' + response + ')');
  });
</script>

由于@ResourceMapping注释目前不支持返回JSON,我只是用org.json.JSONObject我的地图转换成JSON对象,然后返回此对象的toString()。 @ResourceMapping的值应该匹配resourceURL的ID。使用eval的JSON字符串转换为Javascript会带来安全风险,但我只是包含它,因为它是最简单的例子。如果你担心安全性,使用JSON解析器。

Since the @ResourceMapping annotation currently doesn't support returning JSON, I just used org.json.JSONObject to convert my map to a JSON object, and then returned the toString() of this object. The value of @ResourceMapping should match the id of the resourceURL. The use of eval to convert the JSON string to Javascript poses a security risk, but I just included it because it's the simplest example. If you are worried about security, use a JSON parser.