如何使用AJAX调用具有指定URL的Controller的@RequestMapping方法

Ket*_*tan 1 ajax spring portlet spring-portlet-mvc

我是Spring和Portlet的新手.我想用jqgrid来显示一些列表.我试图在控制器中调用一个方法,该方法使用@RequestMapping进行注释,但该方法未被调用

我的控制器有以下方法

@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;
    }
}
Run Code Online (Sandbox Code Playgroud)

我的JSP代码使用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){
       ...
    }
});
Run Code Online (Sandbox Code Playgroud)

当上面的AJAX代码正在执行时,我的方法不会被调用.

pap*_*pap 5

你在问题中提到了Portlets.使用Spring和portlet与servlet有点不同.

所以,假设你有一个像这样的portlet

@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
    }
}
Run Code Online (Sandbox Code Playgroud)

如您所见,@ ResourceMapping由资源ID标识.对于资源映射的URL可以使用标准Portlet API的方法和类来创建createResourceURL()javax.portlet.ResourceURL.

如果您更喜欢使用portlet taglibrary,还可以使用<portlet:resourceRequest>标记生成资源URL .

您的视图可能看起来像这样

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>
...
Run Code Online (Sandbox Code Playgroud)