【问题标题】:Spring MVC 3.0 Annotated controller not working with JQuery $.post()Spring MVC 3.0 带注释的控制器不适用于 JQuery $.post()
【发布时间】:2011-12-24 05:44:55
【问题描述】:

在 Spring MVC 控制器中,我试图访问 JQuery 简单帖子发送的名称。 我收到错误在@RequestMapping* 中找不到@PathVariable [name] 我哪里出错了?

JQuery 帖子

$.post("addName.htm",{ name: "John"});

弹簧控制器

@RequestMapping(value = "/addName.htm", method = RequestMethod.POST)
public void setAllocations(@PathVariable String name) {

    System.out.println("inside Setting value.... ");
    System.out.println(name);
}

我遇到错误

在@RequestMapping 中找不到@PathVariable [name]

【问题讨论】:

    标签: jquery spring model-view-controller post annotations


    【解决方案1】:

    这不是@PathVariable,您必须改用@RequestParam。试试这个:

    @RequestMapping(value = "/addName.htm", method = RequestMethod.POST)
    public void setAllocations(@RequestParam String name) {
        System.out.println(name);
    }
    

    这就是区别:

    • 路径变量:http://yourhost/{name}/addName.html
    • 请求参数:http://yourhost/addName.html?name={name}

    【讨论】:

    • 没错,@PathVariable 会嵌入到 URL 的主要部分,例如“/addName/{name}”
    【解决方案2】:

    您应该使用@RequestParam 而不是@PathVariable

    @RequestMapping(value = "/addName.htm", method = RequestMethod.POST)
    public void setAllocations(@RequestParam String name) {
      System.out.println("inside Setting value.... ");
      System.out.println(name);
    }
    

    来自docs

    1. @PathVariable 注释参数用于访问 URI 模板变量。
    2. @RequestParam 注释参数用于访问特定的 Servlet 请求参数。

    【讨论】:

      猜你喜欢
      • 2011-05-16
      • 1970-01-01
      • 2010-12-30
      • 1970-01-01
      • 2011-12-21
      • 1970-01-01
      • 1970-01-01
      • 2012-06-16
      • 2015-01-15
      相关资源
      最近更新 更多