0

Guys i've been trying to upload a file with some data comming from form fields but I had no luck, the servlet which I'm ussing is down here. As you can see afther the for is initialized an If is there, that if is working ok but the rest of condtional if are ignored and no data is retrieved or displayed(with the out.print) so I'm pasting here the servlet code in hope someone will see what afther hours and hours I couldn't see, please guys help me out with the issue.

import DAO.CuentaCobroDAO;
import DTO.CuentaCobroDTO;
import DTO.contratoDTO;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
*
* @author Leonardo
*/
public class CuentaCobroCtrol extends HttpServlet {

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, FileUploadException, ParseException, SQLException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    CuentaCobroDAO ccdao= new CuentaCobroDAO();
    CuentaCobroDTO cdto= new CuentaCobroDTO();
    contratoDTO con= new contratoDTO();
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
    FileItemFactory fif= new DiskFileItemFactory();
    ServletFileUpload sfu= new ServletFileUpload(fif);
    String fechai="", fechaf="";
    String contrato, dias=null;
    String valor, arl=null, eps=null, pension=null;
    List items=sfu.parseRequest(request);
    java.sql.Date fi, ff, factual;
    Date fechaActual;

   try{ 
    for (int i = 0; i < items.size(); i++) {
        FileItem item = (FileItem) items.get(i);

        if(item.isFormField()){

            if(item.getFieldName().equals("fechai")){
            fechai=obtenerDatoDeFormulario(item.getInputStream());
           out.print(fechai);
            }

            if(item.getFieldName().equals("fechaf")){
                fechaf=obtenerDatoDeFormulario(item.getInputStream());
                out.print("FECHAF"+fechaf);
            }


            if(item.getFieldName().equals("numcont")){
                contrato=obtenerDatoDeFormulario(item.getInputStream());
                out.print("CONTRATO"+contrato);
            }
            if(item.getFieldName().equals("dias")){
                dias=obtenerDatoDeFormulario(item.getInputStream());
                out.println(dias);
            }
            if(item.getFieldName().equals("valor")){
                valor=obtenerDatoDeFormulario(item.getInputStream());
                out.print(valor);
            }
            if(item.getFieldName().equals("arl")){
                arl=obtenerDatoDeFormulario(item.getInputStream());
                out.println("Por ARL:"+arl);
            }
            if(item.getFieldName().equals("eps")){
                eps=obtenerDatoDeFormulario(item.getInputStream());
                out.println("Por EPS:"+eps);
            }
            if(item.getFieldName().equals("pension")){
                pension=obtenerDatoDeFormulario(item.getInputStream());
                out.println("Por PENSION:"+pension);
            }

            out.print("El valor 2 de fecha I es:"+fechai);

        }
        /*            A continuación validamos que los campos que vienen del formulario no estén vacios, esto en caso de que javascript falle,
        así garantizamos que tenemos todos los datos; hago esto antes de escribir el archivo en el servidor para evitar que se suba
        información que está incompleta y no debe ser subida sino hasta que se compruebe que se tienen todos los datos.*/
        out.print("El valor 3 de fechai es:"+fechai+"el de final es:"+fechaf);
            fechaActual=  new Date();
            Date inicial=formatter.parse(fechai);
            fi= new java.sql.Date(inicial.getTime());
            Date ffinal=formatter.parse(fechaf);
            ff= new java.sql.Date(ffinal.getTime());
            factual=new java.sql.Date(fechaActual.getTime());
            out.print("El valor 4:"+fechai+"Y el de final es:"+fechaf);
            if(fi.compareTo(factual)>0 || ff.compareTo(factual)>0){
                response.sendRedirect("nomina/cuentacobro.jsp?msg="+"Error, no puedes ingresar una cuenta del mes futuro o actual");
                break;
            }else if(dias!=null){
                response.sendRedirect("nomina/cuentacobro.jsp?msg= Debes ingresar los días trabajados");
                break;
            }else if(30<Integer.parseInt(dias)){
                response.sendRedirect("nomina/cuentacobro.jsp?msg= En el mes pueden ser máximo 30 días");
                break;
            }else if(arl==null){
                response.sendRedirect("nomina/cuentacobro.jsp?msg= Tienes que ingresar el valor de la ARL");
                break;
            }else if(eps==null){
                response.sendRedirect("nomina/cuentacobro.jsp?msg= Es necesario ingresar el valor de la EPS");
                break;
            }else if(pension==null){
                response.sendRedirect("nomina/cuentacobro.jsp?msg= Debes ingresar el valor de pensión");
                break;
            }else{
                String ruta="/archivos/pdf/"+request.getSession(false).getAttribute("iduser")+"/";
                String nombreArchivo=request.getSession(false).getAttribute("iduser")+"-"+factual;
                if(!item.isFormField()){


                    File archivoAServidor= new File(getServletContext().getRealPath(ruta+nombreArchivo));
                    try {
                        item.write(archivoAServidor);
                    } catch (Exception ex) {
                        Logger.getLogger(CuentaCobroCtrol.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            cdto.setFinicial(fi);
            cdto.setFfinal(ff);
            cdto.setDias(Integer.parseInt(request.getParameter("dias")));
            cdto.setHoras(Integer.parseInt(request.getParameter("horas")));
            cdto.setPagoArl(Integer.parseInt(request.getParameter("arl")));
            cdto.setPagoEps(Integer.parseInt(request.getParameter("eps")));
            cdto.setPagoPension(Integer.parseInt(request.getParameter("pension")));
            cdto.setIdContratista((Integer)request.getSession(false).getAttribute("iduser"));
            cdto.setValorAPagar(Integer.parseInt(request.getParameter("valor")));
            con.setIdCONTRATO((Integer)request.getSession(false).getAttribute("idContrato"));
            cdto.setRutaDocumento(ruta+nombreArchivo);
            String salida=cdto.insertCuenta(cdto, con);
            response.sendRedirect("nomina/cuentacobro.jsp?msg="+salida);
            }
    }
   }catch(IOException iex){
       throw iex;
   }catch(ParseException pex){
       throw pex;
   }






    try {
        /* TODO output your page here. You may use following sample code. */
        out.println("<!DOCTYPE html>");
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet CuentaCobroCtrol</title>");            
        out.println("</head>");
        out.println("<body>");
        out.println("<h1>Servlet CuentaCobroCtrol at " + request.getContextPath() + "</h1>");
        out.println("</body>");
        out.println("</html>");
    } finally {
        out.close();
    }
}

private static String obtenerDatoDeFormulario(InputStream is){
    BufferedReader br=null;
    StringBuilder sb= new StringBuilder();

    String linea;


    try {
        br= new BufferedReader(new InputStreamReader(is));
        while((linea=br.readLine())!= null){
            sb.append(linea);
        }
    } catch (IOException ex) {
        ex.printStackTrace();
    } finally{
        if(br!=null){
            try {
                br.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }

    return sb.toString();

}


// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
 * Handles the HTTP <code>GET</code> method.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {
        processRequest(request, response);
    } catch (FileUploadException ex) {
        Logger.getLogger(CuentaCobroCtrol.class.getName()).log(Level.SEVERE, null, ex);
    } catch (ParseException ex) {
        Logger.getLogger(CuentaCobroCtrol.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SQLException ex) {
        Logger.getLogger(CuentaCobroCtrol.class.getName()).log(Level.SEVERE, null, ex);
    }
}

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {
        processRequest(request, response);
    } catch (FileUploadException ex) {
        Logger.getLogger(CuentaCobroCtrol.class.getName()).log(Level.SEVERE, null, ex);
    } catch (ParseException ex) {
        Logger.getLogger(CuentaCobroCtrol.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SQLException ex) {
        Logger.getLogger(CuentaCobroCtrol.class.getName()).log(Level.SEVERE, null, ex);
    }
}

/**
 * Returns a short description of the servlet.
 *
 * @return a String containing servlet description
 */
@Override
public String getServletInfo() {
    return "Short description";
}// </editor-fold>

}

PD: The out.print are used to show the informatión gathered from the fiel but after the first If is processed then the others are just ignored.

Leo21
  • 13
  • 1
  • 7

3 Answers3

0

I'm not sure if this will help any, as I am using annotations in this example, but here is a sample servlet that uploads a file and saves it to the file system: https://www.openshift.com/forums/openshift/how-to-upload-and-serve-files-using-java-servlets-on-openshift

  • mmm well the matter here is that I've already did the upload file servlet and just used the example to build this one, my problem is with the read of inputs coming from the form 'cause they aren't being picked up and the if seems like being ignored after the first one is evaluated. – Leo21 Jan 14 '14 at 13:16
  • Can you verify what items.size is by logging it somewhere our outputting it to the screen? Maybe just loop through it and get the field names and print them out? –  Jan 14 '14 at 15:24
  • I can try it, but I think I won't get anything cause as I mentioned before the first "if" of the list which evaluates "fechai" is being executed but the rest just aren't and as it is doing the cycle, even been just one cycle I believe it should execute it 'cause the cicle has been started as long as the use of "for" states tha the cycle is executed at leats once until it reaches the condition so all the if's should be executed or Do I'm wrong? – Leo21 Jan 14 '14 at 15:41
0

You will get the uploaded file if it is NOT a form field. So, your check should be:

 if(!item.isFormField()){
     String fileName = item.getName();
     InputStream is = item.getInputStream();
     // process the file
 } else {
     // Get the field name
     String fieldName = item.getName();
     // Get the field value
     String value = item.getString();
 }

Check out http://commons.apache.org/proper/commons-fileupload/using.html for more details.

Salil
  • 9,534
  • 9
  • 42
  • 56
  • Thanks, I understand that but what I want to achieve is to retrieve data from form fields given that the initial form is a multipart form which contains the file to be uploaded and some information, what I want to do is to catch that information of the form fields to put them into variable's so I can write that info to the database an upload a file which corresponds to that information – Leo21 Jan 15 '14 at 18:11
  • Then why do you have code like "item.getInputStream()" when it is a form field? Also, are all these file items? – Salil Jan 16 '14 at 18:23
  • 'cause I need to get the imput coming from the form wich is equals to the name of the field, so I use item.getimputStream to send the data to the convert method (ObtenerDatoDeFormulario) for that field so it can be converted to an string! but as I mentioned before the first field of the form is the only one recognized the others are just ignored I don't know why! – Leo21 Jan 17 '14 at 22:26
0

Well guys afther thinking for a long long time, I had a genious spark and finally realized what was going on with this servelet so explenation is here:

Firs I need to say that at the begining I couldn't understand how data is sent to the servlet when the form is a multipart, so here was the huge mistake, we have to undestand that every single form field is going to be comverted as an item so for the form I was using I had 9 fields so the cicle will run 10 times and here was the mistake, if you analize my first servlet you'll find that I was using if(9 times) and then a nested if which was parsing a date and here the whole thing is wrong way, cause as the cicle iterates over each item found then it will evaluate all the if's found there on the body of the for so with just the first cicle I've got an unparseable date exception and here nothing nothing works so keep in mind that when doing cicles even with Iterator or for each it will run the number of times equals to the number of items evaluating what is inside the cicle so be cautious of what conditions you evaluate and how you do it. So here I'll put the correct servlet which do exactly what I want and that is: get the content of the form fields then get the file to be writed on the server, write it and finally store the information fo the form field on a database. Here you'll find the servlet (excuse if some code is confusing, it could be cause it's written in Spanish)

package controlador;

import DAO.CuentaCobroDAO;
import DTO.CuentaCobroDTO;
import DTO.contratoDTO;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.io.File;
import java.io.PrintWriter;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Calendar;


/**
*
* @author Leonardo
*/
public class CuentaCobroCtrol extends HttpServlet {

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, FileUploadException, ParseException, SQLException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();                
    String fechaIni="";
    String fechaFin="";
    String contrato="";
    String valorArl="";
    String valorEps="";
    String valorPension="";
    String valorAPagar="";
    String numeroDias="";
    String ruta="";
    String nombreArchivo="";
    String timeStamp="";
    boolean suceed=false;
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); 
    CuentaCobroDAO ccdao= new CuentaCobroDAO();
    CuentaCobroDTO cdto= new CuentaCobroDTO();
    contratoDTO con= new contratoDTO();


    FileItemFactory ff = new DiskFileItemFactory();



    ServletFileUpload sfu = new ServletFileUpload(ff);



    List items = sfu.parseRequest(request);
    java.sql.Date fi=null, fif=null, factual=null;
    Date fechaActual;

   try{ 


       for(int i=0;i<items.size();i++){



        FileItem item = (FileItem) items.get(i);

        if (item.isFormField()){  

                         /*            A continuación validamos que los campos que vienen del formulario no estén vacios, esto en caso de que javascript falle,
        así garantizamos que tenemos todos los datos; hago esto antes de escribir el archivo en el servidor para evitar que se suba
        información que está incompleta y no debe ser subida sino hasta que se compruebe que se tienen todos los datos.*/
          if(item.getFieldName().equals("numcont")){
              contrato=getStringFromInputStream(item.getInputStream());
              out.print("<br/>  el valor de numero es: "+contrato);  
          }
          if(item.getFieldName().equals("dias")){
              numeroDias=getStringFromInputStream(item.getInputStream());
              out.print(" <br/> el valor de dias es: "+numeroDias);  
              if(numeroDias==null){
                response.sendRedirect("nomina/cuentacobro.jsp?msg= Debes ingresar los días trabajados");
                break;}else if(30<Integer.parseInt(numeroDias)){
                response.sendRedirect("nomina/cuentacobro.jsp?msg= En el mes pueden ser máximo 30 días");
                break;
            }
          }
          if(item.getFieldName().equals("valor")){
              valorAPagar=getStringFromInputStream(item.getInputStream());
              out.print(" <br/> el valor  es: "+valorAPagar); 
              if(Integer.parseInt(valorAPagar)<=0 || valorAPagar==null){
                  response.sendRedirect("nomina/cuentacobro.jsp?msg= El valor no puede ser nagativo o nulo. Por favor ingresa el valor a pagar");
              }
          }
          if(item.getFieldName().equals("arl")){
              valorArl=getStringFromInputStream(item.getInputStream());
              out.print(" <br/> el valor de arl es: "+valorArl);  
              if(valorArl==null){
                response.sendRedirect("nomina/cuentacobro.jsp?msg= Tienes que ingresar el valor de la ARL");
                break;
            }
          }
          if(item.getFieldName().equals("eps")){
              valorEps=getStringFromInputStream(item.getInputStream());
              out.print(" <br/> el valor de eps es: "+valorEps);  
              if(valorEps==null){
                response.sendRedirect("nomina/cuentacobro.jsp?msg= Es necesario ingresar el valor de la EPS");
                break;
            }
          }
          if(item.getFieldName().equals("pension")){
              valorPension=getStringFromInputStream(item.getInputStream());
              out.print(" <br/> el valor de pension es: "+valorPension); 
              if(valorPension==null){
                response.sendRedirect("nomina/cuentacobro.jsp?msg= Debes ingresar el valor de pensión");
                break;
            }
          }
           if(item.getFieldName().equals("fechai"))  
        {  
            fechaIni=getStringFromInputStream(item.getInputStream());
            out.print("el valor de fechaInicial es: "+fechaIni);
            if(fechaIni==null || fechaIni.length()<4){
                response.sendRedirect("nomina/cuentacobro.jsp?msg= Error, no ingresaste el valor de fecha periodo inicial");
            }
        }
          if(item.getFieldName().equals("fechaf")){
              fechaFin=getStringFromInputStream(item.getInputStream());
              fechaActual=  new Date();
            Date inicial=formatter.parse(fechaIni);
            fi= new java.sql.Date(inicial.getTime());
            Date ffinal=formatter.parse(fechaFin);
            fif= new java.sql.Date(ffinal.getTime());
            factual=new java.sql.Date(fechaActual.getTime());
            if(fi.compareTo(factual)>0 || fif.compareTo(factual)>0){
                response.sendRedirect("nomina/cuentacobro.jsp?msg="+"Error, no puedes ingresar una cuenta del mes futuro o actual");
                break;
            }

          }
     }

        if(!item.isFormField()){
               timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime());
               ruta="/archivos/pdf/"+request.getSession(false).getAttribute("iduser")+"/";
               nombreArchivo=request.getSession(false).getAttribute("iduser")+"-"+timeStamp+".pdf";
                    File dir=new File(ruta+nombreArchivo);
                    dir.mkdirs();
                    File archivoAServidor= new File(getServletContext().getRealPath(ruta+nombreArchivo));

                    try {
                        item.write(archivoAServidor);
                        suceed=true;
                    } catch (Exception ex) {
                        Logger.getLogger(CuentaCobroCtrol.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
    }
    if(suceed==true){
        cdto.setFinicial(fi);
            cdto.setFfinal(fif);
            cdto.setDias(Integer.parseInt(numeroDias));
            cdto.setHoras(Integer.parseInt("0"));
            cdto.setPagoArl(Integer.parseInt(valorArl));
            cdto.setPagoEps(Integer.parseInt(valorEps));
            cdto.setPagoPension(Integer.parseInt(valorPension));
            cdto.setIdContratista((Integer)request.getSession(false).getAttribute("iduser"));
            cdto.setValorAPagar(Integer.parseInt(valorAPagar));
            con.setIdCONTRATO((Integer)request.getSession(false).getAttribute("idContrato"));
            cdto.setRutaDocumento(ruta+nombreArchivo);
            String salida=cdto.insertCuenta(cdto, con);
            response.sendRedirect("nomina/cuentacobro.jsp?msg="+salida);
    }



   }catch(IOException iex){
       throw iex;
   }catch(ParseException pex){
       throw pex;
   }






    try {
        /* TODO output your page here. You may use following sample code. */
        out.println("<!DOCTYPE html>");
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet CuentaCobroCtrol</title>");            
        out.println("</head>");
        out.println("<body>");
        out.println("<h1>Servlet CuentaCobroCtrol at " + request.getContextPath() + "</h1>");
        out.println("</body>");
        out.println("</html>");
    } finally {
        out.close();
    }
}

private static String getStringFromInputStream(InputStream is) {

    BufferedReader br = null;
    StringBuilder sb = new StringBuilder();

    String line;
    try {

        br = new BufferedReader(new InputStreamReader(is));
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }

    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (br != null) {
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    return sb.toString();

}


// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
 * Handles the HTTP <code>GET</code> method.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {
        processRequest(request, response);
    } catch (FileUploadException ex) {
        Logger.getLogger(CuentaCobroCtrol.class.getName()).log(Level.SEVERE, null, ex);
    } catch (ParseException ex) {
        Logger.getLogger(CuentaCobroCtrol.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SQLException ex) {
        Logger.getLogger(CuentaCobroCtrol.class.getName()).log(Level.SEVERE, null, ex);
    }
}

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {
        processRequest(request, response);
    } catch (FileUploadException ex) {
        Logger.getLogger(CuentaCobroCtrol.class.getName()).log(Level.SEVERE, null, ex);
    } catch (ParseException ex) {
        Logger.getLogger(CuentaCobroCtrol.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SQLException ex) {
        Logger.getLogger(CuentaCobroCtrol.class.getName()).log(Level.SEVERE, null, ex);
    }
}

/**
 * Returns a short description of the servlet.
 *
 * @return a String containing servlet description
 */
@Override
public String getServletInfo() {
    return "Short description";
}// </editor-fold>

}
Leo21
  • 13
  • 1
  • 7