Bowe
Bowe

Reputation: 191

How do you handle an Ajax.Request call in a Spring MVC (3.0) app?

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?

Upvotes: 0

Views: 2678

Answers (1)

Bozho
Bozho

Reputation: 597234

@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

Upvotes: 5

Related Questions