【问题标题】:Neither BindingResult nor plain target object for bean name 'user' available as request attributeBean 名称“用户”的 BindingResult 和普通目标对象都不能用作请求属性
【发布时间】:2013-04-12 13:17:07
【问题描述】:

我正在使用 spring,但我遇到了一个示例。如果我解决了一个错误,它会给我带来不同的错误...

我有一个名为 UserController2.java 的控制器程序,如下所示

package project2;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;

@Controller
public class UserController2 extends MultiActionController {

    private UserDAO userDAO;

    public void setUserDAO(UserDAO userDAO) {
        this.userDAO = userDAO;
    }
    @RequestMapping(params = "add", method = RequestMethod.POST)
    public ModelAndView add(HttpServletRequest request,
           HttpServletResponse response, User user) throws Exception {
        userDAO.saveUser(user);
        return new ModelAndView("redirect:list.htm");
    }
    @RequestMapping(params = "delete", method = RequestMethod.POST)
    @Transactional
    public ModelAndView delete(HttpServletRequest request,
        HttpServletResponse response, User user) throws Exception {
        userDAO.deleteUser(user);
        return new ModelAndView("redirect:list.htm");
    }

    public ModelAndView list(HttpServletRequest request,
        HttpServletResponse response) throws Exception {
        ModelMap modelMap = new ModelMap();
        modelMap.addAttribute("userList", userDAO.listUser());
        modelMap.addAttribute("user", new User());
        return new ModelAndView("userForm", modelMap);
    }
}

和jsp页面userForm.jsp如下

<body>
 <center> WELCOME TO CUSTOMER ACCESS SITE.PLEASE ENTER THE FOLLOWING 
  INFORMATION</center>
<form:form method="POST" action="add.htm"  modelAttribute="user">
   <table>
    <tr>
        <td><form:label path="name">Name</form:label></td>
        <td><form:input path="name" /></td>
    </tr>

    <tr>
        <td><form:label path="id">id</form:label></td>
        <td><form:input path="id" /></td>
    </tr>

    <tr>
        <td><form:label path="password">password</form:label></td>
        <td><form:input path="password" /></td>
    </tr>
    <tr>
        <td><form:label path="gender">Gender</form:label></td>
        <td><form:input path="gender" /></td>
    </tr>
    <tr>
        <td><form:label path="country">Country</form:label></td>
        <td><form:input path="country" /></td>
    </tr>
    <tr>
        <td colspan="2">
            <input type="submit" value="Submit"/>
        </td>
    </tr>
 </table>  
</form:form>

</body>

和 UserController2-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:p="http://www.springframework.org/schema/p"
   xmlns:aop="http://www.springframework.org/schema/aop"
   xmlns:tx="http://www.springframework.org/schema/tx"
   xsi:schemaLocation="http://www.springframework.org/schema/beans  
    http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
   http://www.springframework.org/schema/aop http://www.springframework.org/schema 
    /aop/spring-aop-2.5.xsd
   http://www.springframework.org/schema/tx http://www.springframework.org/schema 
    /tx/spring-tx-2.5.xsd">
<bean   
class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"/>


<bean id="urlMapping"  
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
    <property name="mappings">
        <props>
            <prop key="index.htm">indexController</prop>
        </props>
    </property>
</bean>

<bean id="viewResolver"
      class="org.springframework.web.servlet.view.InternalResourceViewResolver"
      p:prefix="/WEB-INF/jsp/"
      p:suffix=".jsp" />

<bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy- 
method="close">
    <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
    <property name="url" value="jdbc:mysql://localhost:3306/indi"/>
    <property name="username" value="admin"/>
    <property name="password" value=""/>
</bean>

<bean id="mySessionFactory"   
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
    <property name="dataSource" ref="myDataSource" />
    <property name="annotatedClasses">
        <list>
            <value>Spring.project2.User</value>

        </list>
    </property>
    <property name="hibernateProperties">
        <props>
            <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
            <prop key="hibernate.show_sql">true</prop>
            <prop key="hibernate.hbm2ddl.auto">create</prop>
        </props>
    </property>
</bean>

<bean id="myUserDAO" class="project2.UserDAOImpl">
     <property name="sessionFactory" ref="mySessionFactory"/>
</bean>

 <bean name="/user/*.htm" class="project2.UserController2" >
    <property name="userDAO" ref="myUserDAO" />
</bean>


<bean name="indexController"  
class="org.springframework.web.servlet.mvc.ParameterizableViewController"
      p:viewName="userForm" />

 </beans>

而web.xml文件如下

<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
    <servlet-name>UserController2</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>2</load-on-startup>
 </servlet>
<servlet-mapping>
     <servlet-name>UserController2</servlet-name>
    <url-pattern>*.htm</url-pattern>
</servlet-mapping>

现在我收到以下错误

org.apache.jasper.JasperException: java.lang.IllegalStateException: Neither  
BindingResult nor plain target object for bean name 'user' available as request 
attribute

我只在 jsp 和控制器类中使用了“用户”。有人告诉我从以下代码行更改

modelMap.addAttribute("user", new User());

到这里

modelMap.addAttribute("user", new user());

