方法参数类型 [java.lang.Integer] 缺少 URI 模板变量“studentId” - Spring MVC

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20713522/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 03:45:51  来源:igfitidea点击:

Missing URI template variable 'studentId' for method parameter type [java.lang.Integer] - Spring MVC

javaspring-mvcuri

提问by just_a_girl

I'm getting this error when I try to redirect to a certain view.

当我尝试重定向到某个视图时出现此错误。

In one handler method i have:

在一种处理程序方法中,我有:

// get student ID, add it to model, and return redirect URI
Integer studentId = student.getStudentId();
model.addAttribute("studentId", studentId);
return "redirect:/students/{studentId}";

But I'm not getting the parameter studentIdin this handler method:

但是我没有studentId在这个处理程序方法中得到参数:

@RequestMapping(value="/{student}", method = RequestMethod.GET)
public String getStudent(@PathVariable Integer studentId, Model model) {

    Student student = studentService.get(studentId);
    model.addAttribute("student", student);

    return "student";
}

What am I missing here?

我在这里缺少什么?

采纳答案by Sotirios Delimanolis

If you don't specify the name of the path variable, Spring tries to use the name of your parameter.

如果您没有指定路径变量的名称,Spring 会尝试使用您的参数名称。

Therefore in

因此在

@RequestMapping(value="/{student}", method = RequestMethod.GET)
public String getStudent(@PathVariable Integer studentId, Model model) {

Spring will try to find a path variable called studentIdwhile you have a path variable called student.

studentId当您有一个名为 的路径变量时,Spring 将尝试找到一个名为的路径变量student

Just add a value attribute

只需添加一个值属性

@PathVariable("student") Integer studentId

or change the parameter name.

或更改参数名称。