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

StackOverflow https://stackoverflow.com/questions/9014330

Domanda

This is a simple program I am writing to understand the @RequestMapping annotations and such. I have two controllers. The home controller is the home page and renders the home.jsp. The team controller handles the 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. 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. This is where the problem occurs: I get this message:

"Neither BindingResult nor plain target object for bean name 'removedTeam' available as request attribute"

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

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

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

Here is the servlet-context:

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

<?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>
È stato utile?

Soluzione

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. This is where the problem occurs: I get this message:

And this is the storeTeam method:

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

  • 16.5.3.2 The redirect: prefix
  • 16.5.3.3 The forward: prefix
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top