Sunday, September 25, 2011

Spring Portlet MVC - Ajax

I have created an example that shows how you can use @ResourceMapping annotation of Spring Portlet MVC to return JSP content as response to an Ajax request. You can find the details of the example in the following post in Author Online Forum of Portlets in Action: http://www.manning-sandbox.com/thread.jspa?threadID=46135&tstart=0

4 comments:

  1. It's a nice example, but a very limited one. What's really missing is the @RequestBody stuff for mapping JSON to Models... as it turned out, @ResoureseMapping is not Working with @RequestBody.

    Therefore, I ended up doing it by hand using Jackson and the Validator...

    ReplyDelete
  2. Can you show some code examples how u did it.
    As in I wanted to post json data to a controller but it says @RequestBody not supported.

    ReplyDelete
    Replies
    1. Try this
      http://liferayiseasy.blogspot.in/2015/03/ajax-call-in-spring-mvc-portlet.html

      Delete
  3. @RenderMapping
    public ModelAndView handleRenderRequest (RenderRequest request, RenderResponse response)throws Exception {
    Map<String, Object> model = new HashMap<String, Object>();
    return new ModelAndView("view", model);
    }


    @ResourceMapping
    public void ajaxHandler(ResourceRequest request, ResourceResponse response) {
    String id= request.getParameter("id");
    List<SomeClass> aClassList =aService.findById(Integer.parseInt(id));

    String test= JSONFactoryUtil.serialize(aClassList);

    response.setContentType("text/json");

    try {
    response.getWriter().write(test);
    } catch (IOException e) {
    LOGGER.error(e);
    }
    }

    and in jsp put:
    <portlet:resourceURL var="getJsonURL" id="ajaxHandler"/>

    <script>
    function test(){
    $.ajax({
    type: "POST",
    url: "<%=getJsonURL%>",
    data: { id: 1 }
    }).done(function( msg ) {
    console.log(msg);
    });

    </script>

    ReplyDelete