• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 513
  • Last Modified:

jsp to servlet

sunu340 : i need your help. i was succeeded to get that two file name. but how do i pass this two file names to servlet.

because in servlet i need string this two files.
0
aaronyeo22
Asked:
aaronyeo22
  • 23
  • 22
3 Solutions
 
rrzCommented:
I guess this is a continuation of  
http://www.experts-exchange.com/Programming/Languages/Java/J2EE/JSP/Q_27486012.html?cid=748#a37266265 
What trouble are you having with sunu340's solutution ?  
Please explain in detail. What do you want to do with the file names in the servlet ?    
0
 
aaronyeo22Author Commented:
sunu340 was provided the solution to me. In servlet i need to string request.getParameter that two files.
how do i string in servlet. thanks
0
 
aaronyeo22Author Commented:
<fieldset>
        <legend>Upload File</legend>
        <form action="asdas" 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.ArrayList;
import java.util.List;
import java.util.Iterator;

public class asdas 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();

            //int i=0;
                  List<String> filenames = new ArrayList<String>();
                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());


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

asdas.java
--------------------------------------------------

  <%
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/>
<%
}
%>

cde.jsp
----------------------------

filename_1 contains two files name and how do i pass to servlet. i need to string this two files.

thanks. please help.
0
Network Scalability - Handle Complex Environments

Monitor your entire network from a single platform. Free 30 Day Trial Now!

 
aaronyeo22Author Commented:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            performTask(request, response);
      }

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

      private void performTask(HttpServletRequest request, HttpServletResponse response) throws ServletException,
                  IOException {


                String pdfFileName = "ddd/cdee.pdf";
                System.out.println(pdfFileName);
            String contextPath = getServletContext().getRealPath(File.separator);
            File pdfFile = new File(contextPath + pdfFileName);

            response.setContentType("application/pdf");
            response.addHeader("Content-Disposition", "attachment; filename=" + pdfFileName);
            response.setContentLength((int) pdfFile.length());

            FileInputStream fileInputStream = new FileInputStream(pdfFile);
            OutputStream responseOutputStream = response.getOutputStream();
            int bytes;
            while ((bytes = fileInputStream.read()) != -1) {
                  responseOutputStream.write(bytes);

            }
                       
      }

how do i use cde.jsp pass parameter to servlet string:  
String pdfFileName = "ddd/cdee.pdf";
0
 
rrzCommented:
Please explain in more detail. What do you want to accomplish ? Describe the navigational flow of your web application.  

For example, the code that you posted does is the following.
In index.jsp  the user  uploads his chosen files to the Servlet mapped to "asdas".
The  Servlet receives the files and put the files into server file system.
The Servlet creates a list of the uploaded files and sets that list into session scope.  
The Servlet redirects the user to cde.jsp
cde.jsp  reads the gets the filenames  list from the session scope.  
cde.jsp prints out the file names in its response to the user.    

Is this what you want your web application to do ?  
Do you want to change it ?  


Ok, I see your latest post.  You have a second Servlet. I guess you want this second servlet to serve the files.  
So, I guess you want  cde.jsp to display links to the uploaded files. That way the users can chose which file to open up.  Is this what you want to do ?


0
 
rrzCommented:
If I guessed right then use the following in cde.jsp
<%
java.util.List<String> filenames = (java.util.List<String>)request.getSession().getAttribute("item");
for(String filename: filenames) {
%>
     <a href="mappingSecondServlet?name=<%=filename%>">Read <%=filename%></a <br/>
<%
}
%>

Open in new window

  and in second Servlet use
 String pdfFileName = request.getParameter("name");

Open in new window

0
 
rrzCommented:
error  
<a href="mappingSecondServlet?name=<%=filename%>">Read <%=filename%></a <br/>  
should have been  
<a href="mappingSecondServlet?name=<%=filename%>">Read <%=filename%></a> <br/>
0
 
aaronyeo22Author Commented:
<a href="gettt?name=<%=filename%>">Read <%=filename%></a> <br/>

thats true my second servlet name is gettt. but still got error http status 404
0
 
rrzCommented:
>but still got error http status 404  
Look at the source code that cde.jsp sent to the browser. Is the link's url right ?
0
 
rrzCommented:
I assume that you mapped your second Servlet to "gettt" in the same way that you mapped your first to "asdas".  
Is that right ?
0
 
aaronyeo22Author Commented:
yes
0
 
