简体   繁体   English

为什么我会在 Spring 中收到此消息? “ BindingResult 和 bean 名称 'removedTeam' 的普通目标对象都不能用作请求属性”

[英]Why am I getting this message in Spring? “Neither BindingResult nor plain target object for bean name 'removedTeam' available as request attribute”

This is a simple program I am writing to understand the @RequestMapping annotations and such.这是我正在编写的一个简单程序,用于理解 @RequestMapping 注释等。 I have two controllers.我有两个控制器。 The home controller is the home page and renders the home.jsp.主控制器是主页并呈现 home.jsp。 The team controller handles the team.jsp.团队控制器处理 team.jsp。 The home page has a remove team form on it that removes a team object from the database.主页上有一个删除团队表单,用于从数据库中删除团队对象。 That works just fine.这工作得很好。 To add a team the user clicks the link that takes them to the team.jsp.要添加团队,用户单击将他们带到 team.jsp 的链接。 On that page, the user can enter the data for the new team.在该页面上,用户可以输入新团队的数据。 Once the user enters this information the database is updated successfully.一旦用户输入此信息,数据库就会成功更新。 The function 'storeTeam' then returns to "home" in the home controller.然后函数“storeTeam”返回到家庭控制器中的“home”。 This is where the problem occurs: I get this message:这是出现问题的地方:我收到此消息:

"Neither BindingResult nor plain target object for bean name 'removedTeam' available as request attribute" “对于 bean 名称‘removedTeam’既没有 BindingResult 也没有普通目标对象作为请求属性可用”

Why is the "removeAteam" function being called in the home controller when the home function should be called to repopulate the table with the database contents?当应调用 home 函数以使用数据库内容重新填充表时,为什么在 home 控制器中调用“removeAteam”函数? Here are the associated files.以下是相关文件。 Thanks for the help.谢谢您的帮助。

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团队控制器.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";
    }

}

Those are the controllers and here are the views:这些是控制器,这里是视图:

home.jsp主页.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团队.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>

Here is the servlet-context:这是 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>

...and finally here is the web.xml ...最后这里是 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>

I do not fully understand your behavior description, but there is definitely a mistake.我不完全理解你的行为描述,但肯定有错误。 Maybe it is the cause of the problem.也许这是问题的原因。

You have written:你写:

The function 'storeTeam' then returns to "home" in the home controller.然后函数“storeTeam”返回到家庭控制器中的“home”。 This is where the problem occurs: I get this message:这是出现问题的地方:我收到此消息:

And this is the storeTeam method:这是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";
}

This method does NOT return anything to the home CONTROLLER.此方法不会向主控制器返回任何内容。 It only uses the home.jsp to render.它只使用home.jsp来渲染。 If you want to "return" to the home controller you can use different ways:如果您想“返回”到家庭控制器,您可以使用不同的方式:

  • return "redirect:/home"; (that is what I would recommend after an delete) (这是我删除后的建议)
  • return "forward:/home";
  • return this.homeController.home(loacle, model);

@See Spring Reference chapters: @See Spring 参考章节:

  • 16.5.3.2 The redirect: prefix 16.5.3.2 重定向:前缀
  • 16.5.3.3 The forward: prefix 16.5.3.3 forward:前缀

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我得到异常BindingResult和bean名称&#39;studentRegistration&#39;的普通目标对象在春天都不可用作请求属性 - I am getting exception Neither BindingResult nor plain target object for bean name 'studentRegistration' available as request attribute in spring BeanResult的BindingResult或普通目标对象都不能用作请求属性,我也不知道为什么 - Neither BindingResult nor plain target object for bean name available as request attribute, and I don't know why 循环时获取“既没有 BindingResult 也没有可用作请求属性的 bean 名称‘bean 名称’的普通目标对象” - Getting "Neither BindingResult nor plain target object for bean name 'bean name' available as request attribute" when looping Bean名称的BindingResult和普通目标对象都不能用作请求属性(Spring MVC) - Neither BindingResult nor plain target object for bean name available as request attribute (Spring MVC) Spring MVC:BindingResult和bean名称&#39;POJO&#39;的普通目标对象都不能作为请求属性使用 - Spring MVC : Neither BindingResult nor plain target object for bean name 'POJO' available as request attribute Spring-mvc 错误:Bean 名称“userBean”的 BindingResult 和普通目标对象都不能用作请求属性 - Spring-mvc error: Neither BindingResult nor plain target object for bean name 'userBean' available as request attribute BeanResult&#39;student&#39;的BindingResult或普通目标对象都不能用作请求属性-Spring MVC - Neither BindingResult nor plain target object for bean name 'student' available as request attribute - Spring MVC 春季| 休眠| Thymeleaf:BeanResult&#39;id&#39;的BindingResult或普通目标对象都不能用作请求属性 - Spring | Hibernate | Thymeleaf: Neither BindingResult nor plain target object for bean name 'id' available as request attribute Spring MVC产生“ Bean名称&#39;command&#39;的BindingResult和普通目标对象异常都不能用作请求属性” - Spring MVC produces “Neither BindingResult nor plain target object exception for bean name 'command' available as request attribute” Spring 3 MVC:Bean名称的BindingResult和普通目标对象都不可用作请求属性 - Spring 3 MVC:Neither BindingResult nor plain target object for bean name available as request attribute
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM