我的 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) 处理这个问题?
最佳答案
@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(..)
。如果未指定值,则假定为参数名称(first
、last
)。否则,从请求中获取值 (order_quantity)
。 -
@ResponseBody
意味着您需要 Jackson 或 JAXB 出现在类路径上,并且<mvc:annotation-driven>
在 xml 配置中。它将分别使用 JSON 或 XML 呈现结果。
如果您想直接将 HTML 写入响应,您有两种选择:
- 将返回类型更改为
String
并将 HTML 返回为String
变量 - 添加
HttpServletResponse response
该方法的参数并使用response.getWriter().write(..)
写入响应的方法
关于java - 如何在 Spring MVC (3.0) 应用程序中处理 Ajax.Request 调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3643203/