rrzCommented:
Is the link's url right ?  Show what is sent to browser.
0
 
aaronyeo22Author Commented:
String pdfFileName = request.getParameter("uploads/name");
                //String pdfFileName = "uploads/billing_398141815_4ecc8eb8d22f5.pdf";
//                String []filename_1 = request.getParameterValues(""
//                        + "filename_1");
                System.out.println(pdfFileName);
            String contextPath = getServletContext().getRealPath(File.separator);
            File pdfFile = new File(contextPath + pdfFileName);

            response.setContentType("application/pdf");
            response.addHeader("Content-Disposition", "attachment; filename=" + pdfFileName);
            response.setContentLength((int) pdfFile.length());

            FileInputStream fileInputStream = new FileInputStream(pdfFile);
            OutputStream responseOutputStream = response.getOutputStream();
            int bytes;
            while ((bytes = fileInputStream.read()) != -1) {
                  responseOutputStream.write(bytes);

            }

the code got any problem. i got error:java.io.FileNotFoundException: C:\apache-tomcat-6.0.33\webapps\NewApp\null (The system cannot find the file specified)

i upload that file under C:\apache-tomcat-6.0.33\webapps\NewApp\uploads

please help.
0
 
rrzCommented:
What does  
 System.out.println(pdfFileName);  
print out ?
0
 
aaronyeo22Author Commented:
null
0
 
aaronyeo22Author Commented:
sorry. can already
0
 
aaronyeo22Author Commented:
but my second servlet to serve these two files and i wanna use i submit button only  
0
 
aaronyeo22Author Commented:
but my second servlet need to serve these two files not one file and i wanna use one submit button only. sorry  
0
 
rrzCommented:
C:\apache-tomcat-6.0.33\webapps\NewApp\null  
I guess it is null.  
Show us the link that made the request.
0
 
aaronyeo22Author Commented:
still got error : C:\apache-tomcat-6.0.33\webapps\NewApp\hero.pdf

System.out.println(pdfFileName); = hero.pdf

because my file was uploaded in C:\apache-tomcat-6.0.33\webapps\NewApp\uploads/hero.pdf
0
 
aaronyeo22Author Commented:
0
 
rrzCommented:
>but my second servlet need to serve these two files not one file and i wanna use one submit button only. sorry  
You want to download two files at once ?
I don't think that is possible. You would have to zip them into one.
0
 
aaronyeo22Author Commented:
i dont want to download. i just want the parameter pass to servlet. thanks
0
 
