Signup · Login
Stardeveloper.com  
Home · Tutorials · Forums · ASP.NET Newsletter Application · Web Hosting Plans · Faisal Khan's Blog · Contact
Search Stardeveloper.com
Newsletter
Enter your email address to receive full length articles at Stardeveloper:


Article Categories
.NET  .NET
  ASP (16)
  ASP.NET (43)
  ADO (16)
  ADO.NET (11)
  COM (6)
  Web Services (4)
  C# (1)
  VB.NET (3)
  IIS (2)

J2EE  J2EE
  JSP (15)
  Servlets (9)
  Web Services (1)
  EJB (4)
  JDBC (4)
  E-Commerce (1)
  J2ME (1)
  Products (1)
  Applets (1)
  Patterns (1)

Main Category  Other
  Website Maintenance (3)
Log In
UserName Or Email:

Password:

Auto-Login:

Hosted by Securewebs.com
 
Home : J2EE : Servlets : Introduction to Java Servlets, Developing your first Java Servlet
 
Read full length articles at Stardeveloper using Twitter Follow on Twitter Facebook Facebook fan page Email Get Articles via Email RSS Get Articles via RSS Feed

Introduction to Java Servlets, Developing your first Java Servlet

by Faisal Khan.

Overview
In this article we will learn about Java Servlets. We will develop and deploy a simple Java Servlet in the Tomcat Servlet Container. We will also learn about the web.xml (Web Deployment Descriptor) file. After reading this article you'll be able to develop and deploy Java Servlets.

I'll assume here that you know a bit of Java and can understand it's syntax.

What are Java Servlets?
Servlets are snippets of Java programs which run inside a Servlet Container. A Servlet Container is much like a Web Server which handles user requests and generates responses. Servlet Container is different from a Web Server because it can not only serve requests for static content like HTML page, GIF images, etc., it can also contain Java Servlets and JSP pages to generate dynamic response. Servlet Container is responsible for loading and maintaining the lifecycle of the a Java Servlet. Servlet Container can be used standalone or more often used in conjunction with a Web server. Example of a Servlet Container is Tomcat and that of Web Server is Apache.

Servlets are actually simple Java classes which must implement the javax.servlet.Servlet interface. This interface contains a total of five methods. Most of the time you don't need to implement this interface. Why? Because javax.servlet package already provides two classes which implement this interface i.e. GenericServlet and HttpServlet. So all you need to do is to extend one of these classes and override the method(s) you need for your Servlet. GenericServlet is a very simple class which only implements the javax.servlet.Servlet interface and provides only basic functionality. On the other hand, HttpServlet is a more useful class which provides methods to work with the HTTP protocol. So if your Servlet works with HTTP protocol (in most cases this will be the case) then you should extend javax.servlet.http.HttpServlet class to build Servlets and this is what we are going to do in this article.

Servlets once initialized are kept in memory. So every request which the Servlet Container receives, is delegated to the in-memory Java Servlet which then generates the response. This 'kept in memory' feature makes Java Servlets, a fast and efficient method of building Web Applications.

We will be using Tomcat 6.0.14 for this tutorial. Tomcat 6.0 supports latest Servlet specification 2.5. The installation, configuration and deployment of Tomcat 6.0 has alread been discussed in detail in this tutorial: Installing Tomcat 6.0 on Windows, and Developing & Running your first JSP page. Before moving any further, make sure that you have a working copy of Tomcat 6.0 running on your computer, and that you were able to develop and run your first JSP page.

Following is a list of topics we'll cover in this article :

Your first Java Servlet
Create a new text file and save it as 'TestServlet.java' in the "C:\apache-tomcat-6.0.14\webapps\star\WEB-INF\classes\com\stardeveloper\servlets" folder. "C:\apache-tomcat-6.0.14\webapps" is the folder where web applications (not individual files) that we create should be kept, in order for Tomcat to find them. "\star" is the name of our sample web application that we created it in an earlier tutorial (Installing Tomcat 6.0 on Windows, and Developing & Running your first JSP page). "\WEB-INF\classes" is the folder to keep Servlet class files. "\com\stardeveloper\servlets' is the package path to the Servlet class that we will create.

