views:

256

answers:

2

I am using Starbox in my Spring page. I want to submit the user rating so I can store it in the database and not have to refresh the page for the user. How can I have a Spring controller that accepts this value and doesn't have to return a new view. I don't necessarily need to return any updated html - if the user clicks the Starbox, that is all that needs to happen.

Similarly, if I have a form with a submit button and want to save the form values on submit but not necessarily send the user to a new page, how can I have a controller do that? I haven't found a great Spring AJAX tutorial - any suggestions would be great.

A: 

The AJAX logic on the browser can simply ignore any data the server sends back, it shouldn't matter what it responds with.

But if you really want to make sure no response body gets sent back, then there are things you can do. If using annotated controllers, you can give Spring a hint that you don't want it to generate a response by adding the HttpServletResponse parameter to your @RequestMapping method. You don't have to use the response, but declaring it as a parameter tells Spring "I'm handling the response myself", and nothing will be sent back.


edit: OK, so you're using old Spring 2.0-style controllers. If you read the javadoc on the Controller interface, you'll see it says

@return a ModelAndView to render, or null if handled directly

So if you don't want to render a view, then just return null from your controller, and no response body will be generated.

skaffman
But when I implement the org.springframework.web.servlet.mvc.Controller class, I have to override the handleRequest method which returns a ModelAndView object. How do I structure the controller so it doesn't return a new view and send the user to another page? What about on the jsp side - how do I set the values I need in the controller?
David Buckley
I don't understand what you mean by "the jsp side", you just said you *didn't* want to generate a view.
skaffman
I mean how do I actually submit the javascript value to the controller from my existing jsp. I don't want to then send the user to another page, but I have a javascript value that I need to send (the rating, or some other data). I'm new to Ajax. Do I use the prototype Ajax.Request and just specify my controller URL there?
David Buckley
That's a whole different question.
skaffman
A: 

If you use annotations, perhaps the more elegant way to return no view is to declare a void-returning controller method with @ResponseStatus(HttpStatus.OK) or @ResponseStatus(HttpStatus.NO_CONTENT) annotations.

If you use Controller class, you can simply return null from handleRequest.

To post a from to the controller via AJAX call you can use the appropriate features of your client-side Javascript library (if you have one), for example, post() and serialize() in jQuery.

axtavt