views:

55

answers:

1

I have the following call in my JavaScript:

new Ajax.Request('/orders/check_first_last/A15Z2W2', 
{asynchronous:true, evalScripts:true, 
parameters:{first:$('input_initial').value, 
last:$('input_final').value, 
order_quantity:$('input_quantity').value}});

What do I need to do to get Spring MVC (3.0) to handle this?

+4  A: 
@Controller
@RequestMapping("/orders")
public OrderController {

   @RequestMapping("/check_first_last/{code}")
   @ResponseBody
   public Result checkFirstLast(@PathVariable String code, 
        @RequestParam int first, 
        @RequestParam int last, 
        @RequestParam("order_quantity") int orderQuantity)  {

       // fetch the result
       Result result = fetchResult(...);
       return result;
  }
}

A few notes:

  • @PathVariable gets a variable defined with {..} in the request mapping
  • @RequestParam is equvallent to request.getParameter(..). When no value is specified, the name of the parameter is assumed (first, last). Otherwise, the value (order_quantity) is obtained from the request.
  • @ResponseBody means you need Jackson or JAXB present on the classpath, and <mvc:annotation-driven> in the xml config. It will render the result with JSON or XML respectively.

If you want to write HTML to the response directly, you have two options:

  • change the return type to String and return the HTML as a String variable
  • add an HttpServletResponse response parameter to the method and use the response.getWriter().write(..) method to write to the response

Resource: Spring MVC documentation

Bozho
Brilliant! And if I need to write a response back to the page by replacing some HTML, can I do so from your checkFirstLast() method? Oh wait, is that what you mean by @ResponseBody?
Bowe
@Bowe see my update about that.
Bozho
@Bozho: Wouldn't that call to the write() method result in a brand new HTML page or would it allow me to replace an element on the existing page without a page refresh? I have a text element on the page that I would like to update with a calculation I would perform in the checkFirstLast() method, but without refreshing the page.
Bowe
it won't refresh the page.
Bozho
@Bozho: Thanks. I think I'm starting to understand how it works now.
Bowe
I'd suggest a quick read of the document that I linked. It is really not so long and sheds light on many important aspects.
Bozho