rrzCommented:
>http://localhost:8080/NewApp/gettt?name=hero.pdf  
Instead of using  
String []filename_1 = request.getParameterValues(" + "filename_1");
use  
String pdfFileName = request.getParameter("name");
0
 
aaronyeo22Author Commented:
String pdfFileName = request.getParameter("name");


yes i am using the above code, but still error

System.out.println(pdfFileName); = C:\apache-tomcat-6.0.33\webapps\NewApp\hero.pdf

my file was uploaded in C:\apache-tomcat-6.0.33\webapps\NewApp\uploads/hero.pdf
0
 
rrzCommented:
The code of your gettt Servlet will download a file to the browser.
0
 
rrzCommented:
Instead of using  
>File pdfFile = new File(contextPath + pdfFileName);  
in your gettt servlet   use
File pdfFile = new File(contextPath + "uploads/" + pdfFileName);
or maybe try
File pdfFile = new File(contextPath + "/uploads/" + pdfFileName);
0
 
aaronyeo22Author Commented:
ya. that's only an example. actually i wanna pass the first .pdf file and second certificate file to generate a new pdf. so i need get the parameter of this two file pass to my servlet. please help.
0
 
rrzCommented:
By the way,
>String contextPath = getServletContext().getRealPath(File.separator);  
I would  use something like
String fileDirPath = getServletContext().getRealPath("/uploads");
0
 
aaronyeo22Author Commented:
File pdfFile = new File(contextPath + "/uploads/" + pdfFileName);

the above code was solved it. no problem.

but how do i use one button to submit and pass the two parameter(two files name) to servlet. please help me.
0
 
rrzCommented:
>so i need get the parameter of this two file pass to my servlet.
In cde.jsp instead of using
<a href="gettt?name=<%=filename%>">Read <%=filename%></a> <br/>
You could use  
<a href="gettt?namePdf=<%=filePdf%>&nameCert=<%=nameCert%>">Go to gettt</a> <br/>
you have to first create those Strings.
0
 
aaronyeo22Author Commented:
your means is one by one create a string?
0
 
rrzCommented:
> and i wanna use one submit button only.  
Make a HTML form  instead of the links.
0
 
rrzCommented:
>your means is one by one create a string?  
Yes.
0
 
aaronyeo22Author Commented:
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();

            int i=0;
                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);
                    }
                }
            } catch (FileUploadException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

FileUploadDemoServlet.java
---------------------------------------------------


   <%
               String item1 = (String) request.getSession().getAttribute("item1");
                 String item2 = (String) request.getSession().getAttribute("item2");


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

cde.jsp
----------------------------------------------

the above code that's more easier for me. but i dont know why it only can upload one file. can you please help me to look at. thanks
0
 
aaronyeo22Author Commented:
please help rrz@871311
0
 
rrzCommented:
Take these lines out of the while loop.
>                   request.getSession().setAttribute("item"+i, item.getName());
>                                        response.sendRedirect("cde.jsp");
0
 
rrzCommented:
No that is wrong
0
 
rrzCommented:
As sunu340 posted in your other question,  take  
>  response.sendRedirect("cde.jsp");  
out of loop and place it after it.
0
 
aaronyeo22Author Commented:
?? not understand
0
 
rrzCommented:
Take the redirect out of the while loop. You can only redirect once.
0
 
rrzCommented:
I have to go. I will be back in 3-4 hours.
0
 
aaronyeo22Author Commented:
k
0
 
rrzCommented:
I just noticed these lines in FileUploadDemoServlet.java
>File path = new File(root + "/uploads");
>...
>File uploadedFile = new File(path + "/" + fileName);  
That won't work.  Maybe you meant to make "path" a String.  
String path = root + "/uploads";  
Or you could use  
String path = getServletContext().getRealPath("/uploads");  

>but how do i use one button to submit and pass the two parameter(two files name) to servlet. please help me.
You can put them in <input> elements in a HTML form.
0
 
sunu340Commented:
@aaronyeo22:
I have provided the code snippet as a reference..So if u want to display the filename in cde.jsp and by a submit button u want the filename to pass to another servlet, try the below codes..

---cde.jsp---
<form action="GetUploadedFileServlet">
<%
java.util.List<String> filenames = (java.util.List<String>)session.getAttribute("item");
for(int i=0;i<filenames.size();i++) {
String filename = filenames.get(i);
%>
      <input id="filename_<%=i+1%>" type="text"" name="filename_<%=i+1%>" size="50" value='<%=filename%>'/><br/>
<%
}
%>
<input type="submit" value="Get File Content"/>
</form>

This will generate 2 input textbox with name and id : filename_1 and filename_2..and here I have used servlet "GetUploadedFileServlet'.

---GetUploadedFileServlet---
private void performTask(HttpServletRequest request,
                  HttpServletResponse response) throws ServletException, IOException {

            String pdfFileName = request.getParameter("filename_1").toString();
            System.out.println(pdfFileName);
            String contextPath = getServletContext().getRealPath(File.separator);
            File pdfFile = new File(contextPath+"uploads"+File.separator+pdfFileName);

            response.setContentType("application/pdf");
            response.addHeader("Content-Disposition", "attachment; filename="+ pdfFileName);
            response.setContentLength((int) pdfFile.length());

            FileInputStream fileInputStream = new FileInputStream(pdfFile);
            OutputStream responseOutputStream = response.getOutputStream();
            int bytes;
            while ((bytes = fileInputStream.read()) != -1) {
                  responseOutputStream.write(bytes);
            }

      }

Here I have used request.getParameter("filename_1").toString() to get the value of input box filename_1.The request parameter name will be same as the id of input box.
If u have used another name,use that name.
Again this is for reference,u can iterate the request parameter in a loop if u want to do different stuff with filename_2 as well.
 
Hope this helps :-)
0
 
aaronyeo22Author Commented:
thanks rrz@871311 and sunu340
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Improve Your Query Performance Tuning

In this FREE six-day email course, you'll learn from Janis Griffin, Database Performance Evangelist. She'll teach 12 steps that you can use to optimize your queries as much as possible and see measurable results in your work. Get started today!

  • 23
  • 22
Tackle projects and never again get stuck behind a technical roadblock.
Join Now