Free tutorials for Java, Eclipse and Web programming



Follow me on twitter

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!