但我收到错误

  user cannot be resolved to a type

我已经彻底搜索了网络,查看了各种示例,但我无法解决代码。有什么建议吗??

【问题讨论】:

  • 告诉你改变那行代码的人从来没有写过java。你的 list 方法如何在没有 @RequestMapping 的情况下被调用?您现在可以做的是将User 对象添加到请求属性中,例如request.setAttribute("user", new User()),但我非常想用ModelMap 解决它

标签: spring spring-mvc


【解决方案1】:

如果我没记错的话,我认为您正在混合 Spring 新版本和旧版本的一些概念。在您的控制器中:

  • 使用@Controller 并删除extends MultiActionController(弹簧3 方式)

  • MultiActionController 扩展并删除@Controller(弹簧2 方式)。你还应该在 Spring XML 配置文件中声明这个 bean。

也许这会有所帮助,或者我错了,但对我来说用这两种东西声明一个控制器似乎很奇怪。

此外,您必须从您的web.xml 中删除您的UserController2。如果您使用 Spring 2 方法,则必须在 Spring XML 配置文件中声明它。

【讨论】:

    【解决方案2】:

    我遇到了同样的问题。确保在控制器中返回页面 userForm.jsp 时放入代表用户的模型对象。例如,就我而言:

    @RequestMapping(value = "registration", method = RequestMethod.GET)
    public String registration(Model model) {
        model.addAttribute("UserForm", new UserForm()); // !!!!
        return PATH_REGISTRATION;
    }
    
     @RequestMapping(value = "/register", method = RequestMethod.POST)
    public String register(
            @Valid @ModelAttribute("UserForm") UserForm userForm,
            BindingResult result, HttpServletRequest request, Model model,
            Principal principal) {
        if (!result.hasErrors()) {
            model.addAttribute("message", "Registration success");
        }
        try {
            userService.create(createUser(userForm));
        } catch (SQLException e) {
            model.addAttribute("message", "Can't create user");
            log.error("Can't create user " + userForm.getLogin(), e);
        }
        return PATH_REGISTRATION;
    }
    

    在 JSP 中:

    ...
    <form:form method="POST" action="registrate" commandName="UserForm">
    ....
    

    【讨论】:

      【解决方案3】:

      我在项目中遇到了同样的问题。我通过修改控制器类解决了这个问题。代码如下: LoginForm.jsp 页面

      <%@ page language="java" contentType="text/html; charset=UTF-8"
          pageEncoding="UTF-8"%>
      <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
      
      <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
          "http://www.w3.org/TR/html4/loose.dtd">
      <html>
      <head>
      <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
      <title>Login</title>
      <style>
          .error { 
              color: red; font-weight: bold; 
          }
      </style>
      </head>
      <body>
          <div align="center">
              <h2>Spring MVC Form Validation Demo - Login Form</h2>
              <table border="0" width="90%">
              <form:form action="login" commandName="userFormNew">
                      <tr>
                          <td align="left" width="20%">Email: </td>
                          <td align="left" width="40%"><form:input path="email" size="30"/></td>
                          <td align="left"><form:errors path="email" cssClass="error"/></td>
                      </tr>
                      <tr>
                          <td>Password: </td>
                          <td><form:password path="password" size="30"/></td>
                          <td><form:errors path="password" cssClass="error"/></td>
                      </tr>
                      <tr>
                          <td></td>
                          <td align="center"><input type="submit" value="Login"/></td>
                          <td></td>
                      </tr>
              </form:form>
              </table>
          </div>
      </body>
      </html>
      

      在 LoginForm.jsp 页面中观察 commandName="userFormNew" 在控制器中我有两种方法,一种是自动填充 loginForm.jsp 页面,当我们尝试使用 @RequestingMapping(value="/",method=RequestMethod.GET) 运行应用程序时通过重定向 LoginForm.jsp 页面返回模型对象。

      这是控制器类:

      @Controller
      public class LoginController {
          @RequestMapping(value = "/", method = RequestMethod.GET)
          public String viewLogin(Map<String, Object> model) {
              User user = new User();
              model.put("userFormNew", user);
              return "LoginForm";
          }
      
          @RequestMapping(value = "/login", method = RequestMethod.POST)
          public String doLogin(@Valid @ModelAttribute("userFormNew") User userForm,
                  BindingResult result, Map<String, Object> model) {
      
              if (result.hasErrors()) {
                  return "LoginForm";
              }
      
              return "LoginSuccess";
          }
      }
      

      我的模型类:

      public class User {
          @NotEmpty
          @Email
          private String email;
      
          @NotEmpty(message = "Please enter your password.")
          @Size(min = 6, max = 15, message = "Your password must between 6 and 15 characters")
          private String password;
      
          public String getEmail() {
              return email;
          }
      
          public void setEmail(String email) {
              this.email = email;
          }
      
          public String getPassword() {
              return password;
          }
      
          public void setPassword(String password) {
              this.password = password;
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-05-23
        • 2015-08-31
        • 2013-04-04
        • 2011-11-25
        • 2019-10-29
        • 2013-08-15
        相关资源
        最近更新 更多