How to render JSON presentation / response via AJAX using Spring MVC annotation controller for portlets?

I spent the last six hours trying to find Google and stackoverflow to answer this question. I am originally a PHP developer, so bear with me - returning a JSON array from a PHP controller is trivial.

I am using Spring MVC 3.0, and I just want to return the JSON object back to Javascript from my Spring MVC controller. There seems to be no easy way to do this using the portlet (https://jira.springsource.org/browse/SPR-7344). The solutions I've seen suggest creating another DispatcherServlet that serves JSON responses, but I still have to find a well-documented example of this. If someone knows a good way to accomplish this (preferably with annotations), please tell us!

+5
source share
5 answers

I ended up finding a way to bypass "JSON" from the Spring MVC portlet controller. Here is how I did it.

In my controller:

@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());
}

In "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 URL. eval JSON Javascript , , . , JSON.

+6

Spring 3.0.5 :

  • WebArgumentResolver JSON ResourceRequest
  • MappingJacksonJsonView .

Spring 3.1 - setExtractValueFromSingleKeyModel MappingJacksonJsonView

- intereset, java-

+2

@alex:

    @ResourceMapping(value = "showJson")
    public ModelAndView showJson(ResourceRequest request) {
    ModelAndView mav = new ModelAndView(new 
                                   MappingJacksonJsonView());
    mav.addObject("key", myBeanToBeSerializedAsJson);
    return mav;
    }
0

Spring 3, json, ajax get/post json (...getJSON .postJSON jQuery). Spring MVC.

, .

http://blog.springsource.com/2010/01/25/ajax-simplifications-in-spring-3-0/

-1
source

All Articles