Announcement Announcement Module
Collapse
No announcement yet.
Command problems Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Command problems

    Hi,

    I'm having a problem with the Command.

    Code:
    Neither BindingResult nor plain target object for bean name 'reportCommand' available as request attribute
    When I enter in my webpage it's load correctly but when it's call itself the server show the error.

    I don't know what is the issue. I post a part of my code:

    Form:

    Code:
    <form:form method="post" commandName="reportCommand" name="AltaReportForm" id="AltaReportForm">
    Controller:
    Code:
    protected ModelAndView onSubmit(
    			HttpServletRequest request,
    			HttpServletResponse response, 
    			Object command,
    			BindException errors)
    	throws Exception{
    ...
    
    sesion.setAttribute("listaerrores", control.getAltaReportControllerError(crearReportCommandConDatosRequest(file)));
    	    			mav.setViewName("redirect:"+Constantes.ALTA_REPORT);
    	    			return mav;
    command:


    Code:
    public class ReportCommand {
    	
    	private String nombre;
    	private String area;
    	private String descripcion;
    	private String descripcionLarga;
    	private String autor;
    	private String fechaInicio;
    	private String diaInicio;
    	private String mesInicio;
    	private String anyoInicio;
    	
    	public ReportCommand ()
    	{
    		
    	}
    	
    	public ReportCommand(String area, String autor, String descripcion,
    			String descripcionLarga, String fechaInicio, String nombre,
    			String diaInicio, String mesInicio, String anyoInicio) {
    		super();
    		this.area = area;
    		this.autor = autor;
    		this.descripcion = descripcion;
    		this.descripcionLarga = descripcionLarga;
    		this.fechaInicio = fechaInicio;
    		this.nombre = nombre;
    		this.diaInicio = diaInicio;
    		this.mesInicio = mesInicio;
    		this.anyoInicio = anyoInicio;
    	}
    
    ...
    the command have the getter and setters too

    servlet:

    Code:
    <bean name="/AltaReport.htm" class="com.uw.controller.AltaReportController">
    	<property name="sessionForm" value="true"/>
    	<property name="commandName" value="reportCommand"/>
        <property name="commandClass" value="com.uw.command.ReportCommand"/>
        <property name="control" ref="control" />
         <property name="bindOnNewForm" value="true"/>
    </bean>
    Thanks you
    Last edited by praedos; Aug 14th, 2008, 06:09 AM.

  • #2
    Hi,

    Looks like the controller is posting to itself, i mean the form page and success page is the same or the success page has the form.

    Add the following in you onSubmit method of the controller
    Code:
    protected ModelAndView onSubmit(
    			HttpServletRequest request,
    			HttpServletResponse response, 
    			Object command,
    			BindException errors)
    	throws Exception{
    Map map = new HashMap();
    map.put(getCommandName(),(ReportCommand)command);
    return new ModelAndView("whateverview",map);
    
    }

    Comment


    • #3
      Thank you a lot but that is not the problem.

      I have done a test. In the method onSubmit I put a System.out line and it does not show. That means that the method is never called. The error is throw before.

      Perhaps it's an error in the creation of the Command, I read in the Spring guie that you can create a Command by the declaration in the constructor of setCommandClass or by the declaration of the method formBackingObject like me.

      Then, Where is the problem?

      Comment


      • #4
        Hello praedos,

        Have you tried removing "name" and "id" from your <form:form> tag?

        Comment


        • #5
          Hi,

          Your xml code does not have formView and successView tags and their values. Could you please post your controller class?

          My form has both name and id and it still displaying with out error.

          Thanks,
          Gupta

          Comment


          • #6
            Hi ,

            Could you post the controller's entire code and add the formView property in the xml,

            Comment


            • #7
              Ok,

              Thank you for your answer. I put formView in XML but it do nothing.

              Here you have the code of the controller:

              Code:
              package com.uw.diode.controller;
              
              import java.io.DataInputStream;
              import java.io.File;
              import java.io.FileOutputStream;
              import java.util.HashMap;
              import java.util.List;
              import java.util.Map;
              import javax.servlet.ServletException;
              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 org.springframework.web.servlet.mvc.SimpleFormController;
              import com.uw.diode.error.ErrorControl;
              import com.uw.diode.error.Control;
              import com.uw.diode.command.ReportCommand;
              import com.uw.diode.exception.FicheroExistenteException;
              import com.uw.diode.util.Constantes;
              
              /**
               * Clase que controla la pantalla de alta de reports
               * @author jaarjona
               *
               */
              public class AltaReportController extends SimpleFormController {
              	
              	private Control control;
              
              	public Control getControl() {
              		return control;
              	}
              
              	public void setControl(Control control) {
              		this.control = control;
              	}
              
              	/**
              	 * Controla la salida de onSubmit de la pantalla
              	 * @param HttpServletRequest request
              	 * @param HttpServletResponse response
              	 * @param Object command
              	 * @param BindException erros
              	 * @return ModelAndView
              	 * @exception Exception
              	 */
              	protected ModelAndView onSubmit(
              			HttpServletRequest request,
              			HttpServletResponse response, 
              			Object command,
              			BindException errors)
              	throws Exception{
              		
              		System.out.println("Aquí llega");
              		
              		ModelAndView mav = new ModelAndView ();
              		
              		String contentType = request.getContentType();
                  	String file = "";
                  	String saveFile;
                  	String boundary;
                  	String nombreFichero = "";
                  	
                  	DataInputStream input;
                  	FileOutputStream fileOut = null;
                  	File fichero = null;
                  	
                  	HttpSession sesion = request.getSession();
                  	
                  	int formDataLength;
                  	int byteRead = 0;
                  	int totalBytesRead = 0;
                  	int lastIndex;
                  	int pos;
                  	int boundaryLocation;
                  	int startPos;
                  	int endPos;
                  	
                  	byte dataBytes[];
                  	
                  	//Comprobamos el que request tenga valores de multipart/form-data, es decir, que sea un formulario en bytes.
                  	if ((contentType != null) && (contentType.indexOf("multipart/form-data") >= 0))
                  	{
                  		try
                  		{
              	    		input = new DataInputStream(request.getInputStream());
              	    		formDataLength = request.getContentLength(); //Tomamos el valor del tamaño del fichero
              	    		dataBytes = new byte[formDataLength]; 
              	    		lastIndex = contentType.lastIndexOf("=");
              	    		
              	    		//Convierte el archivo de subida en un codigo byte    		
              	    		while (totalBytesRead < formDataLength)
              	    		{
              	    			byteRead = input.read(dataBytes, totalBytesRead, formDataLength);
              	    						totalBytesRead += byteRead;
              	    		}
              	    		
              	    		//Pasamos los bytes a una cadena
              	    		file = new String(dataBytes);
              	    		
              	    		if (control.getAltaReportControllerError(crearReportCommandConDatosRequest(file)).size() > 0)
              	    		{
              	    			sesion.setAttribute("listaerrores", control.getAltaReportControllerError(crearReportCommandConDatosRequest(file)));
              	    			mav.setViewName("redirect:"+Constantes.ALTA_REPORT);
              	    			return mav;
              	    		}
              	    		
              	    		//Para guardar el nombre del archivo...
              	    		saveFile = file.substring(file.indexOf("filename=\"") + 10);
              	    		saveFile = saveFile.substring(0, saveFile.indexOf("\n"));
              	    		saveFile = saveFile.substring(saveFile.lastIndexOf("\\") + 1,saveFile.indexOf("\""));
              	    		
              	    		if (!saveFile.equals(""))
              	    		{
              		    		boundary = contentType.substring(lastIndex + 1, contentType.length());
              		    		
              		    		//Extrayendo el índice del archivo 
              		    		pos = file.indexOf("filename=\"");
              		    		pos = file.indexOf("\n", pos) + 1;
              		    		pos = file.indexOf("\n", pos) + 1;
              		    		pos = file.indexOf("\n", pos) + 1;
              		    		boundaryLocation = file.indexOf(boundary, pos) - 4;
              		    		startPos = ((file.substring(0, pos)).getBytes()).length;
              		    		endPos = ((file.substring(0, boundaryLocation)).getBytes()).length;
              		    				    		
              		    		//Creando un nuevo archivo con el mismo nombre y escribiendo el contenido en el nuevo archivo.
              		    		fichero = new File (Constantes.RUTA_INFORMES+File.separator+nombreFichero);
              		    		
              		    		if (fichero.exists())
              		    			throw new FicheroExistenteException ();
              		    		
              		    		fileOut = new FileOutputStream(Constantes.RUTA_INFORMES+File.separator+nombreFichero);
              		    		fileOut.write(dataBytes, startPos, (endPos - startPos));
              		    		fileOut.flush(); //Limpiamos la caché
              		    		fileOut.close(); //Cerramos el fileOutputStream
              	    		}
                  		}
                  		finally
                  		{
                  			if (fileOut != null)
                  				fileOut.close(); //Cerramos el fileOutputStream
                  		}
                  	}
                  	
              		return mav;
              	}
              	
              	/**
                   * Este método nos permite añadir contenido a la web
                   * @param HttpServletRequest
                   * @return Map<String, Object>
                   */
              	@SuppressWarnings("unchecked")
              	protected Map<String, Object> referenceData(HttpServletRequest request) {
              		
              		System.out.println("Entra en el reference data");
              
                      //hashmap de datos
                  	Map<String, Object> hmPerfilForm = new HashMap<String, Object>();
                  	
                  	List<ErrorControl> listaerrores = (List<ErrorControl>) request.getSession(true).getAttribute("listaerrores");
                  	
                  	if (listaerrores != null && listaerrores.size()>0){
                  		hmPerfilForm.put("errores",listaerrores);
                  	}
                  	request.getSession().setAttribute("listaerrores",null);
              
                  	return hmPerfilForm;
                  }
              	
              	/**
              	 * Controla la entrada de datos del Command en la página
              	 * @param HttpServletRequest request
              	 * @return Object
              	 * @exception ServletException
              	 */
              	protected Object formBackingObject(HttpServletRequest request) throws ServletException {
              		
              		ReportCommand reportCommand = new ReportCommand ();
              		
              		return reportCommand;
              	}
              	
              	/**
                   * Toma los valores de un fichero binario y los devuelve en cadena de caracteres
                   * @param String parametro
                   * @param String fichero
                   * @return String
                   */
                  private String obtenerParametrosDelFicheroRequest(String parametro, String fichero)
                  {
                  	/* El fichero es un fichero de texto plano en el que buscamos los nombres de los parámetros y su valor. Es importante que
                  	 * el parámetro tenga un nombre ya que en el fichero aparece este y no el ID.
                  	 */
                  	String valorParametro;
                  	
                  	int posicion = 0;
                  	
                  	posicion = fichero.indexOf(parametro);
                  	
                  	if (posicion == -1)
                  		valorParametro = "";
                  	else
                  	{    	
              			posicion = fichero.indexOf("\n", posicion) +1 ;
              			posicion = fichero.indexOf("\n", posicion) +1 ;
              			
              			valorParametro = fichero.substring(posicion,fichero.indexOf("\n", posicion)).trim();
                  	}
                  	
                  	return valorParametro;
                  }
                  
                  /**
                   * Toma los valores del request y devuelve un ReportCommand
                   * @param String file
                   * @return ReportCommand
                   */
                  private ReportCommand crearReportCommandConDatosRequest (String file) throws Exception
                  {
                  	ReportCommand reportCommand = new ReportCommand ();
                  	
              		//Tomamos el valor del nombre
              		reportCommand.setNombre(obtenerParametrosDelFicheroRequest("nombre", file));
              		
              		//Tomamos el valor del area
              		reportCommand.setArea(obtenerParametrosDelFicheroRequest("area", file));
              		
              		//Tomamos el valor de la descripción
              		reportCommand.setDescripcion(obtenerParametrosDelFicheroRequest("descripcion", file));
              		
              		//Tomamos el valor de la descripción larga
              		reportCommand.setDescripcionLarga(obtenerParametrosDelFicheroRequest("descripcionLarga", file));
              		
              		//Tomamos el valor del día de inicio
              		reportCommand.setDiaInicio(obtenerParametrosDelFicheroRequest("diaInicio", file));
              		
              		//Tomamos el valor del mes de inicio
              		reportCommand.setMesInicio(obtenerParametrosDelFicheroRequest("mesInicio", file));
              		
              		//Tomamos el valor del año de inicio
              		reportCommand.setAnyoInicio(obtenerParametrosDelFicheroRequest("anyoInicio", file));		
              		
              		return (reportCommand);
                  }
              }

              Comment


              • #8
                Hi,

                I am looking for a solution. I have discovered that if I remove all form:input the problem is solved but i can see what is the problem, the first time that the page run It go well but when I push on submit button show the error.

                It is as if it could not load the fields in the command But the command is specified correctly.

                It must be and a configuration error on XML but I can't fount it.

                I put the command code:

                Code:
                public class ReportCommand {
                	
                	private String nombre;
                	private String area;
                	private String descripcion;
                	private String descripcionLarga;
                	private String autor;
                	private String fechaInicio;
                	private String diaInicio;
                	private String mesInicio;
                	private String anyoInicio;
                	
                	public ReportCommand ()
                	{
                		
                	}
                	
                	public ReportCommand(String area, String autor, String descripcion,
                			String descripcionLarga, String fechaInicio, String nombre,
                			String diaInicio, String mesInicio, String anyoInicio) {
                		super();
                		this.area = area;
                		this.autor = autor;
                		this.descripcion = descripcion;
                		this.descripcionLarga = descripcionLarga;
                		this.fechaInicio = fechaInicio;
                		this.nombre = nombre;
                		this.diaInicio = diaInicio;
                		this.mesInicio = mesInicio;
                		this.anyoInicio = anyoInicio;
                	}
                
                	public String getNombre() {
                		return nombre;
                	}
                
                	public void setNombre(String nombre) {
                		this.nombre = nombre;
                	}
                
                	public String getArea() {
                		return area;
                	}
                
                	public void setArea(String area) {
                		this.area = area;
                	}
                
                	public String getDescripcion() {
                		return descripcion;
                	}
                
                	public void setDescripcion(String descripcion) {
                		this.descripcion = descripcion;
                	}
                
                	public String getDescripcionLarga() {
                		return descripcionLarga;
                	}
                
                	public void setDescripcionLarga(String descripcionLarga) {
                		this.descripcionLarga = descripcionLarga;
                	}
                
                	public String getAutor() {
                		return autor;
                	}
                
                	public void setAutor(String autor) {
                		this.autor = autor;
                	}
                
                	public String getFechaInicio() {
                		return fechaInicio;
                	}
                
                	public void setFechaInicio(String fechaInicio) {
                		this.fechaInicio = fechaInicio;
                	}
                
                	public String getDiaInicio() {
                		return diaInicio;
                	}
                
                	public void setDiaInicio(String diaInicio) {
                		this.diaInicio = diaInicio;
                	}
                
                	public String getMesInicio() {
                		return mesInicio;
                	}
                
                	public void setMesInicio(String mesInicio) {
                		this.mesInicio = mesInicio;
                	}
                
                	public String getAnyoInicio() {
                		return anyoInicio;
                	}
                
                	public void setAnyoInicio(String anyoInicio) {
                		this.anyoInicio = anyoInicio;
                	}
                }

                Comment


                • #9
                  Hello praedos,

                  You are using sessionForm, and if you are still seeing error msg like "Neither BindingResult nor plain target object for bean name 'reportCommand' available as request attribute" with the fact that your initial view been displayed successfully, then it's very likely cause is the form object has not been added to session! This step is done automatically in one of showForm method.

                  Are you sure you haven't override this method? If you did, you need to call super.showForm at the end of your method.

                  Hope this helps.

                  Comment


                  • #10
                    Hi thebugslayer,

                    I'm sure that this method is not overrided. Although, I have overrided this method and put

                    Code:
                    return super.showForm(request, response, errors);
                    to try if it works ... and not. But the problem must be for this way. I´m going to show some lines of the server messages to help you.

                    Code:
                    [#|2008-08-13T09:25:59.747+0200|INFO|sun-appserver9.1|javax.enterprise.system.stream.out|_ThreadID=18;_ThreadName=httpSSLWorkerThread-8080-1;|21882 [httpSSLWorkerThread-8080-1] DEBUG com.uw.diode.controller.ReportController  - Displaying new form
                    
                    [#|2008-08-13T09:25:59.762+0200|INFO|sun-appserver9.1|javax.enterprise.system.stream.out|_ThreadID=18;_ThreadName=httpSSLWorkerThread-8080-1;|21897 [httpSSLWorkerThread-8080-1] DEBUG org.springframework.web.servlet.view.JstlView  - Added model object 'reportCommand' of type [com.uw.diode.command.ReportCommand] to request in view with name 'AltaReport'
                    
                    [#|2008-08-13T09:25:59.762+0200|INFO|sun-appserver9.1|javax.enterprise.system.stream.out|_ThreadID=18;_ThreadName=httpSSLWorkerThread-8080-1;|21897 [httpSSLWorkerThread-8080-1] DEBUG org.springframework.web.servlet.view.InternalResourceViewResolver  - Cached view [AltaReport]
                    
                    [#|2008-08-13T09:25:59.762+0200|INFO|sun-appserver9.1|javax.enterprise.system.stream.out|_ThreadID=18;_ThreadName=httpSSLWorkerThread-8080-1;|21897 [httpSSLWorkerThread-8080-1] DEBUG org.springframework.web.servlet.DispatcherServlet  - Rendering view [org.springframework.web.servlet.view.JstlView: name 'AltaReport'; URL [/jsp/AltaReport.jsp]] in DispatcherServlet with name 'diodereporting'
                    
                    [#|2008-08-13T09:25:59.762+0200|INFO|sun-appserver9.1|javax.enterprise.system.stream.out|_ThreadID=18;_ThreadName=httpSSLWorkerThread-8080-1;|21897 [httpSSLWorkerThread-8080-1] DEBUG org.springframework.web.servlet.view.JstlView  - Rendering view with name 'AltaReport' with model {reportCommand=com.uw.diode.command.ReportCommand@3e0c6, org.springframework.validation.BindingResult.reportCommand=org.springframework.validation.BeanPropertyBindingResult: 0 errors} and static attributes {}
                    
                    [#|2008-08-13T09:25:59.762+0200|INFO|sun-appserver9.1|javax.enterprise.system.stream.out|_ThreadID=18;_ThreadName=httpSSLWorkerThread-8080-1;|21897 [httpSSLWorkerThread-8080-1] DEBUG org.springframework.web.servlet.view.JstlView  - Added model object 'reportCommand' of type [com.uw.diode.command.ReportCommand] to request in view with name 'AltaReport'
                    
                    [#|2008-08-13T09:25:59.762+0200|INFO|sun-appserver9.1|javax.enterprise.system.stream.out|_ThreadID=18;_ThreadName=httpSSLWorkerThread-8080-1;|21897 [httpSSLWorkerThread-8080-1] DEBUG org.springframework.web.servlet.view.JstlView  - Added model object 'org.springframework.validation.BindingResult.reportCommand' of type [org.springframework.validation.BeanPropertyBindingResult] to request in view with name 'AltaReport'
                    
                    [#|2008-08-13T09:25:59.762+0200|INFO|sun-appserver9.1|javax.enterprise.system.stream.out|_ThreadID=18;_ThreadName=httpSSLWorkerThread-8080-1;|21897 [httpSSLWorkerThread-8080-1] DEBUG org.springframework.web.servlet.view.JstlView  - Forwarding to resource [/jsp/AltaReport.jsp] in InternalResourceView 'AltaReport'
                    As you can see show "Added model object 'reportCommand' to request" and the error is "nor plain target object for bean name 'reportCommand' available as request attribute"... I don't understand...

                    Comment


                    • #11
                      Hi,

                      please put the following code in the onsubmit method of your controller,

                      Code:
                      protected ModelAndView onSubmit(
                      			HttpServletRequest request,
                      			HttpServletResponse response, 
                      			Object command,
                      			BindException errors)
                      	throws Exception{
                      		
                      	// basically you are enriching the command object from the file object //that you have recieved.
                      // after calling the method that returns you the enriched command object
                      ReportCommand reportCommand = crearReportCommandConDatosRequest(file);
                      // add this line of code
                      ModelAndView mv = new ModelAndView("viewname",getCommandName(),reportCommand);
                      The framework is designed in such a way that it removes the form object from the session whenever there is a form submission.

                      Comment


                      • #12
                        Hi Sami25,

                        Thank you for your answer, but it still doesn't work.

                        I'm going to put more information:

                        In the Controller I have 3 method from SimpleFormController:

                        - referenceData
                        - onSubmit
                        - formBackingObject

                        In the three I have put a message to see in server log and I can see that the application enter into the formBackingObject then enter in referenceData and never enter in onSubmit.

                        In this way, I think that the problem not in the onSubmit method. The problem must be before of the onSubmit method.

                        Thank you a lot

                        Comment


                        • #13
                          Problem found but not resolved

                          Hi all!

                          I'm using the application server Glassfish (Sun application server). It is the first time that I use it, before Apache Tomcat 6 was using.

                          I try to run my new application with Apache Tomcat and surprise! It's works!

                          Now the problem is, How can I use Glassfish application server?

                          Should I open a new post?

                          Thank you,

                          Praedos

                          Comment


                          • #14
                            i got similar problem but i cleared it in this way

                            since form submission is 2 stage process.For the first time u must pass GET request to the controller.This can be done in this way just provide a a link that points to Contextpath/AltaReport.htm

                            hope this helps u

                            Comment

                            Working...
                            X