Link to home
Start Free TrialLog in
Avatar of aaronyeo22
aaronyeo22Flag for Malaysia

asked on

servlet pass data to jsp

when i try to upload two file and use  
out.println(item.getName()); it can display the two file name like : abc.gif and cde.gif

how do i display this two file name in jsp with two text input.

thanks


 <fieldset>
        <legend>Upload File</legend>
        <form action="uploadservlet" method="post" enctype="multipart/form-data">
            <label for="filename_1">File: </label>
            <input id="filename_1" type="file" name="filename_1" size="50"/><br/>
            <label for="filename_2">File: </label>
            <input id="filename_2" type="file" name="filename_2" size="50"/><br/>
            <br/>
            <input type="submit" value="Upload File"/>
        </form>
    </fieldset>

index.jsp

import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import java.io.IOException;
import java.io.File;
import java.io.PrintWriter;
import java.util.List;
import java.util.Iterator;

public class FileUploadDemoServlet extends HttpServlet {
    private static final long serialVersionUID = -3208409086358916855L;

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

         PrintWriter out = response.getWriter();
          response.setContentType("text/plain");
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);

        if (isMultipart) {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);

            try {
                List items = upload.parseRequest(request);
                Iterator iterator = items.iterator();
                while (iterator.hasNext()) {
                    FileItem item = (FileItem) iterator.next();

                    if (!item.isFormField()) {
                        String fileName = item.getName();

                        String root = getServletContext().getRealPath("/");
                        File path = new File(root + "/uploads");
                        if (!path.exists()) {
                            boolean status = path.mkdirs();
                        }

                        File uploadedFile = new File(path + "/" + fileName);
                        out.println(item.getName());

                        request.getSession().setAttribute("item", item);
                                        response.sendRedirect("cde.jsp");
                        item.write(uploadedFile);
                    }
                }
            } catch (FileUploadException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

FileUploadDemoServlet.java

Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

>>out.println(item.getName()); it can display the two file name like : abc.gif and cde.gif

Just pass the jsp a parameter called 'filenames' say. Concatenate the strings produced by the code i quoted into a comma-separated list
ASKER CERTIFIED SOLUTION
Avatar of chaitu chaitu
chaitu chaitu
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
sorry you should initialize i as 0;
i=0;
String item1 = (String) request.getSession().getAttribute("item1");
            String item2 = (String) request.getSession().getAttribute("item2");

>>String item1 = (String) request.getSession().getAttribute("item1");

How will you know how many items there are?
as he is expecting two .gif files.so we can hardcoded with item1 amd item2 etc..;but that is not the generic way.
he is having only textboxes so we have hardcodes.if he is having multiple text boxes then it is better to follow another approach.
2 textboxes
>>he is having only textboxes so we have hardcodes.

That's true. Probably better to do it generically though imo
Avatar of aaronyeo22

ASKER

thanks
First of all the above code will not execute for both the files as response.sendRedirect("cde.jsp"); is used inside the while loop,so the code will redirect before executing for both files.

To send the file names to jsp,you can simply add the file names in a list and set the list in session as it is done :

boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (isMultipart) {
    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    try {
        List items = upload.parseRequest(request);
      Iterator iterator = items.iterator();
      List<String> filenames = new ArrayList<String>();
      while (iterator.hasNext()) {
      FileItem item = (FileItem) iterator.next();
        if (!item.isFormField()) {
          String fileName = item.getName();
            String root = getServletContext().getRealPath("/");
          File path = new File(root + "/uploads");
          if (!path.exists()) {
                 boolean status = path.mkdirs();
          }

          File uploadedFile = new File(path + "/" + fileName);
          filenames.add(fileName);                              
          item.write(uploadedFile);
        }
    }
    request.getSession().setAttribute("item", filenames);
    response.sendRedirect("cde.jsp");  
    } catch (FileUploadException e) {
              e.printStackTrace();
    } catch (Exception e) {
              e.printStackTrace();
    }
}

**********JSP*********
<%
java.util.List<String> filenames = (java.util.List<String>)request.getSession().getAttribute("item");
for(String filename: filenames) {
%>
      <input id="filename_1" type="text"" name="filename_1" size="50" value='<%=filename%>'/><br/>
<%
}
%>

Hope this helps :)
yes you are correct.there are so many approaches to send the list to jsp.this is one of them.even putting filenames to session you can print the filenames using request scope.
sunu340 can help me
really sorry . chaituu only can upload one file. but yours one is two files. but after i submit that becomes 4 text input. i just want two. thanks
fix already. thanks sunu340
chaituu: your solution only able to upload one file. sorry
>>chaituu: your solution only able to upload one file. sorry

Worries about the number of files it allows just show, as i mentioned earlier, that the solution should be generic - so it doesn't matter how many there are.