Now, copy and paste the following text into the 'TestServlet.java' file we created earlier:

package com.stardeveloper.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

import javax.servlet.*;
import javax.servlet.http.*;

public class TestServlet extends HttpServlet {

	public void doGet(HttpServletRequest req, HttpServletResponse res) 
		throws IOException, ServletException {

		res.setContentType("text/html");

		PrintWriter out = res.getWriter();

		/* Display some response to the user */

		out.println("<html><head>");
		out.println("<title>TestServlet</title>");
		out.println("\t<style>body { font-family: 'Lucida Grande', " +
			"'Lucida Sans Unicode';font-size: 13px; }</style>");
		out.println("</head>");
		out.println("<body>");
		
		out.println("<p>Current Date/Time: " +
			new Date().toString() + "</p>");
		out.println("</body></html>");

		out.close();
	}
}

Explanation
Our TestServlet is extremely simple. It displays the current date and time on the server to the user.

We overrode just one method of HttpServlet class. doGet() is called when a HTTP GET request is received by the Servlet Container. In this method we set the content type of our response to 'text/html' (informing the client browser that it is an HTML document). Then we get hold of PrintWriter object and using its println() method, we send our own HTML content to the client browser. Once we are finished, we call its close() method.


 ( 1 Remaining ) Next

Comments/Questions ( Threads: 13, Comments: 29 )
    Contains 1 or more replies by the Author of this Article.
    Contains 1 or more replies by Faisal Khan.

  1. Good article
  2. compilation error in Tomcat5.5.17 server
  3. Help,I can't run servlet from Tomcat6.0 ( 1 Reply ) This thread contains 1 reply by the Author of this Article. This thread contains 1 reply by Faisal Khan.
  4. test ( 1 Reply ) This thread contains 1 reply by the Author of this Article. This thread contains 1 reply by Faisal Khan.
  5. Compling & Running Servlets ( 1 Reply ) This thread contains 1 reply by the Author of this Article. This thread contains 1 reply by Faisal Khan.
  6. need help --regarding Servlet compilation and execution ( 1 Reply ) This thread contains 1 reply by the Author of this Article. This thread contains 1 reply by Faisal Khan.
  7. 10 errors when i compile TestServlet.java ( 2 Replies ) This thread contains 1 reply by the Author of this Article. This thread contains 1 reply by Faisal Khan.
  8. The requested resource (/star/servlet/com.stardeveloper.servlets.TestServlet) is not available ( 1 Reply ) This thread contains 1 reply by the Author of this Article. This thread contains 1 reply by Faisal Khan.
  9. HttpServlet Destroy Method ( 1 Reply ) This thread contains 1 reply by the Author of this Article. This thread contains 1 reply by Faisal Khan.
  10. Help, the Testservlet class not running in browser with tomcat 4.1.18 ( 2 Replies ) This thread contains 1 reply by the Author of this Article. This thread contains 1 reply by Faisal Khan.
  11. Help, the Testservlet class not running in browser with tomcat 4.1.18
  12. HTTP Status 404 ( 2 Replies ) This thread contains 1 reply by the Author of this Article. This thread contains 1 reply by Faisal Khan.
  13. the folder to keep Servlet classes ( 1 Reply ) This thread contains 1 reply by the Author of this Article. This thread contains 1 reply by Faisal Khan.
  14. compile TestServlet errors ( 3 Replies ) This thread contains 2 replies by the Author of this Article. This thread contains 2 replies by Faisal Khan.

Post Comments/Questions

In order to post questions/comments, you must be logged-in. If you are not a member yet, then signup, otherwise login. Once you login then come back to this page and you'll see a form right here which will allow you to post comments/questions.

Please note, one of the benefits of signing up is to be notified immediately by email everytime you receive a reply to the thread you have subscribed.

 
© 1999 - 2010 Stardeveloper.com, All Rights Reserved.