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

时间:2010-09-04 17:00:08

标签: java javascript 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}});

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

1 个答案:

答案 0 :(得分: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;
  }
}

一些注意事项:

  • @PathVariable获取在请求映射
  • 中使用{..}定义的变量
  • @RequestParamrequest.getParameter(..)完全相同。如果未指定任何值,则假定参数的名称为firstlast)。否则,将从请求中获取值{order_quantity)
  • @ResponseBody表示您需要在类路径中使用Jackson或JAXB,并在xml配置中使用<mvc:annotation-driven>。它将分别使用JSON或XML呈现结果。

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

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

资源:Spring MVC documentation