Upload file using Servlets/JSP in Java

Hello friends!

In many web applications, the user needs to upload a file on the web so that it can be used later on. Java EE allows developers to create dynamic web applications using Servlets or JSP (Java Server Pages). A Servlet is like any other Java class. You insert your HTML code into print statements like you use System.out. On the other hand, a JSP gets converted to a Servlet and embeds the Java code into HTML. Servlets and JSP are functionally equivalent.

In this post I will demonstrate how to upload a file using the Servlets/JSP technology.

Pre-requisites: Eclipse IDE for Java EE developers, Apache Tomcat 7

Open Eclipse. Create a new Dynamic web project. Name the project as FileUploadExample. Select Target Runtime environment as Apache Tomcat 7.0. If you are unable to get this option, you need to configure and install Apache Tomcat 7 by following this link.

file_upload_1

Create new dynamic web project

Create new dynamic web project

Step 1: Add .jar files

Before you start implementing your Servlet code, you need to add two .jar files namely commons-fileupload-1.3.jar and commons-io-2.4.jar to the lib folder present under WEB-INF.

Step 2: Create JSP page

Now create a new JSP page named index.jsp inside your WebContent folder.

index.jsp


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>File Upload</title>
</head>
 
<body>

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

Step 3: Create Servlet and modify web.xml

Right click the src folder, and select New –> Servlet. Name the Servlet FileUploadDemoServlet and give the package name as com.example

FileUploadDemoServlet.java

