【问题标题】:How do you handle an Ajax.Request call in a Spring MVC (3.0) app?您如何处理 Spring MVC (3.0) 应用程序中的 Ajax.Request 调用?
【发布时间】:2010-09-04 17:00:08
【问题描述】:

我的 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) 处理这个问题?

【问题讨论】:

    标签: java javascript ajax spring spring-mvc


    【解决方案1】:
    @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 在请求映射中获取使用 {..} 定义的变量
    • @RequestParam 等同于 request.getParameter(..)。如果未指定值,则假定参数的名称(firstlast)。否则,从请求中获取值 (order_quantity)
    • @ResponseBody 表示您需要 Jackson 或 JAXB 出现在类路径中,<mvc:annotation-driven> 出现在 xml 配置中。它将分别使用 JSON 或 XML 呈现结果。

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

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

    资源:Spring MVC documentation

    【讨论】:

    • 太棒了!如果我需要通过替换一些 HTML 将响应写回页面,我可以从您的 checkFirstLast() 方法中这样做吗?哦等等,这就是@ResponseBody 的意思吗?
    • @Bozho:对 write() 方法的调用不会产生一个全新的 HTML 页面,还是允许我在不刷新页面的情况下替换现有页面上的元素?我在页面上有一个文本元素,我想通过在 checkFirstLast() 方法中执行的计算来更新它,但不刷新页面。
    • @Bozho:谢谢。我想我现在开始了解它的工作原理了。
    • 我建议快速阅读我链接的文档。它真的不长,阐明了许多重要方面。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-01
    • 1970-01-01
    • 2011-07-01
    • 1970-01-01
    • 2013-02-15
    相关资源
    最近更新 更多