Spring MVC Missing request attribute

2020-04-18 05:53发布

问题:

So i'm currently taking a course on udemy about Spring MVC. In the current section there's a simple form being build to submit firstname and lastname.

Hey user, may i know your name?
<form:form action="hello" modelAttribute="info">
    First Name: <form:input path="firstName" />
    Last Name: <form:input path="lastName" />
    <input type="submit" value="Submit" />
</form:form>

The input gets submitted via an Information Class to the HelloController

@Controller
public class HelloController {

@RequestMapping("/hello")
public ModelAndView helloWorld(@RequestAttribute("info") Information userInfo) {
    ModelAndView model = new ModelAndView("hello");

    model.addObject("firstName", userInfo.getFirstName());
    model.addObject("lastName", userInfo.getLastName());

    return model;
}

@RequestMapping("/")
public ModelAndView homepage() {
    ModelAndView model = new ModelAndView("index", "info", new Information());

    return model;
}

Information Class:

public class Information {
private String firstName;
private String lastName;

public String getFirstName() {
    return firstName;
}
public void setFirstName(String firstName) {
    this.firstName = firstName;
}
public String getLastName() {
    return lastName;
}
public void setLastName(String lastName) {
    this.lastName = lastName;
}   
}

Next the informatiion Class should be forwarded to the view file hello.jsp

<body>
<h2> Hello ${firstName} ${lastName} </h2><br/>

</body>

I thought this is actually rather simple, but after submitting the form i get the exception "Missing request attribute 'info' of type Information". I double-checked my code against the code from the udemy instructor, but couldn't find any errors. Can someone help?

On a sidenote, i don't know if it has anything todo with this error, but after adding @Controllerto the Class, auto-completion in eclipse stops working for this Class. After removing the annotation auto-completion starts towork again.

回答1:

You are using the wrong annotation. @RequestAttribute is for retrieving attributes set on the HttpServletRequest using setAttribute. You however want to bind request parameters to an object, for that you should use the @ModelAttribute annotation instead.

@RequestMapping("/hello")
public ModelAndView helloWorld(@ModelAttribute("info") Information userInfo) { ... }

Changing the annotation will make it work.