Ни BindingResult, ни простой целевой объект для регистрации имени компонента не доступны в качестве атрибута запроса

После успешного входа в систему мне нужно открыть регистрационную форму, которая работает с объектом представления модели, но показывает ошибку, см. код ниже. Это мой класс контроллера входа в систему:

package controller;

import entity.User;
import org.springframework.web.servlet.mvc.SimpleFormController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import service.*;

@SuppressWarnings("deprecation")
public class LoginController extends SimpleFormController {

Service clientService;

@SuppressWarnings("deprecation")
public LoginController() {
    setCommandClass(User.class);
    setCommandName("user");
    clientService=new ServiceImpl();
}

@Override
protected void doSubmitAction(Object command) throws Exception {
    throw new UnsupportedOperationException("Not yet implemented");
}
//Use onSubmit instead of doSubmitAction 
//when you need access to the Request, Response, or BindException objects
@Override
protected ModelAndView onSubmit(HttpServletRequest request,HttpServletResponse response,Object command, BindException errors) throws Exception {
    User user =(User) command;  
    String UserId = user.getUname();
    String Password = user.getpwd();
    boolean result;

    result=clientService.checkLoginIdPassword(UserId, Password);
    ModelAndView mv=null;
   if(result)
   {      
    System.out.println("Login TRUE");
    mv= new ModelAndView("registrationForm","user",user);
    return mv;
   }
   else
   {
       System.out.println("Login FALSE");
       response.sendRedirect("login.htm");
       return mv;
   }

 }
}

Моя страница Login.jsp:

    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
    <html>
     <head>
      <title>User Login </title>
     </head>
    <body>
  <h1>User Login</h1>
  <form:form method="POST" commandName="user">
   <table width="95%" bgcolor="f8f8ff" border="0" cellspacing="0" cellpadding="5">
  <tr>
     <td alignment="right" width="20%">User Id</td>
     <td width="20%"><form:input path="uname"  /></td>
     <td width="60%">
  </tr>
  <tr>
     <td alignment="right" width="20%">Password</td>
     <td width="20%"> <form:password path="pwd" /> </td>
     <td width="60%">
  </tr>
  </table>
   <input type="submit" value="login" />
 </form:form>
</body>
</html>

Моя страница RegistrationForm.jsp:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"     "http://www.w3.org/TR/html4/loose.dtd">
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<head>
<title>Registration Page</title>
</head>
<body>

<form:form method="POST" commandName="registration">
<table>
<tr>
    <td>User Name :</td>
    <td><form:input path="name" /> </td>
</tr>
<tr>
    <td>Age :</td>
    <td> <form:input path="age" /></td>
</tr>
<tr>
    <td>Gender :</td>
    <td>
        <form:input path="gender" />
    </td>
</tr>
<tr>
    <td>Country :</td>
    <td>
    <form:input path="country" />
     </td>
</tr>
<tr>
    <td>Mobile :</td>
    <td><form:input path="mobile" /></td>
</tr>
<tr>
    <td>Email :</td>
    <td>
       <form:input path="email" />
    </td>
</tr>
<tr>
    <td>About You</td>
    <td>
    <form:textarea path="aboutYou"/>
    </td>
</tr>
</table>
<input type="submit" value="submit"></td>
</form:form>

</body>
</html>

Мой код DispatcherServlet.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
xmlns:p="http://www.springframework.org/schema/p"  
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"  
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-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">

 <bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"/>

 <bean name="/login.htm" class="controller.LoginController"/>
 <bean name="/registrationForm.htm" class="controller.RegistrationController"/>  

<!--view resolver -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"    p:prefix="/WEB-INF/jsp/" p:suffix=".jsp"/>
<!--view resolver -->   

</beans>

Мой файл RegistrationController.java:

package controller;
import entity.*;
import org.springframework.web.servlet.mvc.SimpleFormController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import service.*;
/** 
 *
 * @author pawan
 */
@SuppressWarnings("deprecation")
public class RegistrationController extends SimpleFormController {

Service clientService;

@SuppressWarnings("deprecation")
public RegistrationController() {

    setCommandClass(Registration.class);
    setCommandName("registration");
    System.out.println(" In Registration----------A--");
    clientService=new ServiceImpl();
}

@Override
protected void doSubmitAction(Object command) throws Exception {
    throw new UnsupportedOperationException("Not yet implemented");
}
//Use onSubmit instead of doSubmitAction 
//when you need access to the Request, Response, or BindException objects
@Override
protected ModelAndView onSubmit(HttpServletRequest request,HttpServletResponse response,Object command, BindException errors) throws Exception {

  Registration reg=(Registration) command;  

    System.out.println("Name------------"+reg.getName());
    System.out.println("Age-------------"+reg.getage());
    System.out.println("Gender----------"+reg.getGender());
    System.out.println("Mobile----------"+reg.getMobile());
    System.out.println("County----------"+reg.getCountry());
    System.out.println("Email-----------"+reg.getEmail());
    System.out.println("AboutYo---------"+reg.getAboutYou());


    ModelAndView mv=new ModelAndView("home");

   return mv;
   }
}

Это ошибка вывода, которую я получаю:

AAA
BBB
QUERY- SQLQueryImpl(SELECT * FROM user where Username='john' AND Password='rambo')
UserId from DB- John
Password from DB- Rambo
Login TRUE
view name 1 - 
view name 2 - registrationForm
Sep 29, 2014 3:31:56 PM org.springframework.web.servlet.tags.RequestContextAwareTag doStartTag
SEVERE: Neither BindingResult nor plain target object for bean name 'registration' available as     request attribute
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'registration' available as request attribute

person Pawan Kumar    schedule 26.09.2014    source источник


Ответы (1)


вам нужно назначить новую модель в ModelAndView. если «Пользователь» - ваша модель, установите mv как

mv= new ModelAndView("регистрация","пользователь",новый пользователь());

И если пользователь не является вашим модельным классом, поместите эту модель вместо пользователя. и не забудьте добавить commandName в тег весенней формы. здесь «пользователь» — это ваше имя команды.

это сработает.

person Jimmy    schedule 26.09.2014
comment
Привет ....... Я попытался сделать это mv=new ModelAndView(registration,user,new User()); Но все же он показывает ту же ошибку. - person Pawan Kumar; 29.09.2014
comment
Привет, я не могу открыть другую страницу регистрации после успешного входа в систему. Кто-нибудь может мне помочь? - person Pawan Kumar; 29.09.2014
comment
привет, предоставит мне точную ошибку, которую вы получаете. а вместо ModelAndView, почему бы вам не попробовать String как возвращаемый тип. - person Jimmy; 12.11.2014