Servlet and JSP development with Eclipse WTP
Table of Contents
Eclipse WTP provides tools for developing standard Java web applications and Java EE applications. Typical web artifacts in a Java environment are HTML pages, XML files, webservices, servlets and JSPs. Eclipse WTP simplifies the creation these web artifacts and provides runtime environments in which these artifacts can be deployed, started and debugged.
In Eclipse WTP you create Dynamic Web Projects. These projects provide the necessary functionality to run, debug and deploy Java web applications. If you are completely new to Java web development you may want to read Introduction to Java Webdevelopment .
Eclipse WTP supports all mayor webcontainers, e.g. Jetty and Apache Tomcat as well as the mayor Java EE application server. This tutorial uses Apache Tomcat as a webcontainer.
Apache Tomcat Tutorial for instructions how to install Apache Tomcat.
After the installation test if Tomcat in correctly installed by opening a browser to http://localhost:8080/. This should open a information page of Tomcat.
Afterwards stop Tomcat. Eclipse WTP needs to start Tomcat itself for its deployments.
In case you have downloaded an Eclipse version for Java development, you can update it via theEclipse Update Manager . Install all packages from the category "Web, XML, Java EE Development and OSGi Enterprise Development" except "PHP Development" and the "RAP" Tooling.
For an introduction in the Eclipse IDE please see the Eclipse IDE Tutorial .
To configure Eclipse WTP select from the menu Add button.
→ → → . Press theSelect your version of Tomcat.
To compile the JSP into servlets you need to use the JDK. You can check your setup by clicking on the
button.Press Finish and then OK. You are now ready to use Tomcat with WTP.
We will create a Servlet which works as a webpage counter. This servlet keeps track of the number of visitors of a webpage. The servlet will persists the number of visitors in a text file. Create a newDynamic Web Project called de.vogella.wtp.filecounter by selecting → → → → .
Press finished. If Eclipse ask you, 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 holds all the JAR files that the Java web application requires.
Create a new package called 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. Enter the following data.
Press finish.
You could also create a servlet without the wizard. The wizard creates a Java class which extends thejavax.servlet.http.HpptServlet
and adds the servlet settings to the web.xml
file.
Enter the following code.
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 // every time 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 will demonstrate the creation and usage of a JaveServer Page. Create a new Dynamic Web Project called de.vogella.wtp.jspsimple and a package with the same name.
Select the folder "WebContent", right-click -> New -> JSP and create the JSP "FirstJSP". 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>JSP with the current date</title> </head> <body> <%java.text.DateFormat df = new java.text.SimpleDateFormat("dd/MM/yyyy"); %> <h1>Current Date: <%= df.format(new java.util.Date()) %> </h1> </body> </html>
Start your webapplication. You find your JSP under the URL "http://localhost:8080/de.vogella.wtp.jspsimple/FirstJSP.jsp".
Set the JSP page as the welcome page for your application to have it automatically opened if the application is started. Modify the WebContent/WEB-INF/web.xml
file.
<?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_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>de.vogella.wtp.jspsimple</display-name> <welcome-file-list> <welcome-file>FirstJSP.jsp</welcome-file> </welcome-file-list> </web-app>
This allows to start the JSP via the path ""http://localhost:8080/de.vogella.wtp.jspsimple".
This example will demonstrate the usage of 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" and the package "de.vogella.wtp.jsp"
Create a new servlet called Controller in the de.vogella.wtp.jsp.controller
package.
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 checks which parameters is passed to the servlet and then forward the request to the correct JSP.
In the folder "WebContent" create the new JSP "ShowAll" with the following code.
<%@ 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 "Delete.jsp" 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.
You can now import the War file to your production Tomcat system and test the web application.
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 .