| Java, Eclipse and Web programming Tutorials |
Version 1.0
Copyright © 2008 - 2009 Lars Vogel
02.11.2009
| Revision History | ||
|---|---|---|
| Revision 0.1 - 0.2 | 12.12.2007 | Lars Vogel / Waldemar Geppart |
| First Version | ||
| Revision 0.3 | 10.09.2008 | Lars Vogel |
| Moved Webservice part to own article | ||
| Revision 0.4 | 13.10.2008 | Lars Vogel |
| Added JSP and MVC example, added authorization chapter | ||
| Revision 0.5 | 12.04.2009 | Lars Vogel |
| Rework, removed DB example | ||
| Revision 0.6 | 18.05.2009 | Lars Vogel |
| Improved wording, general clean-up | ||
| Revision 0.7 | 02.07.2009 | Lars Vogel |
| Update to Eclipse 3.5 | ||
| Revision 0.8 | 03.07.2009 | Lars Vogel |
| Moved Servlet which creates JavaScript to http://www.vogella.de/blog/?p=395 | ||
| Revision 0.9 | 18.07.2009 | Lars Vogel |
| Minor improvements | ||
| Revision 1.0 | 02.11.2009 | Lars Vogel |
| Closing the file counter | ||
Eclipse Web Tool Platform (WTP)
This article describes the development of servlets and JSPs with Eclipse WTP.
It starts by developing servlets which keeps track of the number of visitors of a website, including a servlet which stores this data into a file.
The creation of JavaServerPages and well as the creation of a war file to run the application in a web container is also explained.
This article assume that you have already basic Eclipse knowledge. The following uses the JDK 1.6, Eclipse 3.5 (Galileo) and Tomcat 6.0 for its examples.
Table of Contents
Eclipse WTP provides tools for developing standard Java web applications and Java EE applications. Eclipse WTP simplifies the creation of web artifacts and provides a runtime environment in which these artifacts can be deployed, started and debugged. Typical web artifacts in a Java environment are HTML pages, XML files, webservices, servlets and JSPs.
The following article will focus on the creation of servlets and JSP with Eclipse WTP and how to use the runtime environment of Eclipse to test them.
Eclipse WTP supports all mayor webcontainer, e.g. Jetty and Apache Tomcat as well as the mayor Java EE application server. This tutorial will be based on Apache Tomcat.
The development of webservices with Eclipse WTP is covered in Webservices with Axis2 and the Eclipse Web Tool Platform (WTP) - Tutorial .
The development of JavaServerFaces is covered in JavaServer Faces (JSF) development with Eclipse WTP JSF - Tutorial and JSF with Apache Myfaces Trinidad and Eclipse .
Eclipse uses builders which are responsible for working with the relevant artifacts. Eclipse WTP uses "Dynamic Web Projects". These projects provide the necessary builders to run, debug and deploy a Java web application. Therefore for the development of Java web application you create "Dynamic Web Projects" .
Download the Tomcat server 6.0.x from the following webpage http://tomcat.apache.org/
Installing Tomcat (on windows) is very easy and self explaining as it comes with a standard installer. For an overview of the usage and configuration of Tomcat see Apache Tomcat - Tutorial . For a tomcat installation on other platform please use Google.
After the installation test if Tomcat in correctly installed by opening a browser to http://localhost:8080/.
This should open the Tomcat main page. If it works then Tomcat is correctly installed.
Stop now Tomcat before starting Eclipse. If Tomcat is still running Eclipse WTP will have problems using the installed Tomcat.
Depending on your Eclipse installation you also need to install the WTP tools. Use the update manager to install the all packages from "Web, XML, and Java EE Development" except "PHP Development" and "Eclipse RAP" from the standard Galileo site. Please see Using the Eclipse Update Manager

You have to configure WTP to use the Tomcat installation.
Select Windows -> Preferences -> Server -> Runtime Environments. Press Add.

Select your version of Tomcat.


Press Finish and then Ok. You are now ready to use Tomcat with WTP.
During development you will create your server. You can manager you server via the server view. To see if you data was persisted stop and restart the server. You can do this via the Windows -> Show View -> Servers -> Servers

The following shows where you can start, stop and restart your server.

We will create a servlet which works as a webpage counter. This servlet will keep track of the number of visitors of a webpage. The servlet will persists the number of visitors in a text file.
Create a new dynamic web project called "de.vogella.wtp.filecounter" by selecting File -> New -> Other -> Web -> Dynamic Web Project.


Press finished. If asked if you want to switch to the Java EE Perspective answer yes.
A new project has been created with the standard structure of a Java web application. The WEB-INF/lib directory will later hold all the JAR files that the Java web application requires.
Create a new package "de.vogella.wtp.filecounter.dao" .
Create the Java class which will provide the number of visitors write this value to a file.
package de.vogella.wtp.filecounter.dao;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
public class FileDao {
public int getCount() {
int count = 0;
// Load the file with the counter
FileReader fileReader = null;
BufferedReader bufferedReader = null;
PrintWriter writer = null ;
try {
File f = new File("FileCounter.initial");
if (!f.exists()) {
f.createNewFile();
writer = new PrintWriter(new FileWriter(f));
writer.println(0);
}
if (writer !=null){
writer.close();
}
fileReader = new FileReader(f);
bufferedReader = new BufferedReader(fileReader);
String initial = bufferedReader.readLine();
count = Integer.parseInt(initial);
} catch (Exception ex) {
if (writer !=null){
writer.close();
}
}
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return count;
}
public void save(int count) throws Exception {
FileWriter fileWriter = null;
PrintWriter printWriter = null;
fileWriter = new FileWriter("FileCounter.initial");
printWriter = new PrintWriter(fileWriter);
printWriter.println(count);
// Make sure to close the file
if (printWriter != null) {
printWriter.close();
}
}
}
Create a servlet. Right click on the folder Webcontent and select New-> Other. Select Web -> Servlet. Maintain the following data.

