Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I return a view from a spring controller using an ajax request?

Tags:

java

ajax

spring

I make an ajax request using jquery, this calls the following spring controller:

@RequestMapping(value = "/dialogController", method = RequestMethod.POST)
public String dialogController(Model model, @RequestBody MyClass myclass) {
  myClass.setTitle("SUCCESS");       
  model.addAttribute("myClass",myClass);
  return "dialogContent";  //this resolves to dialogContent.jsp
}

However I receive the following error :

org.springframework.web.HttpRequestMethodNotSupportedException: 
Request method 'POST' not supported

And if required here is the ajax call I am making using jQuery:

   jq.postJSON("/dialogController", myClass, function(data) {
      myDialog.html(data);
      myDialog.dialog('open'); 
      //dialog settings previously assigned, 
      //but the success callback function is not reached anyway
    });

EDIT I get same error if I use :

jq.ajax({
  type: 'POST',
  url: "/dialogController",
  data:myClass,
  success:  function(data) {            
         previewDialog.html(data);
         previewDialog.dialog('open');
  });
like image 802
NimChimpsky Avatar asked Oct 18 '25 07:10

NimChimpsky


1 Answers

For the viewers at home ... I found that the problem was due to the method signature defined in controller not matching the ajax call. I removed the Model model parameter from controller method. I also then realized I had to also return a new model and view; here is the working code:

var myJSON  = {"title":"help"}; 
myJSON = JSON.stringify(myJSON);

<c:url var="postAndView" value="/PostJSONMAV" />
...
jQuery.ajax({
    type: 'POST',
    url: "${postAndView}",
    data:myJSON,
    contentType: "application/json",
    success:  function(data) {          
        previewDialog.html(data);
        previewDialog.dialog('open');
    }
});

I changed to the ajax call but jQuery.postJSON() will probably work aswell. And shown below is the new controller code, which corrrectly adds a new object to model and returns jsp page, which is opened up in a dialog:

@RequestMapping(value = "/PostJSONMAV", method = RequestMethod.POST)
public  ModelAndView postJSON(@RequestBody MyClass myClass) {
    ModelAndView mav = new ModelAndView();
    myClass.setTitle("SUCCESS");
    mav.setViewName("dialogContent");
    mav.addObject("myClass", myClass);
    return mav;     
}
like image 137
NimChimpsky Avatar answered Oct 19 '25 21:10

NimChimpsky



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!