java.lang.IllegalStateException: BindingResult 和 bean 名称“command”的普通目标对象都不能用作请求属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29003809/
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
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'command' available as request attribute
提问by Mdumanoj
I am beginner to Spring MVC Framework. I started to learn Spring two days back. For learning purpose I am developing one simple Application. i.e., Get user input from form and display values in another page. I got an Exception " java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'command' available as request attribute". I cant figure out what's wrong in my code. I searched Google and tried many solution but the problem is still here.
我是 Spring MVC 框架的初学者。两天前我开始学习 Spring。出于学习目的,我正在开发一个简单的应用程序。即,从表单获取用户输入并在另一个页面中显示值。我得到了一个异常“java.lang.IllegalStateException:对于 bean 名称‘command’既没有 BindingResult 也没有普通目标对象作为请求属性可用”。我无法弄清楚我的代码有什么问题。我搜索了谷歌并尝试了很多解决方案,但问题仍然存在。
Here is my view index.jsp
这是我的观点 index.jsp
<form:form action="/addDisplay" method="POST">
<form:label path="name"><h3>Name</h3></form:label>
<form:input type="text" path="name" cssClass="form-control text-center" required="required"/>
<form:label path="age"><h3>Age</h3></form:label>
<form:input type="number" path="age" cssClass="form-control text-center" required="required"/>
<form:label path="work"><h3>Work Place</h3></form:label>
<form:input type="text" path="work" cssClass="form-control text-center" required="required"/>
<form:label path="designation"><h3>Designation</h3></form:label>
<form:input type="text" path="designation" cssClass="form-control text-center" required="required"/>
<form:label path="area"><h3>Area</h3></form:label>
<form:input type="text" path="area" placeholder="Where Are You From?" cssClass="form-control text-center" required="required"/>
<form:label path="mobile"><h3>Mobile Number</h3></form:label>
<form:input type="number" path="mobile" placeholder="Your Mobile Number.!" cssClass="form-control text-center" required="required"/>
<form:label path="email"><h3>Email</h3></form:label>
<form:input type="email" path="email" placeholder="Your Email Id..!" cssClass="form-control text-center" required="required"/>
<br/>
<input type="submit" value="Generate" class="btn btn-success form-control"/>
</form:form>
myself.jsp
我自己.jsp
<div style="margin-top: 3%; font-size: 20px;">
<h3>My Introduction.</h3>
<p>
Hi, I am ${name} my age is ${age} and I am from ${area}. I am working as a ${designation}
in ${work}. You can contact me in my mobile ${mobile} and You can also shoot mail to
${email}.
</p>
</div>
web.xml
网页.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>SpringWork</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/mvc-dispatcher-servlet.xml</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
</web-app>
mvc-dispatcher-servlet.xml
mvc-dispatcher-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="com.infofaces.spring.form" />
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/pages/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="com/infofaces/spring/form/MySelf" />
</bean>
<mvc:resources mapping="/resources/**" location="/resources/" />
<mvc:annotation-driven />
</beans>
My model name is Myself.java and it has private variables and getter, setter methods for that variable. Here is my controller.
我的模型名称是 Myself.java,它具有私有变量和该变量的 getter、setter 方法。这是我的控制器。
HelloController.java
你好控制器.java
package com.infofaces.spring.form;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class HelloController {
@RequestMapping(value = "/display", method = RequestMethod.GET)
public ModelAndView display() {
return new ModelAndView("myself", "command", new MySelf());
}
@RequestMapping(value="/addDisplay", method = RequestMethod.POST)
public String addDisplay(@ModelAttribute("command") MySelf myself, ModelMap model) {
model.addAttribute("name",myself.getName());
model.addAttribute("age", myself.getAge());
model.addAttribute("work", myself.getWork());
model.addAttribute("designation", myself.getDesignation());
model.addAttribute("mobile", myself.getMobile());
model.addAttribute("email", myself.getEmail());
return "myself";
}
}
Full Stack Trace.
全栈跟踪。
type Exception report
message java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'command' available as request attribute
description The server encountered an internal error that prevented it from fulfilling this request.
exception
org.apache.jasper.JasperException: java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'command' available as request attribute
org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:549)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:465)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:395)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:339)
javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
root cause
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'command' available as request attribute
org.springframework.web.servlet.support.BindStatus.<init>(BindStatus.java:141)
org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getBindStatus(AbstractDataBoundFormElementTag.java:179)
org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getPropertyPath(AbstractDataBoundFormElementTag.java:199)
org.springframework.web.servlet.tags.form.LabelTag.autogenerateFor(LabelTag.java:130)
org.springframework.web.servlet.tags.form.LabelTag.resolveFor(LabelTag.java:120)
org.springframework.web.servlet.tags.form.LabelTag.writeTagContent(LabelTag.java:90)
org.springframework.web.servlet.tags.form.AbstractFormTag.doStartTagInternal(AbstractFormTag.java:103)
org.springframework.web.servlet.tags.RequestContextAwareTag.doStartTag(RequestContextAwareTag.java:80)
org.apache.jsp.index_jsp._jspx_meth_form_005flabel_005f0(index_jsp.java:265)
org.apache.jsp.index_jsp._jspx_meth_form_005fform_005f0(index_jsp.java:170)
org.apache.jsp.index_jsp._jspService(index_jsp.java:105)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:395)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:339)
javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
Please help to find problem in my code. Thanks in advance.
请帮助在我的代码中找到问题。提前致谢。
回答by Rajeev
You are missing commandName="command"
in your index.jsp file .
您commandName="command"
在 index.jsp 文件中丢失了。
<form:form action="/addDisplay" method="POST" commandName="command" >
Make sure that command
object is available in your request attribute before index.jsp is being processed. I hope this would work.
command
在处理 index.jsp 之前,确保该对象在您的请求属性中可用。我希望这会奏效。
EDIT : As you said in comment when you call index.jsp definatily you will get java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'command' available as request attribute
error.
编辑:正如您在评论中所说,当您明确调用 index.jsp 时,您会收到 java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'command' available as request attribute
错误消息。
Because when your jsp is being rendered command object not available for that first you have to make request to controller , put object into Model name it command
and then provide view name index.jsp
因为当你的jsp被渲染时命令对象不可用,你首先必须向控制器发出请求,将对象放入模型名称中command
,然后提供视图名称index.jsp
For example :
例如 :
@RequestMapping(value = "/index", method = RequestMethod.GET)
public ModelAndView display() {
return new ModelAndView("index", "command", new MySelf());
}
Now you won't get that error. I hope this would work.
现在你不会得到那个错误。我希望这会奏效。
回答by Master Slave
Instead of forwarding to your index.jsp via welcome-fileslist, you should add
而不是通过欢迎文件列表转发到您的 index.jsp ,您应该添加
<mvc:view-controller path="/" view-name="index"/>
to your mvc configuration, and an accompanying controller mapping where you will add the command object to the model, e.g.
到您的 mvc 配置,以及随附的控制器映射,您将在其中将命令对象添加到模型中,例如
@RequestMapping(value = "/", method = RequestMethod.GET)
public String home(Model model) {
model.addAttribute("command", new MySelf());
return "index";
}
Your problem is that you got forwarded to the index.jsp
via welcome-files and the request wasn't process by spring. Yet you use spring's form:form
which if not otherwise renamed via commandNameor modelAttributeattributes expects an object with the key commandinside the request attributes
你的问题是你被转发到了index.jsp
通过欢迎文件并且请求没有在春天处理。然而,您使用 spring 的form:form
,如果没有通过commandName或modelAttribute属性以其他方式重命名,则需要在请求属性中包含关键命令的对象
回答by Abhishek Nayak
you have used spring form tag in index.jsp where a command/modelAttribute object should be available as a request parameter to bind form data, which is you have not done and the exception message what it says.
您在 index.jsp 中使用了 spring 表单标记,其中命令/modelAttribute 对象应该可用作绑定表单数据的请求参数,这是您尚未完成的操作以及它所说的异常消息。
To solve this problem follow below steps:
要解决此问题,请按照以下步骤操作:
Step 1:Remove all welcome-file-list from web.xml.
步骤 1:从 web.xml 中删除所有欢迎文件列表。
Step 2:add "/" into display GET handler.
第 2 步:将“/”添加到显示 GET 处理程序中。
@RequestMapping(value = {"/", "/display"}, method = RequestMethod.GET)
public ModelAndView display() {
return new ModelAndView("myself", "command", new MySelf());
}
Step 3:add modelAttribute name in form tag:
第 3 步:在表单标签中添加 modelAttribute 名称:
<form:form action="${pageContext.request.contextPath}/addDisplay"
method="POST"
modelAttribute="command">
回答by OO7
Consider, you have HTML form like below
考虑一下,您有如下所示的 HTML 表单
Login Form:
登录表单:
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<body>
<form:form action="doLogin.html" method="post" modelAttribute="loginEntity" name="loginForm">
<!-- Form inputs -->
</form:form>
</body>
</html>
You want to perform login by calling action doLogin.html
. As you have specified modelAttribute="loginEntity"
attribute in Spring form which is created using above code snippet. You must set an empty Object of model which hold required request params in Controller.Observe below code carefully:-
您想通过调用 action 来执行登录doLogin.html
。正如您modelAttribute="loginEntity"
在使用上述代码片段创建的 Spring 表单中指定的属性一样。您必须设置一个空的模型对象,该对象在控制器中保存所需的请求参数。仔细观察以下代码:-
Model Class:
型号分类:
public class Login {
private String userName = "";
private String password = "";
// getters/setters
}
Controller Class:
控制器类:
@Controller
public class LoginController {
@RequestMapping(value = "/showLoginForm", method = RequestMethod.GET)
public ModelAndView showLoginForm() {
System.out.println("In login form...");
ModelAndView mv = new ModelAndView("login");
mv.addObject("loginEntity", new Login());
return mv;
}
@RequestMapping(value = "/doLogin", method = RequestMethod.POST)
public ModelAndView doLogin(@ModelAttribute Login login, BindingResult result) {
String userName = login.getUserName();
String password = login.getPassword();
if ("OO7".equals(userName) && "OO7".equals(password)) {
return new ModelAndView("forward:success.html");
} else {
return new ModelAndView("forward:failure.html");
}
}
}
In the controller, I have added an empty model new Login()
for the modelAttribute loginEntity
in the showLoginForm()
function. This will map all the request parameters & allow to set &/or retrieve values from them.
在控制器中,我已经添加空模型new Login()
的的ModelAttributeloginEntity
在showLoginForm()
功能。这将映射所有请求参数并允许设置和/或从中检索值。
Now, you can add link to your index.jsp
which will give a call to Controller to display login.jsp
just like below :-
现在,您可以添加指向您的链接,index.jsp
该链接将调用 Controller 以显示login.jsp
如下:-
Index Page:
索引页:
<html>
<body>
<ul>
<li><a href="showLoginForm.html">Login</a></li>
</ul>
</body>
</html>
Overall Request Flow:
整体请求流程:
- At application start
index.jsp
will load having a link tologin.jsp
. - On click of link
<a href="showLoginForm.html">Login</a>
a call to controller is made & it searches for request mapping showLoginFormin it. - Once he found the specified mapping, he proceed further to display
login.jsp
page. - On submit of the login form, a request for
doLogin.html
is made. Once again control goes to Controller to search fordoLogin
request mapping. - Once he found
doLogin
request mapping, depending on the login credentials, you will be redirected to eithersuccess.jsp
orfailure.jsp
page.
- 在应用程序启动时
index.jsp
将加载一个链接到login.jsp
. - 单击链接时,
<a href="showLoginForm.html">Login</a>
将调用控制器并在其中搜索请求映射showLoginForm。 - 一旦找到指定的映射,他就继续显示
login.jsp
页面。 - 在提交登录表单时,会发出一个请求
doLogin.html
。控制权再次转到控制器以搜索doLogin
请求映射。 - 一旦他找到
doLogin
请求映射,根据登录凭据,您将被重定向到success.jsp
或failure.jsp
页面。
NOTE:
笔记:
- Don't mix
commandName
&modelAttribute
in Spring form. You are only allow to use any of them. If you forgot to add empty model in the Controller, then you will face below exception
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'loginEntity' available as request attribute
- 不要在 Spring 形式中混合
commandName
&modelAttribute
。您只能使用其中的任何一个。 如果您忘记在控制器中添加空模型,那么您将面临以下异常
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'loginEntity' available as request attribute
I hope this will clear your idea of using @ModelAttribute
in Spring.
我希望这会清除您@ModelAttribute
在 Spring中使用的想法。