How to Upload Java Project in Eclipse

This tutorial will take you on the way to develop a Java servlet that handles file upload to server from customer, footstep by step. A simple Coffee spider web awarding will be developed to demonstrate upload facility. The awarding consists of:

    • An upload class that allows user to pick up a file to upload.
    • A Java servlet that parses the request and saves the uploaded file equally a permanent file on the server.
    • A bulletin page that shows successful/error messages.

In this tutorial, the application volition be developed using Eclipse IDE, so you are supposed to be familiar with Eclipse.

Table of content:

    1. Setting upwards surround
    2. Setting up Eclipse project
    3. Coding file upload form
    4. Creating the servlet
    5. Implementing code to handle file upload
    6. Coding message page
    7. Full lawmaking of the servlet class
    8. The generated web.xml file
    9. Testing the application

i. Setting upward surroundings

Before moving on, make sure you got the following software installed on your estimator (of course y'all can use newer versions):

    • Tomcat 6.0 or newer.
    • JDK/JRE half-dozen.0 or newer.
    • Eclipse IDE for Java EE Developers (Helios 3.6.2) or newer.
    • Apache Common File Upload 1.2.2 and Apache Commons IO ii.3

If you don't have one of the above software installed, download and install them by clicking on an private link. After downloading the Common File Upload library, extract the nothing file to a desired location, and make certain you got a JAR file chosen eatables-fileupload-ane.ii.ii.jar under lib directory. Likewise, the Commons IO library is a dependency for the Common File Upload library, and brand sure you got the JAR file commons-io-2.3.jar later extracting the cypher file. These JAR files volition exist used in the project.

NOTES: In this tutorial, we target the application to Servlet ii.v environment. For Servlet 3.0 or later, nosotros recommend this article: How to write upload file servlet with Servlet 3.0 API.

2. Setting up Eclipse project

two.1. Creating new project

In Eclipse'southward Java EE perspective, select File > New Dynamic Web Project from main menu. In the dialog New Dynamic Web Project, blazon UploadServletApp every bit Project name. Select 2.5 from the dropdown list Dynamic web module version:

create project 1

Click Stop. The project is created with some skeleton code.

2.2. Creating Java bundle

Under src directory, create a new Java package called net.codejava.upload. The project's initial construction should look like this:

project structure

ii.3. Adding Tomcat server

Skip this step you have Tomcat already appears in the Servers view.

Switch to Server views (Select Windows >Testify View >Others >Servers from chief carte). Correct click in the Servers view, select New >Server:

new server

In the dialog New Server, select Tomcat v6.0 Server. Click Side by side:

select server

In the side by side screen, click Browse button to select Tomcat's installation directory on your computer:

select tomcat install dir

NOTES: Yous may not see this screen if you used Tomcat before, equally Eclipse remembers Tomcat installation directory then it won't enquire you.

Click Next. In the Add and Remove screen, select UploadServletApp on the left and click Add button to move in to the right:

add app to server

Click Finish, the application UploadServletApp is now configured to run on Tomcat.

2.4. Making server runtime bachelor to the project

Tomcat provides API to work with Coffee servlets, so we demand to make that API available to the projection. Select Project > Properties from main menu. In the dialog Backdrop for UploadServletApp, select Targeted Runtimes on the left, and check Apache Tomcat v6.0 on the right:

targeted runtime check

2.5. Adding required libraries to the project

Copy 2 JAR files eatables-fileupload-one.two.2.jar and eatables-io-two.3.jar to WebContent\WEB-INF\lib directory under project directory. The Mutual File Upload API will be available to the project and packaged together with the awarding when creating a WAR file.

two.6. Testing Tomcat server

In the Servers view, click on the Start button to first Tomcat:

start server button

Then switch to Console view, if you see the last line looks like:

INFO: Server startup in 289 ms

That means the server has started successfully.

And pay attention at the line looks like this:

INFO: Starting Coyote HTTP/1.1 on http-8080

That means the server is listening on the port number 8080.

console view

three. Coding File Upload class

We need to create a JSP page that shows a form which allows user to pick up a file to upload. Right-click on WebContent directory, select New >JSP File from context menu. In the New JSP File dialog, enter proper noun of the JSP folio as "upload" nether File proper noun field:

new jsp file

Click Finish. The upload.jsp file is created nether WebContent directory.

Write code for the upload.jsp file equally follows:

<%@ page linguistic communication="coffee" contentType="text/html; charset=UTF-eight" 	pageEncoding="UTF-viii"%> <!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=UTF-eight"> <title>File Upload</title> </head> <body> 	<center> 		<form method="post" action="UploadServlet" enctype="multipart/form-data"> 			Select file to upload: <input type="file" name="uploadFile" /> 			<br/><br/>  			<input blazon="submit" value="Upload" /> 		</grade> 	</center> </body> </html>

As you can come across, the JSP code is pure HTML. Some noteworthy points are explained as follows:

- The class tag defines the following properties:

    • method="post": when submitting, form's data is sent to server using HTTP Post method. This is required for uploading file because file'southward content can be sent only via POST method.
    • action="UploadServlet": specifies a relative path on the server that handles file upload. In this example, nosotros use the path UploadServlet mapped to a Coffee servlet that handles file upload.
    • enctype="multipart/form-data": tells the browser that this form may incorporate upload data then the browser handles accordingly.

- The input tag (type = "file") displays a text field and a Browse button which allows the user to select a file from his figurer.

- The input tag (type = "submit") displays a submit button labeled as "Upload".

Adjacent, nosotros create a servlet to handle file upload from the upload.jsp folio.

four. Creating the Servlet

Select File >New > Servlet from main bill of fare. In the Create Servlet dialog:

    • Blazon or browse the package cyberspace.codejava.upload in the field Java package.
    • Type UploadServlet into the field Class name.

create servlet 1

Click Next. The next screen lets reviewing name and URL mapping of the servlet:

create servlet 2

Annotation that the URL mapping in this screen must friction match the value of the activeness attribute of the grade divers in the upload.jsp page:

<class method="post" action="UploadServlet" enctype="multipart/form-data">

Click Next. The last screen let usa determine which methods need to be generated:

create servlet 3

The simply method we need to implement in the servlet is doPost(), so let bank check just two check boxes:

    • Inherited abstract methods.
    • doPost.

Click Finish. The servlet UploadServlet class is generated with a skeleton as follows:

package com.upload;  import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;  /**  * Servlet implementation form UploadServlet  */ public class UploadServlet extends HttpServlet { 	individual static final long serialVersionUID = 1L;  	/** 	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse 	 *      response) 	 */ 	protected void doPost(HttpServletRequest request, 			HttpServletResponse response) throws ServletException, IOException { 		// TODO Motorcar-generated method stub 	} }

5. Implementing lawmaking to handle file upload

Information technology's fourth dimension to write actual lawmaking for the UploadServlet grade to read upload information and relieve it as a file on disk. We implement the code in the servlet's doPost() method.

five.one. Defining constants

We define some constants in the servlet as follows:

private static last String UPLOAD_DIRECTORY = "upload"; individual static final int THRESHOLD_SIZE 	= 1024 * 1024 * 3; 	// 3MB private static final int MAX_FILE_SIZE 		= 1024 * 1024 * 40; // 40MB private static final int MAX_REQUEST_SIZE 	= 1024 * 1024 * fifty; // 50MB

These constants will be used to configure upload settings.

    • UPLOAD_DIRECTORY: name of the directory on the server where upload file will be stored. The directory is chosen to be relative to the web awarding's directory.
    • THRESHOLD_SIZE: file that has size less than this threshold value will exist saved into memory. If the size is greater than this value, it will exist stored on disk, temporarily. The value is measured in bytes.
    • MAX_FILE_SIZE: specifies the maximum size of an upload file. We define this constant to hold a file up to 40MB.
    • MAX_REQUEST_SIZE: specifies the maximum size of a HTTP asking which contains the upload file and other grade'southward data, so this constant should be greater than the MAX_FILE_SIZE.

      All sizes are measured in bytes.

v.2. Checking if the request having upload data

Identify the following lines of code at the get-go of doPost() method:

// checks if the request actually contains upload file if (!ServletFileUpload.isMultipartContent(request)) { 	PrintWriter writer = response.getWriter(); 	writer.println("Request does not comprise upload data"); 	writer.flush(); 	render; }

That checks if the request contains upload data (indicated past the aspect enctype="multipart/form-data" of the upload form). If non, we print a message to the user and get out the method.

5.3. Configuring upload settings

Next, we configure some settings using the constants defined previously:

// configures upload settings DiskFileItemFactory mill = new DiskFileItemFactory(); factory.setSizeThreshold(THRESHOLD_SIZE); manufacturing plant.setRepository(new File(Organisation.getProperty("java.io.tmpdir")));  ServletFileUpload upload = new ServletFileUpload(factory); upload.setFileSizeMax(MAX_FILE_SIZE); upload.setSizeMax(MAX_REQUEST_SIZE);

The DiskFileItemFactory form manages file content either in memory or on disk. Nosotros call setSizeThreshold() method to specify the threshold above which files are stored on disk, nether the directory specified by the method setRepository(). In the above code, we specify the temporary directory available for Coffee programs. Files are stored temporarily in that directory and they will be deleted. So we need to copy the files from the temporary directory to a desired location.

The ServletFileUpload is the main form that handles file upload by parsing the request and returning a list of file items. Information technology is also used to configure the maximum size of a single file upload and maximum size of the request, by the methods setFileSizeMax()and setSizeMax() respectively.

5.4. Creating directory to store upload file

Because upload files are stored temporarily under a temporary directory, we need to save them nether some other directory permanently. The following code creates a directory specified by the constant UPLOAD_DIRECTORY under spider web application's root directory, if it does not exist:

// constructs the directory path to store upload file Cord uploadPath = getServletContext().getRealPath("") 	+ File.separator + UPLOAD_DIRECTORY; // creates the directory if it does not exist File uploadDir = new File(uploadPath); if (!uploadDir.exists()) { 	uploadDir.mkdir(); }

NOTES: It's not recommended to save files under the directory relative to application'south directory, because when re-deploying/united nations-deploying the application, all files may be lost. We use this approach for demo purpose but. In practise, you should consider storing files in a location which is independent of the application.

5.5. Reading upload data and save to file

And this is the well-nigh important code: parsing the request to relieve upload data to a permanent file on deejay:

List formItems = upload.parseRequest(asking); Iterator iter = formItems.iterator();  // iterates over form'south fields while (iter.hasNext()) { 	FileItem item = (FileItem) iter.next(); 	// processes only fields that are not grade fields 	if (!item.isFormField()) { 		String fileName = new File(item.getName()).getName(); 		String filePath = uploadPath + File.separator + fileName; 		File storeFile = new File(filePath);  		// saves the file on disk 		item.write(storeFile); 	} }

The parseRequest() method of ServletFileUpload class returns a list of form items which will be iterated to place the item (represented by a FileItem   object) which contains file upload data. The method isFormField() of FileItem   course checks if an particular is a form field or not. A not-form field particular may contain upload data, thus the check:

if (!detail.isFormField()) { }

And to save the file on deejay, we call the write(File) method of FileItem class.

6. Coding message page

Create a new JSP page called message.jsp under WebContent directory and paste the following code:

<%@ page language="coffee" contentType="text/html; charset=UTF-eight" 	pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"  	"http://www.w3.org/TR/html4/loose.dtd"> <html> <caput> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <championship>Upload</title> </head> <body> 	<eye> 		<h2>${requestScope.message}</h2> 	</eye> </body> </html>

The purpose of the bulletin.jsp folio is to show value of a belongings chosen "message" present in the asking scope, using expression language (EL): ${requestScope.message}

We will pass the actual bulletin from the servlet code.

6.1. Showing messages to the user

Information technology's necessary to show a message to the user to indicate whether the upload is done or there's an mistake occurred.

In case the upload has been done successfully:

asking.setAttribute("bulletin", "Upload has been done successfully!");

And in the other case, at that place was an error occurred:

asking.setAttribute("bulletin", "At that place was an error: " + ex.getMessage());

Finally, the following lawmaking redirects the user to the bulletin.jsp page:

getServletContext().getRequestDispatcher("/message.jsp").forrard(request, response);

vii. Full code of the servlet form

The following is complete source code of the UploadServlet.java class:

package internet.codejava.upload;  import java.io.File; import coffee.io.IOException; import java.io.PrintWriter; import java.util.Iterator; import java.util.List;  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.eatables.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload;  /**  * A Coffee servlet that handles file upload from customer.  * @author world wide web.codejava.internet  */ public class UploadServlet extends HttpServlet { 	private static final long serialVersionUID = 1L;  	private static final String UPLOAD_DIRECTORY = "upload"; 	private static final int THRESHOLD_SIZE 	= 1024 * 1024 * 3; 	// 3MB 	private static final int MAX_FILE_SIZE 		= 1024 * 1024 * xl; // 40MB 	private static terminal int MAX_REQUEST_SIZE 	= 1024 * 1024 * 50; // 50MB  	/** 	 * handles file upload via HTTP Post method 	 */ 	protected void doPost(HttpServletRequest request, 			HttpServletResponse response) throws ServletException, IOException { 		// checks if the request actually contains upload file 		if (!ServletFileUpload.isMultipartContent(request)) { 			PrintWriter author = response.getWriter(); 			writer.println("Request does non comprise upload data"); 			writer.flush(); 			return; 		} 		 		// configures upload settings 		DiskFileItemFactory factory = new DiskFileItemFactory(); 		mill.setSizeThreshold(THRESHOLD_SIZE); 		manufacturing plant.setRepository(new File(Arrangement.getProperty("coffee.io.tmpdir"))); 		 		ServletFileUpload upload = new ServletFileUpload(factory); 		upload.setFileSizeMax(MAX_FILE_SIZE); 		upload.setSizeMax(MAX_REQUEST_SIZE); 		 		// constructs the directory path to store upload file 		String uploadPath = getServletContext().getRealPath("") 			+ File.separator + UPLOAD_DIRECTORY; 		// creates the directory if it does not exist 		File uploadDir = new File(uploadPath); 		if (!uploadDir.exists()) { 			uploadDir.mkdir(); 		} 		 		endeavour { 			// parses the asking'south content to excerpt file data 			List formItems = upload.parseRequest(request); 			Iterator iter = formItems.iterator(); 			 			// iterates over form's fields 			while (iter.hasNext()) { 				FileItem item = (FileItem) iter.next(); 				// processes only fields that are not grade fields 				if (!item.isFormField()) { 					String fileName = new File(detail.getName()).getName(); 					String filePath = uploadPath + File.separator + fileName; 					File storeFile = new File(filePath); 					 					// saves the file on disk 					item.write(storeFile); 				} 			} 			request.setAttribute("message", "Upload has been washed successfully!"); 		} catch (Exception ex) { 			request.setAttribute("message", "There was an fault: " + ex.getMessage()); 		} 		getServletContext().getRequestDispatcher("/bulletin.jsp").forward(request, response); 	} }

Every bit yous can see, the lawmaking that parses the request and saves upload data is placed inside a endeavour-catch block. In example of exception, nosotros fix an fault bulletin every bit value for the "message" object. And finally, the servlet forrard user to the message.jsp page.

viii. The generated web.xml file

Although nosotros don't touch the spider web.xml file at all, Eclipse generated the code looks like this:

<?xml version="1.0" encoding="UTF-8"?> <spider 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.sunday.com/xml/ns/javaee  		http://java.lord's day.com/xml/ns/javaee/web-app_2_5.xsd"  	id="WebApp_ID" version="ii.5">   <brandish-name>UploadServletApp</display-name>    <servlet>     <description></description>     <display-name>UploadServlet</brandish-name>     <servlet-proper name>UploadServlet</servlet-name>     <servlet-class>internet.codejava.upload.UploadServlet</servlet-course>   </servlet>      <servlet-mapping>     <servlet-name>UploadServlet</servlet-name>     <url-blueprint>/UploadServlet</url-blueprint>   </servlet-mapping> </web-app>

ix. Testing the awarding

So far nosotros take done the coding function. It'south time to take a test to verify the application. Make sure Tomcat is started, open a new browser window and type the following URL into the address bar:

http://localhost:8080/UploadServletApp/upload.jsp

The upload form is displayed every bit follows:

upload form

Click Scan button and select any file on your computer, then striking Upload push. A message folio is displayed to indicate the upload has been successful:

upload success message

To bank check if the file is saved successfully to a desired location, verify the file is present within upload directory which is created under UploadServletApp directory on the server. In case of this tutorial, since the server is running within Eclipse, the file is saved under this location:

WORKSPACE\.metadata\.plugins\

org.eclipse.wst.server.core\

tmp0\wtpwebapps\UploadServletApp\upload

If you deployed the application on Tomcat outside Eclipse, the file would exist stored under:

c:\Programme Files\Apache Software Foundation\Tomcat 6.0\webapps\UploadServletApp\upload

Related File Upload Tutorials:

  • Java File Upload Case with Servlet 3.0 API
  • Spring MVC File Upload Tutorial with Eclipse IDE
  • Upload file with Struts
  • Upload files to database (Servlet + JSP + MySQL)
  • Upload Files to Database with Jump MVC and Hibernate

Other Coffee Servlet Tutorials:

  • Java Servlet Quick Start for beginners (XML)
  • Java Servlet for beginners (annotations)
  • Handling HTML class data with Java Servlet
  • Java File Download Servlet Instance

About the Author:

Nam Ha Minh is certified Coffee developer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Coffee since then. Make friend with him on Facebook and lookout man his Java videos yous YouTube.

Add annotate

spannproce1950.blogspot.com

Source: https://www.codejava.net/java-ee/servlet/eclipse-file-upload-servlet-with-apache-common-file-upload

0 Response to "How to Upload Java Project in Eclipse"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel