Pourquoi est-ce que je reçois ce message au printemps? «Ni BindingResult ni objet cible simple pour le nom de bean« supprimé »disponible en tant qu'attribut de demande»
-
14-11-2019 - |
Question
Il s'agit d'un programme simple que j'écris pour comprendre les annotations @RequestMapping et autres. J'ai deux contrôleurs. Le contrôleur d'accueil est la page d'accueil et rend la maison.jsp. Le contrôleur de l'équipe gère l'équipe.jsp. La page d'accueil a un formulaire d'équipe de supprimer qui supprime un objet d'équipe de la base de données. Cela fonctionne très bien. Pour ajouter une équipe, l'utilisateur clique sur le lien qui les emmène à l'équipe.jsp. Sur cette page, l'utilisateur peut saisir les données de la nouvelle équipe. Une fois que l'utilisateur entre dans ces informations, la base de données est mise à jour avec succès. La fonction «Storeteam» revient ensuite à la «maison» dans le contrôleur d'origine. C'est là que le problème se produit: je reçois ce message:
"Ni BindingResult ni objet cible simple pour le nom de bean 'supprime" disponible en tant qu'attribut de demande "
Pourquoi la fonction "Removeateam" est-elle appelée dans le contrôleur d'accueil lorsque la fonction domestique doit être appelée pour repeupler le tableau avec le contenu de la base de données? Voici les fichiers associés. Merci pour l'aide.
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";
}
}
Ce sont les contrôleurs et voici les vues:
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>
Voici le 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>
... et enfin voici le 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>
La solution
Je ne comprends pas parfaitement votre descriptions de comportement, mais il y a décemment une erreur, que ce soit la cause du problème.
Vous avez écrit:
La fonction «Storeteam» revient ensuite à la «maison» dans le contrôleur d'origine. C'est là que le problème se produit: je reçois ce message:
Et c'est le storeTeam
méthode:
@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";
}
Cette méthode ne rétablit rien au contrôleur d'origine. Il utilise uniquement le home.jsp
rendre. Si vous souhaitez "retourner" au contrôleur d'accueil, vous pouvez utiliser différentes manières:
return "redirect:/home";
(c'est ce que je recommanderais après une suppression)return "forward:/home";
return this.homeController.home(loacle, model);
@See Spring Reference Chapters:
- 16.5.3.2 La redirection: préfixe
- 16.5.3.3 L'attaquant: préfixe