Por que estou recebendo esta mensagem Primavera?"Nem BindingResult nem simples objeto de destino para o bean name 'removedTeam' disponível como o pedido atributo"

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

Pergunta

Este é um programa simples que eu estou escrevendo para entender o @RequestMapping anotações e tal.Eu tenho dois controladores.A casa do controlador é a página inicial e compõe a casa.jsp.A equipe controlador manipula a equipe.jsp.A página inicial tem um remover equipe de forma que remove uma equipe objeto do banco de dados.Que funciona muito bem.Para adicionar uma equipa o usuário clicar no link que leva para a equipe.jsp.Na página, o usuário pode inserir os dados para a nova equipe.Uma vez que o usuário insere as informações do banco de dados é atualizado com êxito.A função 'storeTeam', em seguida, retorna para "casa" em casa controlador.Este é o lugar onde ocorre o problema:Eu recebo esta mensagem:

"Nem BindingResult nem simples objeto de destino para o bean name 'removedTeam' disponível como o pedido atributo"

Porque é que o "removeAteam" função que está sendo chamada na home do controlador quando a casa de função deve ser chamada para preencher a tabela com o conteúdo do banco de dados?Aqui estão os arquivos associados.Obrigado pela ajuda.

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";
    }

}

Esses são os controladores e aqui estão os pontos de vista:

a casa.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>

a equipe.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>

Aqui é o servlet-contexto:

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

...e, finalmente, aqui é o 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>
Foi útil?

Solução

Eu não sou totalmente a compreender o seu comportamento desciption, mas há defently um erro, que é a causa para o problema.

Você tem escrito:

A função 'storeTeam', em seguida, retorna para "casa" em casa controlador.Este é o lugar onde ocorre o problema:Eu recebo esta mensagem:

E este é o storeTeam método:

@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";
}

Este método NÃO retornos nada para a home do CONTROLADOR.Ele usa apenas o home.jsp para compor.Se você deseja "voltar" para a home controller você pode utilizar formas diferentes:

  • return "redirect:/home"; (que é o que eu recomendaria depois de um delete)
  • return "forward:/home";
  • return this.homeController.home(loacle, model);

@Veja Primavera de Referência capítulos:

  • 16.5.3.2 O redirecionamento:prefixo
  • 16.5.3.3 A frente:prefixo
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top