3

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.

Here is my view 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

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

<?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.

HelloController.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.

Tushar
  • 3,527
  • 9
  • 27
  • 49
Mdumanoj
  • 517
  • 3
  • 9
  • 27
  • I don't know you have solved this problem or not. If not, then you can try my answer. – OO7 Mar 13 '15 at 13:47

4 Answers4

5

You are missing commandName="command" in your index.jsp file .

<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.

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.

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

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.

Rajeev
  • 1,730
  • 3
  • 20
  • 33
  • command is a default object we dont need to mention that right? But ok. I tried that also but this exception still remains. I also tried ModelAttribute="command".' – Mdumanoj Mar 12 '15 at 12:57
  • which url are you calling broswer ? is it index.jsp directly ? or you are calling /display ? – Rajeev Mar 13 '15 at 07:25
  • index.jsp directly.. – Mdumanoj Mar 23 '15 at 09:31
  • thats why you are getting that error . I have edited answer, go through it. – Rajeev Mar 23 '15 at 10:42
  • 1
    I tried this, still I have the same exception `Neither BindingResult nor plain target object for bean name 'command' available as request attribute`. – Mdumanoj Mar 23 '15 at 10:47
0

Instead of forwarding to your index.jsp via welcome-files list, you should add

<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.

@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 commandName or modelAttribute attributes expects an object with the key command inside the request attributes

Master Slave
  • 27,771
  • 4
  • 57
  • 55
0

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.

To solve this problem follow below steps:

Step 1: Remove all welcome-file-list from web.xml.

Step 2: add "/" into display GET handler.

@RequestMapping(value = {"/", "/display"}, method = RequestMethod.GET)
 public ModelAndView display() {
    return new ModelAndView("myself", "command", new MySelf());
 }

Step 3: add modelAttribute name in form tag:

<form:form action="${pageContext.request.contextPath}/addDisplay" 
           method="POST" 
           modelAttribute="command">
Abhishek Nayak
  • 3,732
  • 3
  • 33
  • 64
0

Consider, you have HTML form like below

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:-

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.

Now, you can add link to your index.jsp which will give a call to Controller to display login.jsp just like below :-

Index Page:

<html>
    <body>    
        <ul>
            <li><a href="showLoginForm.html">Login</a></li>
        </ul>
    </body>
</html>

Overall Request Flow:

  1. At application start index.jsp will load having a link to login.jsp.
  2. On click of link <a href="showLoginForm.html">Login</a> a call to controller is made & it searches for request mapping showLoginForm in it.
  3. Once he found the specified mapping, he proceed further to display login.jsp page.
  4. On submit of the login form, a request for doLogin.html is made. Once again control goes to Controller to search for doLogin request mapping.
  5. Once he found doLogin request mapping, depending on the login credentials, you will be redirected to either success.jsp or failure.jsp page.

NOTE:

  1. Don't mix commandName & modelAttribute in Spring form. You are only allow to use any of them.
  2. 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
    

I hope this will clear your idea of using @ModelAttribute in Spring.

OO7
  • 2,785
  • 1
  • 21
  • 33
  • What is the purpose of empty Model.? Is there is any other way to map request from form withoutl that empty Model.? – Mdumanoj Mar 23 '15 at 09:29
  • Empty model maps all the fields in UI with member variables in POJO with the default values specified for each member. – OO7 Mar 23 '15 at 09:35
  • I don't need like href link to display login form and it also calls that empty model.. I want to display the login form directly without using link.. – Mdumanoj Mar 23 '15 at 10:11
  • Then no need to write `modelAttribute` for ur login form, instead create a simple login form & access login credentials from `HttpServletRequest & HttpServletResponse` objects in the method directly & validate it. Or u can also `Autowire HttpServletRequest` to fetch login credentials. – OO7 Mar 23 '15 at 10:19
  • How can I use `HttpServletRequest` & `HttpServletResponse` objects in Spring MVC framework.? – Mdumanoj Mar 23 '15 at 10:22
  • 1
    Look at [this post](http://stackoverflow.com/questions/8504258/spring-3-mvc-accessing-httprequest-from-controller) & [MKYong article](http://www.mkyong.com/java/how-to-get-http-request-header-in-java/). – OO7 Mar 23 '15 at 10:25
  • Ok.. If I am using `HttpServletRequest` there is no need of JSP Form Tag Library. Right? – Mdumanoj Mar 23 '15 at 10:35
  • 1
    Yes. U just need then simple form without any tag library. – OO7 Mar 23 '15 at 10:42
  • Have u tried with simple login form ? Will u able to proceed in ur work with that ? – OO7 Mar 23 '15 at 15:51
  • No. This is also a simple form work. Get details in form and display that in another page thats all.. – Mdumanoj Mar 25 '15 at 09:12
  • What do u want exactly, to get rid of this error or something else ? Will u please elaborate ? How do u want ur system to call pages ? I m using this pattern & it's working. – OO7 Mar 25 '15 at 12:04