你如何在Spring MVC(3.0)应用程序中处理Ajax.Request调用?

Bow*_*owe 0 javascript java ajax spring spring-mvc

我的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}});
Run Code Online (Sandbox Code Playgroud)

我需要做些什么来让Spring MVC(3.0)来处理这个问题?

Boz*_*zho 5

@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;
  }
}
Run Code Online (Sandbox Code Playgroud)

几点说明:

  • @PathVariable获取{..}在请求映射中定义的变量
  • @RequestParam是平等的request.getParameter(..).如果未指定任何值,则假定参数名称为(first,last).否则,该值(order_quantity)从请求中获取).
  • @ResponseBody意味着您需要在类路径和<mvc:annotation-driven>xml配置中存在Jackson或JAXB .它将分别使用JSON或XML呈现结果.

如果要直接将HTML写入响应,则有两种选择:

  • 将返回类型更改为String并将HTML作为String变量返回
  • HttpServletResponse response在方法中添加一个参数,并使用该response.getWriter().write(..)方法写入响应

资源:Spring MVC文档