package com.example;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
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.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 
            {

    	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("/");
                        
                        //path where the file will be stored
                        File path = new File("C:\\programs\\java_documents" + "/uploads");
                        if (!path.exists())
                        {
                            boolean status = path.mkdirs();
                        }
 
                        File uploadedFile = new File(path + "/" + fileName);
                        System.out.println(uploadedFile.getAbsolutePath());
                        item.write(uploadedFile);
                    }
                }
            } catch (FileUploadException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

Modify your web.xml file as follows!

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>FileUploadExample2</display-name>
  
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  
  <servlet>
        <servlet-name>FileUploadDemoServlet</servlet-name>
        <servlet-class>com.example.FileUploadDemoServlet</servlet-class>
  </servlet>
    
  <servlet-mapping>
        <servlet-name>FileUploadDemoServlet</servlet-name>
        <url-pattern>/fileuploadservlet</url-pattern>
  </servlet-mapping>
   
</web-app>

Finally, run the project on the Apache Tomcat server. Make sure no errors are present. You should see the following output on your console and browser respectively!

Output on browser and console

file_upload_output_1

Tutorial #12: Creating your first Struts 2 Application!

Hello everyone,

Last time I told you about some of the features offered by Java EE. Today I will be talking about a popular framework called Struts 2. Apache Struts 2 was designed to streamline the development cycle of applications, right from building to deploying and maintaining them for over a period of time. Struts 2 was used mainly to create enterprise-ready Java web applications.

For this tutorial, you need to download Eclipse IDE for Java EE. Alternatively, you may also use NetBeans or any other IDE as the steps would more or less be the same. It is recommended that you also download the latest version of JDK and Tomcat web server and properly set them up inside Eclipse. Here is a good tutorial for the same.

Step 1: Open up Eclipse. Click New–>Dynamic Web Project. Give a name to your project say “TestStruts1” and click Finish.

Step 2: Adding Struts 2 JAR files

Download the necessary JAR files from here. Note that depending on the current version of Struts 2, the version number of the various JAR files may change. Add these files to the WEB-INF/lib folder present in your project.

The necessary JAR files to be added are:

    commons-logging.jar
    freemarker.jar
    ognl.jar
    struts2-core.jar
    xwork.jar
    javassist.jar
    commons-lang.jar

Additional JAR files can be added as per your requirement.

Step 3: Configuring web.xml

Before you start coding you need to configure your application to use Struts 2. For this purpose, we define a Filter inside WEB-INF/web.xml that acts as an entry point for our Struts 2 Application.

Here is how your web.xml will look:


<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"  xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
 

<display-name>TestStruts1</display-name>  
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  
   <filter>
		<filter-name>struts2</filter-name>
		<filter-class> org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
   </filter>
 
   <filter-mapping>
	<filter-name>struts2</filter-name>
	<url-pattern>/*</url-pattern>
   </filter-mapping>

</web-app>

Note: The FilterDispatcher filter is deprecated since the Struts version 2.1.3. If you are using the latest version of Struts 2 then use StrutsPrepareAndExecuteFilter class instead.

Step 4: Create Action class.

Create a new class named WelcomeUserAction under a package named pack.

WelcomeUserAction.java

package pack;
import com.opensymphony.xwork2.ActionSupport;

public class WelcomeUserAction extends ActionSupport
{
	 
	private String username;
 
	public String getUsername()
    {
		return username;
	}
 
	public void setUsername(String username)
    {
		this.username = username;
	}
 
	// all struts logic here
	public String execute() 
	{
 
		return "SUCCESS";
 
	}
}

Step 5: Create struts.xml

Inside the src folder, create a new XML file named struts.xml

Write the following code:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
 
<struts>
	<package name="p1" namespace="" extends="struts-default">
		<action name="Login">
			<result>login.jsp</result>
		</action>
		<action name="Welcome" class="pack.WelcomeUserAction">
			<result name="SUCCESS">welcome_user.jsp</result>
		</action>
	</package>
</struts>

Step 6: Creating JSP and HTML Pages

Now, as seen from the above struts.xml file we need to define two JSP pages namely login.jsp and welcome_user.jsp

login.jsp


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

<h1>Struts 2 Hello World Example</h1>
 
 <s:form action="Welcome">
		<s:textfield name="username" label="Username" />
		<s:password name="password" label="Password" />
		<s:submit />
</s:form>
	
</body>
</html>

welcome_user.jsp


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

<h1>Struts 2 Hello World Example</h1>
	<h4>
		Hello
		<s:property value="username" />
	</h4>
</body>
</html>

index.html

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<a href="Login">Click here to Login!</a>
</body>
</html>

Finally, it’s done! Make sure no errors are present. Right click your Project, Run As–>Run on Server–>Select Tomcat Server and click Finish.

Here are few screenshots of the final application!

Screenshot 1

Screenshot 2

struts2_sample_3

Stepping into the world of Java EE!

Hey everyone,

It’s been a long time since I last posted over here. It feels great to be back after learning some cool technologies that many developers still use to create quality web applications. Java provides us with a platform called Java EE using which we can create enterprise applications. Through this article, I will bring out some of the features of Java EE and talk about my experiences so far!

Java EE applications are basically multitiered applications that consists of three or four tiers namely:

1) Client tier that includes components running on client machine.

2) Web tier that includes components running on the Java EE Application Server.

3) Business tier that also includes components running on the Java EE Application Server, and finally,

4) Enterprise Information System (EIS) tier, software that runs on the EIS Server.

Java EE Multi-tiered Applications

Generally, most Java EE applications are considered to be 3-tiered comprising of client machines, Java EE Application Server and the database or legacy machines at the back end.

The current version of Java EE i.e Java EE 6 was launched on December 10, 2009. It added some valuable features namely:

Servlets 3.0

The new version of Java EE allowed developers to use annotations while declaring Servlets. A Servlet is basically a Java class in Java EE that helps you to create server side programs.

Java Persistence API 2.0

The Java Persistence API or JPA is a Java framework for managing relational data in applications. It provides POJO (Plain Old Java Objects) standard and Object Relational mapping for accessing, persisting and managing data between Java objects/classes.

Java Server Faces 2.0

Another significant feature was the use of annotations in JSF 2.0, thereby avoiding the use of faces-config.xml and web.xml.

It has been quite a number of years now and you may wonder what prompted me to write this article. I was aware of these technologies back then but never tried using them until a few weeks back. I feel for any aspiring Java developer, these technologies could just lay the foundation for creating rich enterprise applications in the future. With rapid technological advancements, one may soon start realizing the importance of learning such technologies.

So I hope you give Java EE a try soon! I would be talking about Servlets, JPA, Struts2 and much more in my upcoming posts! Enjoy! 🙂

Pic Courtesy