#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2012
    Posts
    8
    Rep Power
    0

    First Java Servlet (File Upload)


    I'm jumping two feet first into the world of Java (previously a PHP programmer) and attempting to write my first servlet. I'm using a sample class from a tutorial I found.

    Code:
    <%@page contentType="text/html" pageEncoding="UTF-8"%>
    <!DOCTYPE html>
    <html>
        <head>
            <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
            <title>JSP Page</title>
        </head>
        <body>
            <form action="FileUploadServlet" enctype="multipart/form-data" method="POST">
                <input type="text" name="filename"/> <br/>
                <input type="file" name="file1"><br>
                <input type="Submit" value="Submit"><br>
            </form>
        </body>
    </html>
    Code:
    package efi.mailmerge.servlets;
    
    import java.io.File;
    import java.io.IOException;
    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.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import org.apache.commons.fileupload.FileItem;
    import org.apache.commons.fileupload.FileUploadException;
    import org.apache.commons.fileupload.disk.DiskFileItemFactory;
    import org.apache.commons.fileupload.servlet.ServletFileUpload;
    
    public class FileUploadServlet extends HttpServlet {
    
    
        protected void processRequest(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            response.setContentType("text/html;charset=UTF-8");
            PrintWriter out = response.getWriter();
            File repository=new File("/Users/Jeff/Development/ReServe-Unleashed/Dev/MailMerge/uploads");
            try {
                DiskFileItemFactory diskFileItemFactory=new DiskFileItemFactory();
    //set temporary dir where uploaded files will be stored
                diskFileItemFactory.setRepository(repository);
    //set the file size threshold beyond from which file will be stored in the disk
                diskFileItemFactory.setSizeThreshold(5*1024*1024);
    //initialize form handler
                ServletFileUpload servletFileUpload= new ServletFileUpload(diskFileItemFactory);
    //get form fields
                List<FileItem> uploadedItems = servletFileUpload.parseRequest(request);
                for (FileItem fileItem : uploadedItems) {
    //if file item is a normal form filed take some action
                    if(fileItem.isFormField()){
                        String fieldName = fileItem.getFieldName();
                        System.out.println("FIELDNAME:"+fieldName);
                    }else{
                        String name = fileItem.getName();
                        System.out.println("NAME:"+name);
                        File uploadedFile=new File(repository.getAbsolutePath()+"\\"+name);
                        fileItem.write(uploadedFile);
                    }
                }
    
            } catch (Exception ex) {
                Logger.getLogger(FileUploadServlet.class.getName()).log(Level.SEVERE, null, ex);
            } finally {
                out.close();
            }
        }
    
    
        @Override
        protected void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            processRequest(request, response);
        }
    
    
        @Override
        protected void doPost(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            processRequest(request, response);
        }
    }
    I've got my class compiling without errors and setup Tomcat using IntelliJ as my IDE. That seems to be ok. However, when I go to index.jsp in my browser and attempt to upload a file, I'm receiving a 404 error: HTTP Status 404 - /FileUploadServlet

    As you can see in the index.jsp file, the action of the form is "FileUploadServlet". How does this work? In the PHP world of things, a file called "FileUploadServlet" would actually have to exist which would explain the 404 error I'm receiving. To re-word my question, how do I get the form to submit to my Java class file for execution?

    Any help is appreciated as I attempt to wrap my head around this. Thanks!
  2. #2
  3. Contributing User
    Devshed Regular (2000 - 2499 posts)

    Join Date
    May 2004
    Location
    Superior, CO, USA
    Posts
    2,418
    Rep Power
    1713
    Jeff - there are two ways in Java/Java EE to map a servlet to a URL.

    The first is to create a web.xml file that does the mapping for you. You didn't specify how your directory structure is laid out but, given the code you have you'd need something like:

    Code:
    webappName
        index.jsp
        web.xml
        WEB-INF
            classes
                efi
                    mailmerge
                        servlets
                            FileUploadServlet.class
    Each indent above is meant to imply a new directory. If you choose to go down the web.xml path, your web.xml must contain something like:


    xml Code:
    <?xml version="1.0" encoding="utf-8"?>
    <web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
        version="3.0">
     
        <welcome-file-list>
            <welcome-file>index.jsp</welcome-file>
        </welcome-file-list>
     
        <servlet>
            <servlet-name>FileUploadServlet</servlet-name>
            <servlet-class>efi.mailmerge.servlets.FileUploadServlet</servlet-class>
        </servlet>
     
        <servlet-mapping>
            <servlet-name>FileUploadServlet</servlet-name>
            <url-pattern>/FileUploadServlet</url-pattern>
        </servlet-mapping>
    </web-app>


    Note that this assumes that you are running under a JEE 6+ container (Tomcat 7, Glassfish 3, etc.)

    Another way (again, assuming a newer JEE container) is with anotations. The directory layout is almost the same (you still need the web.xml but without either the <servlet> or <servlet-mapping> stanzas). But in your servlet code you'll have something like:

    java Code:
    ...
    import org.apache.commons.fileupload.servlet.ServletFileUpload;
    import javax.servlet.annotation.WebServlet;
     
    @WebServlet( urlPatterns = {"/FileUploadServlet"} )
    public class FileUploadServlet extends HttpServlet {
    ...


    This defines the URL path that the servlet uses in the code, not in the XML file.

    Either way will work. I'd argue that it's faster to test with the annotation method (Java annotations start with the '@' character like the WebServlet above) but it is nice to see every path in one place like with the web.xml version.

    Once you have all that you'll need to go to something like

    http://localhost:8080/webapName/FileUploadServlet

    in your browser to see your servlet execute the doGet() method. If you're accessing your JSP then it will just be

    http://localhost:8080/webapName

    where "webappName" is anything you want. If you're using Tomcat it will be in the $TOMCAT_HOME/webapps directory but it should be under its own directory.
    Last edited by stdunbar; March 15th, 2013 at 04:53 PM.
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2012
    Posts
    8
    Rep Power
    0
    Thank you so much! I really appreciate you taking the time to explain this so well. I updating my mappings in web.xml and all seems to be working perfectly.

IMN logo majestic logo threadwatch logo seochat tools logo