2012年1月26日星期四

Servlet and JSP development with Eclipse WTP

Servlet and JSP development with Eclipse WTP

Lars Vogel

Version 1.5

29.06.2011

Revision History
Revision 0.1 12.12.2007 Lars Vogel
created
Revision 0.3 - 1.5 10.09.2008 - 29.06.2011 Lars Vogel
bug fixing and improvements

Eclipse Web Tool Platform (WTP)

This tutorial describes the development of servlets and JSPs with Eclipse WTP. This tutorial is based on Eclipse 3.7 (Indigo) and Tomcat 6.0 and JDK 1.6.


1. Eclipse Web Tool Platform

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 webcontainer, e.g. Jetty and Apache Tomcat as well as the mayor Java EE application server. This tutorial uses Apache Tomcat as a webcontainer.

2. Tomcat Installation

Download the Apache Tomcat server 6.0.x from the following webpage http://tomcat.apache.org/. On MS Windows you can use the self-explanatory MS installer to install Tomcat. For a Tomcat installation on other platforms, 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 and if you see this page then Tomcat is correctly installed.

After verifying that Tomcat is correctly installed, stop Tomcat. Eclipse WTP is try to start Tomcat itself. If Tomcat is already running Eclipse WTP will not be able to use it for development.

3. Installation of WTP

I assume you have downloaded the Eclipse IDE for Java developers . Use the Eclipse Update Manager to install all packages from the category "Web, XML, Java EE Development and OSGi Enterprise Development" except "PHP Development" and the "RAP" Tooling.

4. WTP Configuration

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

Select your version of Tomcat.

Tip

To compile the JSP into servlets you need to use the JDK. In my case the "Workbench default JRE" is pointing to the JDK. You can check you setup by clicking on "Installed JRE".

Press Finish and then Ok. You are now ready to use Tomcat with WTP.

4.1. Server

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.

5. Servlets

5.1. Project

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.

5.2. Creating Data Access Object

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();   }  }  }    

Tip

This Java class is not a servlet, it is a normal Java class.

5.3. Creating the Servlet

Create a servlet. Right click on the folder Webcontent and select New-> Other. Select Web -> Servlet. Maintain the following data.

Press finish.

Tip

You could also create a servlet without the wizard. The wizard creates a Java class which extends javax.servlet.http.HpptServlet and add the servlet settings to the web.xml description file.

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.

5.4. Run

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!

6. JavaServer Pages (JSPs)

6.1. Create Project

The following will demonstrate the creation and usage of a JaveServer Page . Create the Dynamic Web Project "de.vogella.wtp.jspsimple". and the package "de.vogella.wtp.jspsimple"

6.2. Create the JSP

Select the folder "WebContent", right-mouse 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"%> "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">   "Content-Type" content="text/html; charset=ISO-8859-1"> JSP with the current date   <%java.text.DateFormat df = new java.text.SimpleDateFormat("dd/MM/yyyy"); %>  

Current Date: <%= df.format(new java.util.Date()) %>

6.3. Run it

Start your webapplication. You find your JSP under the URL "http://localhost:8080/de.vogella.wtp.jspsimple/FirstJSP.jsp".

6.4. Adjust web.xml

Set the JSP page as the welcome page for your application. This is optional but make it easier because the JSP is automatically opened if the application is started. Modify the file "WebContent/WEB-INF/web.xml" to the following.

     

没有评论: