为什么我在春天收到这条消息? "Neither BindingResult nor plain target object for bean name 'removedTeam' availabl



这是我正在编写的一个简单程序,用于理解@RequestMapping注释等。我有两个控制器。主控制器是主页并呈现home.jsp。团队控制器处理team.jsp。主页上有一个删除团队表单,用于从数据库中删除团队对象。这很好用。要添加团队,用户可以单击将他们带到team.jsp的链接。在该页面上,用户可以输入新团队的数据。一旦用户输入了这些信息,数据库就会成功更新。然后,函数"storeTeam"返回到家庭控制器中的"home"。这就是问题发生的地方:我收到这样的消息:

"BindingResult和bean名称'removedTeam'的纯目标对象都不可用作请求属性"

为什么在主控制器中调用"removeAteam"函数,而应该调用主函数来用数据库内容重新填充表?以下是相关文件。谢谢你的帮助。

HomeController.java
    package com.ryans.MVCproject1;
    import java.text.DateFormat;
    import java.util.Date;
    import java.util.List;
    import java.util.Locale;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.Model;
    import org.springframework.validation.BindingResult;
    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;
    /**
     * Handles requests for the application home page.
     */
    @Controller
    @RequestMapping(value="/")
public class HomeController {
    private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
    @Autowired
    Greeter umpire;
    @Autowired
    Team removedTeam;
    @Autowired baseballService baseballservice; //all teams in the database
    /**
     * Simply selects the home view to render by returning its name.
     */
    @RequestMapping(value = {"/","home"}, method = RequestMethod.GET)
    public String home(Locale locale, Model model) {
        logger.info("Welcome home! the client locale is "+ locale.toString());
        Date date = new Date();
        DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
        String formattedDate = dateFormat.format(date);
        Greeter friend = new Greeter();

        model.addAttribute("serverTime", formattedDate );
        model.addAttribute("friend",friend);
        model.addAttribute("umpire",umpire);
        model.addAttribute("removedTeam",removedTeam);
        getAllTeams(model);

        return "home";
    }
    public void getAllTeams(Model model){
        logger.info("Getting all teams...");
        List<Team> allTeams = baseballservice.getAllTeams(); //Query for all teams in database
        //mav.addObject("GET_TEAMS_KEY", allTeams); 
        model.addAttribute("allTeams", allTeams);
        return;    
    }

    @RequestMapping("removeAteam")
    public String removeAteam(@ModelAttribute("removedTeam")Team theRemovedTeam, BindingResult result,Model model){
        logger.info("Removing team...");
        baseballservice.removeTeam(theRemovedTeam.getTeamName()); //the teamName is being pulled from the model as entered in the jsp form
        getAllTeams(model);
        return "home";
    }       
}

TeamController.java

package com.ryans.MVCproject1;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/**
 * 
 * @author Ryan
 * 
 * Handle Requests for the team page
 *
 */
@Controller
@RequestMapping(value="/team")
public class TeamController {
    private static final Logger logger = LoggerFactory.getLogger(TeamController.class);
    @Autowired
    private Team theTeam;
    @Autowired
    private baseballService teamManager;

    @RequestMapping(method=RequestMethod.GET)
    public String TeamPage(Model model){
        logger.info("You have entered the team controller.");
        model.addAttribute("theTeam", theTeam);
        return "team";
    }
    @RequestMapping("/storeTeam")
    public String storeTeam(@ModelAttribute("theTeam")Team enteredTeam,BindingResult result){
        teamManager.saveTeam(enteredTeam); //the @ModelAttribute is binding to the model attribute added in the get method
        return "home";
    }
}

这些是控制器,下面是视图:

home.jsp

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://www.springframework.org/tags" prefix="s"%>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %> 
<%@ page session="false"%>
<html>
<head>
<title>Basic Baseball Player and Team Manager</title>
</head>
<body>
    <h1>Current Teams in the MLB Database</h1>
    <h1>Current Players in the League</h1>
    <p> ${friend.theMessage} ${umpire.theMessage}</p>

    <a href="team">Create New Team</a>

        <table style="border-collapse: collapse;" width="500" border="1"
            bordercolor="#006699">
            <tbody>
                <tr bgcolor="lightblue">
                    <th>Id</th>
                    <th>Team Name</th>
                    <th>City</th>
                    <th>No. of Players</th>
                    <th></th>
                </tr>
                <c:forEach var="team" items="${allTeams}">
                <tr>
                    <td colspan="4"></td>
                </tr>
                <tr>
                    <td><c:out value="${team.id}"></c:out></td>
                    <td><c:out value="${team.teamName}"></c:out></td>
                    <td><c:out value="${team.city}"></c:out></td>
                    <td></td>
                    <td></td>
                </tr>
            </c:forEach>    

            </tbody>
        </table>
    <form:form method="POST" modelAttribute="removedTeam" action="removeAteam">
            <td>Team Name</td><form:input path="teamName"/>
            <td><input type="submit" value="remove team"/> </td>
            </form:form>
</body>
</html>

team.jsp

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://www.springframework.org/tags" prefix="s" %>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>    
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Team Maker</title>
</head>
<body>
<h3>Welcome to the Team Generator</h3>
<form:form method="POST" modelAttribute="theTeam" action="team/storeTeam">
<table>
<tr>
              <td>Team Name:</td>
              <td><form:input path="teamName" /></td>
          </tr>
          <tr>
              <td>City:</td>
              <td><form:input path="city" /></td>
          </tr>
          <tr>
              <td colspan="2">
                  <input type="submit" value="Create Team" />
              </td>
          </tr>
