本文介绍了Spring MVC缺少请求属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我目前正在参加有关Spring MVC的udemy课程。在当前部分中,正在构建一个简单的表单来提交名字和姓氏。

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>

输入信息通过信息类提交给HelloController

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;
}

信息类别:

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;
}
}

接下来应将信息类转发到视图文件hello.jsp

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

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

</body>

我以为这实际上很简单,但是在提交表单后,我得到了例外缺少请求属性信息类型的信息。我与udemy讲师的代码进行了双重检查,但没有发现任何错误。有人可以帮忙吗?

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?

在旁注中,我不知道它是否与该错误有关,但是在添加了 @Controller 到该类,eclipse中的自动完成功能将停止为该类工作。删除注释后,自动完成功能将再次开始起作用。

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.

推荐答案

您使用了错误的注释。 用于检索使用 setAttribute HttpServletRequest 上设置的属性$ c>。但是,您希望将请求参数绑定到对象,因此应使用批注。

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.

这篇关于Spring MVC缺少请求属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 04:44