java.lang.IllegalStateException:BindingResult和bean名称'userForm'的普通目标对象都不可用作请求属性

时间:2016-04-04 06:53:47

标签: hibernate spring-mvc

映射似乎很好,但我正在努力解决同样的错误。 尝试过@ModelAttribute注释以及ModelAndView方法。

POJO:User.java`

package com.mediastudio.pojo;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.Table;


@Entity
@Table(name = "User")
public class User {

    @Id @GeneratedValue(strategy=GenerationType.AUTO) 
    private int userId;

    // @Column(name="username")
    private String username;

    // @Column(name="password")
    private String password;


    @OneToOne(cascade = CascadeType.ALL) 
    //CascadeType.ALL performs actions on parent class when child class is changed automatically
    private Person person;

    public Person getPerson() {
        return person;
    }
    public void setPerson(Person person) {
        this.person = person;
    }

    @OneToOne(cascade = CascadeType.ALL)
    private UserRole role;

    public UserRole getRole() {
        return role;
    }
    public void setRole(UserRole role) {
        this.role = role;
    }

    public int getUserId() {
        return userId;
    }
    public void setUserId(int userId) {
        this.userId = userId;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }

     public User(){

    } 
}

POJO:Person.java

package com.mediastudio.pojo;

import java.sql.Date;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

import org.springframework.web.multipart.commons.CommonsMultipartFile;

@Entity
@Table(name = "Person")
public class Person {

    @Id 
    @GeneratedValue
//  @Column(name = "PersonId")
    private int personId;

//  @Column(name = "FirstName")
    private String firstName;

//  @Column(name = "LastName")
    private String lastName;

    @Temporal(TemporalType.DATE)
//  @Column(name = "DateOfBirth")
    private Date dateOfBirth;

//  @Column(name = "Gender")
    private String gender;

//  @Column(name = "Email")
    private String email;

    private CommonsMultipartFile profilePic;
    //  @Column(name = "ProfilePicPath")
    private String profilePicPath;

    public String getProfilePicPath() {
        return profilePicPath;
    }
    public void setProfilePicPath(String profilePicPath) {
        this.profilePicPath = profilePicPath;
    }
    public CommonsMultipartFile getProfilePic() {
        return profilePic;
    }
    public void setProfilePic(CommonsMultipartFile profilePic) {
        this.profilePic = profilePic;
    }
    public int getPersonId() {
        return personId;
    }
    public void setPersonId(int personId) {
        this.personId = personId;
    }
    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;
    }
    public Date getDateOfBirth() {
        return dateOfBirth;
    }
    public void setDateOfBirth(Date dateOfBirth) {
        this.dateOfBirth = dateOfBirth;
    }
    public String getGender() {
        return gender;
    }
    public void setGender(String gender) {
        this.gender = gender;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }

    /*
    //bidirectional one to one mapping
    @OneToOne(cascade = CascadeType.ALL) 
    //CascadeType.ALL performs actions on parent class when child class is changed automatically
    @JoinColumn(name="PersonId")
    private User userAccount;

    public User getUserAccount() {
        return userAccount;
    }
    public void setUserAccount(User userAccount) {
        this.userAccount = userAccount;
    }

    */

    public Person(){

    }

    }

查看:register.jsp

<form:form action="adduser" commandName="userForm" method="post">

<table id="registertable" cellpadding="10">

    <tr>
    <td>First Name</td>
    <td><form:input path="person.firstName" size="30" /> <font color="red"><form:errors path="person.firstName"/></font>
        (max 30 characters a-z and A-Z)
    </td>
    </tr>

    <tr>
    <td>Last Name</td>
    <td><form:input path="person.lastName" size="30" /> <font color="red"><form:errors path="person.lastName"/></font>
        (max 30 characters a-z and A-Z)
    </td>
    </tr>

    <tr>
    <td>Email</td>
    <td><form:input path="person.email" size="30" /> <font color="red"><form:errors path="person.email"/></font></td>
    </tr>

    <tr>
    <td>User Name</td>
    <td><form:input path="username" size="30" /> <font color="red"><form:errors path="username"/></font></td>
    </tr>

    <tr>
    <td>Password</td>
    <td><form:password path="password" size="30" /> <font color="red"><form:errors path="password"/></font></td>
    </tr>
    <tr></tr>
    <tr>
    <td colspan="2" align="center">
        <input type="submit" value="Submit">
        <input type="reset" value="Reset">
    </td>
    </tr>

    </table>
</form:form>

LoginController.java

@RequestMapping(value = "/adduser", method = RequestMethod.POST)
@Transactional
public String create (Model model, @Valid @ModelAttribute User userForm, HttpServletRequest request) throws mediaException
{
    userForm.setPerson(userForm.getPerson());
    userDao.create(userForm);
    HttpSession session = request.getSession();
    session.setAttribute("user", userForm);
    return "index";
}

@RequestMapping(value = "/adduser",method = RequestMethod.GET)
public String initializeForm(ModelMap model) {

    model.addAttribute("userForm", new User());
    return "adduser";
}

UserDAO.java

public void create(User user)
            throws mediaException {

            Session session = HibernateUtil.getSessionFactory().openSession();
            try
            {   

            Transaction transaction = session.beginTransaction();

            user.setUsername(user.getUsername());
            user.setPassword(user.getPassword());
            user.getPerson().setEmail(user.getPerson().getEmail());
            user.getPerson().setFirstName(user.getPerson().getFirstName());
            user.getPerson().setLastName(user.getPerson().getLastName());

            session.save(user);
            transaction.commit();

        }
        catch(Exception ex)
        {
            ex.printStackTrace();
        }
        finally
        {
            session.close();
        }
    }

的pom.xml

    <dependencies>
        <!-- Spring -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${org.springframework-version}</version>
            <exclusions>
                <!-- Exclude Commons Logging in favor of SLF4j -->
                <exclusion>
                    <groupId>commons-logging</groupId>
                    <artifactId>commons-logging</artifactId>
                 </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${org.springframework-version}</version>
        </dependency>

        <!-- AspectJ -->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjrt</artifactId>
            <version>${org.aspectj-version}</version>
        </dependency>   

        <!-- Logging -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>${org.slf4j-version}</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>jcl-over-slf4j</artifactId>
            <version>${org.slf4j-version}</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>${org.slf4j-version}</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.15</version>
            <exclusions>
                <exclusion>
                    <groupId>javax.mail</groupId>
                    <artifactId>mail</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>javax.jms</groupId>
                    <artifactId>jms</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>com.sun.jdmk</groupId>
                    <artifactId>jmxtools</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>com.sun.jmx</groupId>
                    <artifactId>jmxri</artifactId>
                </exclusion>
            </exclusions>
            <scope>runtime</scope>
        </dependency>

        <!-- @Inject -->
        <dependency>
            <groupId>javax.inject</groupId>
            <artifactId>javax.inject</artifactId>
            <version>1</version>
        </dependency>

        <!-- Servlet -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.1</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>

        <!-- Hibernate -->

        <dependency>
            <groupId>javax.validation</groupId>
            <artifactId>validation-api</artifactId>
            <version>1.0.0.GA</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>4.2.5.RELEASE</version>
        </dependency>

        <dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>4.2.0.Final</version>
</dependency>


        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>3.5.1-Final</version>
        </dependency>

        <dependency>
            <groupId>org.hibernate.javax.persistence</groupId>
            <artifactId>hibernate-jpa-2.0-api</artifactId>
            <version>1.0.1.Final</version>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-annotations</artifactId>
            <version>3.5.6-Final</version>
        </dependency>

        <dependency>
            <groupId>commons-dbcp</groupId>
            <artifactId>commons-dbcp</artifactId>
            <version>1.4</version>
        </dependency>

        <dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib</artifactId>
            <version>2.2.2</version>
        </dependency>

        <!-- Test -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.7</version>
            <scope>test</scope>
        </dependency>        
    </dependencies>

根本原因:

java.lang.IllegalStateException:BindingResult和bean名称'userForm'的普通目标对象都不能用作请求属性     org.springframework.web.servlet.support.BindStatus。(BindStatus.java:141)

3 个答案:

答案 0 :(得分:0)

userForm 未使用get方法进行初始化,因此需要使用get方法更改以下代码

@RequestMapping(value = "/adduser",method = RequestMethod.GET)
public String initializeForm(ModelMap model) {
    model.addAttribute("userForm", new User());
    model.addAttribute("message", "Hello World!!!");
    return "helloWorld";
}

您还需要使用POST方法更改代码

@RequestMapping(value = "/adduser", method = RequestMethod.POST)
@Transactional
public String create (Model model, @Valid @ModelAttribute User userForm, HttpServletRequest request) throws mediaException
{
        userForm.setPerson(userForm.getPerson());
        userDao.create(userForm);
        HttpSession session = request.getSession();
        session.setAttribute("user", userForm);
        return "redirect:/index";
}

希望你能解决问题

答案 1 :(得分:0)

检查你的jsp文件后,我发现映射不正确(你已经为adduser.htm映射了,而在你的jsp中它是寄存器)。所以只需进行以下更改即可:

@RequestMapping(value = "/register",method = RequestMethod.GET)

public String initializeForm(@ModelAttribute("user")User user) 
{
    return "register";
}

答案 2 :(得分:0)

好的,所以这里是我出错的代码: 我在value参数中使用了错误的映射:| 由于我的TA - Ankit Kothari

解决了这个问题
@RequestMapping(value = "/register",method = RequestMethod.GET)
    public String initializeForm(@ModelAttribute("user") User user) {

        return "register";
    }


    @RequestMapping(value = "/register",method = RequestMethod.POST)
    protected String doSubmitAction(@ModelAttribute("user") User user, BindingResult result) throws Exception {

        UserDAO userDao = new UserDAO();
        userDao.create(user);

        return "index";
    }