</table>
</form:form>
<a href="home">Back Home</a>
</body>
</html>

这里是servlet上下文:

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:beans="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd 
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">

    <!-- DispatcherServlet Context: defines this servlet's request-processing 
        infrastructure -->
    <!-- Enables the Spring MVC @Controller programming model -->
    <annotation-driven />
    <!-- Enables the transactional annotations -->
    <tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>
    <!-- Handles HTTP GET requests for /resources/** by efficiently serving 
        up static resources in the ${webappRoot}/resources directory -->
    <resources mapping="/resources/**" location="/resources/" />
    <!-- Connection to Database 
    *****   hsqldb.lock_file=false *****
    -->
    <beans:bean id="datasource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <beans:property name="driverClassName" value="org.hsqldb.jdbcDriver" />
        <beans:property name="url" value="jdbc:hsqldb:G:/SpringProjects/MVCProj1/database;shutdown=true" />                                     
        <beans:property name="username" value="ryan" />
        <beans:property name="password" value="ryan" />
    </beans:bean>
    <!-- Resolves views selected for rendering by @Controllers to .jsp resources 
        in the /WEB-INF/views directory -->
    <!-- View Resolver -->
    <beans:bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <beans:property name="prefix" value="/WEB-INF/views/" />
        <beans:property name="suffix" value=".jsp" />
    </beans:bean>
    <!-- MessageSource -->
    <beans:bean
        class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
        <beans:property name="basename" value="classpath:messages" />
        <beans:property name="defaultEncoding" value="UTF-8" />
    </beans:bean>
    <!-- Hibernate SessionFactory -->
    <beans:bean id="sessionFactory"
        class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
    <!--    <beans:bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> -->
        <beans:property name="dataSource" ref="datasource"></beans:property>
        <beans:property name="configLocation" value="classpath:hibernate.cfg.xml"></beans:property>
        <beans:property name="configurationClass" value="org.hibernate.cfg.AnnotationConfiguration"></beans:property>
    <!--    <beans:property name="annotatedClasses">
            <beans:list>
                <beans:value>com.ryans.MVCproject1.Team</beans:value>
            </beans:list> 
        </beans:property> -->
        <beans:property name="hibernateProperties">
            <beans:props>
                <beans:prop key="hibernate.dialect">org.hibernate.dialect.HSQLDialect</beans:prop>
                <beans:prop key="hibernate.show_sql">true</beans:prop>
                <beans:prop key="hibernate.hbm2dll.auto">create</beans:prop>
            </beans:props>
        </beans:property>
    </beans:bean>
     <!-- Define a transaction Manager -->
    <beans:bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
    <beans:property name="sessionFactory" ref="sessionFactory"></beans:property>
    </beans:bean>

    <!-- Custom Greeter Bean -->
    <beans:bean id="umpire" class="com.ryans.MVCproject1.Greeter">
    <beans:property name="theMessage" value="I am the umpire!"></beans:property>
    </beans:bean>
    <beans:bean id="theTeam" class="com.ryans.MVCproject1.Team"></beans:bean>
    <beans:bean id="removedTeam" class="com.ryans.MVCproject1.Team"></beans:bean>
    <beans:bean id="baseballDAO" class="com.ryans.MVCproject1.BaseballDAOimp">
    <beans:property name="sessionFactory" ref="sessionFactory"></beans:property>
    </beans:bean> 
    <beans:bean id="baseballservice" class="com.ryans.MVCproject1.baseballServiceImp"> 
    <beans:constructor-arg ref="baseballDAO"></beans:constructor-arg>
    </beans:bean>
    <beans:bean id="teamManager" class="com.ryans.MVCproject1.baseballServiceImp">
    <beans:constructor-arg ref="baseballDAO"></beans:constructor-arg>
    </beans:bean> 

    <context:component-scan base-package="com.ryans.MVCproject1" />

</beans:beans>

最后是web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/spring/root-context.xml</param-value>
    </context-param>
    <!-- Creates the Spring Container shared by all Servlets and Filters -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <!-- Processes application requests -->
    <servlet>
        <servlet-name>appServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>appServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

我不完全理解你的行为描述,但肯定有一个错误。也许这就是问题的原因。

您已经写道:

函数"storeTeam"然后返回到";家;在家庭控制器中。这就是问题发生的地方:我收到这样的消息:

这就是storeTeam方法:

@RequestMapping("/storeTeam")
public String storeTeam(@ModelAttribute("theTeam")Team enteredTeam,BindingResult result){
    teamManager.saveTeam(enteredTeam); //the @ModelAttribute is binding to the model attribute added in the get method
    return "home";
}

此方法不会向主控制器返回任何内容。它仅使用home.jsp进行渲染。如果你想";返回";对于家庭控制器,您可以使用不同的方式:

  • return "redirect:/home";(这是我在删除后的建议)
  • return "forward:/home";
  • return this.homeController.home(loacle, model);

@参见春季参考章节:

  • 16.5.3.2重定向:前缀
  • 16.5.3.3转发:前缀

相关内容

最新更新