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?
@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 torequest.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 aString
variable - add an
HttpServletResponse response
parameter to the method and use theresponse.getWriter().write(..)
method to write to the response
Resource: Spring MVC documentation
精彩评论