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

aaronyeo22Asked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

CEHJCommented:
>>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
chaitu chaituCommented:
changed little bit in servlet

 List items = upload.parseRequest(request);
                Iterator iterator = items.iterator();

		int i=1;
                while (iterator.hasNext()) {
                    FileItem item = (FileItem) iterator.next();

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

                        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"+i, item.getName());
                                        response.sendRedirect("cde.jsp");
                        item.write(uploadedFile);
                    }
                }


JSP
*****

		String item1 = (String) request.getSession().setAttribute("item1");
		String item2 = (String) request.getSession().setAttribute("item2");

		<input id="filename_1" type="file" name="filename_1" size="50" value='<%=item1%>'/><br/>
            <input id="filename_2" type="file" name="filename_2" size="50" value='<%=item2%>'/><br/>

Open in new window

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
chaitu chaituCommented:
sorry you should initialize i as 0;
i=0;
Webinar: Cyber Crime Becomes Big Business

The rising threat of malware-as-a-service is not one to be overlooked. Malware-as-a-service is growing and easily purchased from a full-service cyber-criminal store in a “Virus Depot” fashion. Join us in our upcoming webinar as we discuss how to best defend against these attacks!

chaitu chaituCommented:
String item1 = (String) request.getSession().getAttribute("item1");
            String item2 = (String) request.getSession().getAttribute("item2");

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

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

That's true. Probably better to do it generically though imo
aaronyeo22Author Commented:
thanks
sunu340Commented:
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 :)
chaitu chaituCommented:
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.
aaronyeo22Author Commented:
sunu340 can help me
aaronyeo22Author Commented:
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
aaronyeo22Author Commented:
fix already. thanks sunu340
aaronyeo22Author Commented:
chaituu: your solution only able to upload one file. sorry
CEHJCommented:
>>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.
chaitu chaituCommented:
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
JSP

From novice to tech pro — start learning today.