How to call @RequestMapping method of Controller having specified URL using AJAX

Ketan picture Ketan · Aug 29, 2011 · Viewed 10.9k times · Source

I'm very new to Spring and Portlet. I want to use jqgrid to show some list. I am trying to call a method in controller which is annoted with the @RequestMapping but the method is not being called

My Controller has following method

@Controller(value = "myController")
public class MyController {
    @RequestMapping(value="/myURL",method=RequestMethod.GET)
    public @ResponseBody MyDTO  initItemSearchGrid(RenderResponse response, RenderRequest request){
        MyDTO myDto=new MyDTO();
        return myDto;
    }
}

My JSP code using AJAX

var urlink="/myURL"; /* myURL is the exact String written in value Attribute of
                              resourceMapping in Controller*/
$.ajax({
    url :urlink,
    cache: false,
    data:$('#myForm').formSerialize(),
    dataType: "json",
    type: "GET",
    contentType: "application/json; charset=utf-8",
    success: function(jsondata){
       ...
    }
});

When above AJAX code is executing my method is not called.

Answer

pap picture pap · Aug 29, 2011

You mention Portlets in your question. Working with Spring and portlets is a bit different from servlets.

So, assuming you have a portlet like this

@Controller
@RequestMapping("VIEW") // VIEW mapping (as opposed to EDIT)
public class MyPortlet {
    @RenderMapping
    public ModelAndView handleRenderView(RenderRequest request, RenderResponse response) {
        ResourceURL resourceUrl = response.createResourceURL();
        resourceUrl.setResourceID("myResource"); // this is the id used to reference a @ResourceMapping
        ModelAndView ret = new ModelAndView("myPortlet");
        ret.addObject("resourceUrl", resourceUrl.toString());
        return ret;
    }

    @ResourceMapping("myResource")
    public void handleMyResource(ResourceRequest request, ResourceResponse response) {
        OutputStream out = response.getPortletOutputStream();
        // write whatever to output
    }
}

As you can see, the @ResourceMapping is identified by a resource ID. The url for the resource mapping can be created using the standard portlet API methods and classes createResourceURL() and javax.portlet.ResourceURL.

If you prefer to use the portlet taglibrary instead, you can also generate a resource URL using the <portlet:resourceRequest> tag.

Your view might look something like this

myPortlet.jsp

...
<script>
$.ajax({
         url :${resourceUrl},
             cache: false,
             data:$('#myForm').formSerialize(),
             dataType: "json",
             type: "GET",
             contentType: "application/json; charset=utf-8",
         success: function(jsondata){
        .........   
        .........
        .........
         }
        });
</script>
...