Press finish.
Maintain the following code for the servlet.
package de.vogella.wtp.filecounter.servlets;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import de.vogella.wtp.filecounter.dao.FileDao;
/**
* Servlet implementation class FileCounter
*/
public class FileCounter extends HttpServlet {
private static final long serialVersionUID = 1L;
int count;
private FileDao dao;
public void init() throws ServletException {
dao = new FileDao();
try {
count = dao.getCount();
} catch (Exception e) {
getServletContext().log("An exception occurred in FileCounter", e);
throw new ServletException("An exception occurred in FileCounter"
+ e.getMessage());
}
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// Set a cookie for the user, so that the counter does not increate
// everytime the user press refresh
HttpSession session = request.getSession(true);
// Set the session valid for 5 secs
session.setMaxInactiveInterval(5);
response.setContentType("text/plain");
PrintWriter out = response.getWriter();
if (session.isNew()) {
count++;
}
out.println("This site has been accessed " + count + " times.");
}
public void destroy() {
super.destroy();
try {
dao.save(count);
} catch (Exception e) {
e.printStackTrace();
}
}
}
This code will read the counter from a file on the server and return plain text to the browser. The servlet will increase the counter if the user was 5 seconds inactive.
Select your servlet, right-click on it and select Run As -> Run on Server.
Select your server and include your servlet so that is runs on the server.


Press finish. You should see the Eclipse internal web browser displaying your the count number. If you wait 5 seconds and refresh the number should increase.

Congratulations. You created your first working servlet with Eclipse WTP!
The following demonstrate the usage of JSPs. We will JSPs for the display and a servlet as the controller for a web application. The servlet will dispatch the request to the correct JSP.
Create the Dynamic Web Project "de.vogella.wtp.jsp". Create also the package "de.vogella.wtp.jsp"
Create a new servlet "Controller" in the package "de.vogella.wtp.jsp.controller".
package de.vogella.wtp.jsp.controller;
import java.io.IOException;
import java.util.Map;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class Controller
*/
public class Controller extends HttpServlet {
private static final long serialVersionUID = 1L;
private static String DELETE_JSP = "/Delete.jsp";
private static String EDIT_JSP = "/Edit.jsp";
private static String SHOWALL_JSP = "/ShowAll.jsp";
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String forward="";
// Get a map of the request parameters
@SuppressWarnings("unchecked")
Map parameters = request.getParameterMap();
if (parameters.containsKey("delete")){
forward = DELETE_JSP;
} else if (parameters.containsKey("edit")){
forward = EDIT_JSP;
} else {
forward = SHOWALL_JSP;
}
RequestDispatcher view = request.getRequestDispatcher(forward);
view.forward(request, response);
}
}
This controller will check which parameters has been passed to the servlet and then forward the request to the correct JSP.
Select the folder "WebContent", right-mouse click -> New -> JSP. Call the new JSP "ShowAll". Select the "New JSP File (html)" template.

Create the following coding.
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!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>Show all names</title> </head> <body> <form method="GET" action='Controller' name="showall"> <table> <tr> <td><input type="checkbox" name="id1" /></td> <td>Jim</td> <td>Knopf</td> </tr> <tr> <td><input type="checkbox" name="id2" /></td> <td>Jim</td> <td>Bean</td> </tr> </table> <p><input type="submit" name="delete" value="delete" /> <input type="submit" name="edit" value="edit" /> <input type="reset" value="reset" /></p> </form> </body> </html>
Create the JSP "Delete.jsp".
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!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> Delete successful <form method="GET" action='Controller' name="delete_success"><input type="submit" value="back"></form> </body> </html>
Create the JSP "Edit.jsp".
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!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> <form method="GET" action='Controller' name="edit"> <table> <tr> <td>First name:</td> <td><input type="text" name="firstName"></td> </tr> <tr> <td>Last name:</td> <td><input type="text" name="lastName"></td> </tr> <tr> <td><input type="submit" value="save"> <input type="reset" value="reset"> <input type="submit" value="back"> </td> </tr> </table> </form> </body> </html>
´The following describes how to create a Web Archive (war) from Eclipse.
Right click on the project and select "Export".

Specify the target directory and press finish.

Import now the War file to your production Tomcat system and test the web application.
Thank you for practicing with this tutorial.
Please note that I maintain this website in my private time. If you like the information I'm providing please help me by donating.For questions and discussion around this article please use the www.vogella.de Google Group. Also if you note an error in this article please post the error and if possible the correction to the Group.
I believe the following is a very good guideline for asking questions in general and also for the Google group How To Ask Questions The Smart Way.
http://www.vogella.de/code/codeeclipse.html Source Code of Examples
http://www.ibm.com/developerworks/edu/os-dw-os-eclipse-europa1.html Web development with Eclipse Europa, Part 1: The Java EE for Eclipse
http://www.servlets.com/ Web page about servlets
http://www.windofkeltia.com/j2ee/wtp-tutorial.html Tutorial: Using the Eclipse Web Tools Platform with Apache Tomcat by Russell Bateman