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