Enterprise Java Logo

Getting Started with Servlets

by Dr. Wenjie He

Introduction to Java Servlets

The Java Servlet API allows a software developer to add dynamic content to a Web server using the Java platform. A servlet extends the functionality of a server. Servlets implement the request-response model of communication and provide the foundation of the Java EE technologies.

1. Java Networking Levels

Java has three networking levels. The higher the level, the more abstraction on the networking implementation details.

2. Interface Servlet

Architectually, all servlets must implement the Servlet interface. The methods of interface Servlet are invoked automatically by the servlet container. This interface defines five methods:

3. Servlet Life Cycle

The life cycle of a servlet is controlled by the servlet container. When a request is mapped to a servlet through its URL, the container performs the following steps.

Servlet Case Study

In this section, we study the Duke2 example.

1. Servlet Configuration

The servlets of a web application are configured in the web.xml file. Let us look at the web.xml of Duke2.

Code Listing: Duke2\WEB-INF\web.xml
           
1.	<?xml version="1.0" encoding="UTF-8"?>
2.	<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" 
3.	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
4. 	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
5. 	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
6.
7. 	<display-name>Duke2</display-name>
8.
9.	<servlet>
10.     <display-name>GreetingServlet</display-name>
11.	   <servlet-name>GreetingServlet</servlet-name>
12. 	   <servlet-class>servlets.GreetingServlet</servlet-class>				
13.	</servlet>	
14.  <servlet>
15.	   <display-name>ResponseServlet</display-name>
16.     <servlet-name>ResponseServlet</servlet-name>
17. 	   <servlet-class>servlets.ResponseServlet</servlet-class>
18. 	</servlet>
19. 	<servlet-mapping>
20. 	   <servlet-name>GreetingServlet</servlet-name>
21. 	   <url-pattern>/greeting</url-pattern>
22. 	</servlet-mapping>
23. 	<servlet-mapping>
24. 	   <servlet-name>ResponseServlet</servlet-name>
25. 	   <url-pattern>/response</url-pattern>
26. 	</servlet-mapping>
27.  </web-app>
		

2. Welcome file index.jsp

Code Listing: Duke2\index.jsp
           
1. 	<jsp:forward page="/greeting"/>
	     

3. Servlet Source Code

Code Listing: GreetingServlet.java
  
1.	package servlets;
2.
3.	import java.io.*;
4.	import javax.servlet.*;
5.	import javax.servlet.http.*;
6.
7.	/**
8.	 * This is a simple example of an HTTP Servlet.  It responds to the GET
9.	 * method of the HTTP protocol.
10.	 */
11.	public class GreetingServlet extends HttpServlet {
12.		private static final long serialVersionUID = 6723471178342776147L;
13.
14.	    public void doGet(
15.	        HttpServletRequest request,
16.	        HttpServletResponse response) throws ServletException, IOException {
17.	        response.setContentType("text/html");
18.	        response.setBufferSize(8192);
19.
20.	        PrintWriter out = response.getWriter();
21.
22.	        // then write the data of the response
23.	        out.println("<html>" + "<head><title>Hello</title></head>");
24.
25.	        // then write the data of the response
26.	        out.println(
27.	                "<body  bgcolor=\"#ffffff\">"
28.	                + "<img src=\"duke.waving.gif\" alt=\"Duke waving\">"
29.	                + "<h2>Hello, my name is Duke. What's yours?</h2>"
30.	                + "<form method=\"get\">"
31.	                + "<input type=\"text\" name=\"username\" size=\"25\">"
32.	                + "<p></p>" + "<input type=\"submit\" value=\"Submit\">"
33.	                + "<input type=\"reset\" value=\"Reset\">" + "</form>");
34.
35.	        String username = request.getParameter("username");
36.
37.	        if ((username != null) && (username.length() > 0)) {
38.	            RequestDispatcher dispatcher = getServletContext()
39.	                                               .getRequestDispatcher("/response");
40.
41.	            if (dispatcher != null) {
42.	                dispatcher.include(request, response);
43.	            }
44.	        }
45.	
46.	        out.println("</body></html>");
47.	        out.close();
48.	    }
49.
50.	    public String getServletInfo() {
51.	        return "The Hello servlet says hello.";
52.	    }
53.	}
	     

Code Listing: ResponseServlet.java
  
1. 	package servlets;
2.
3.	import java.io.*;
4.	import javax.servlet.*;
5. 	import javax.servlet.http.*;
6.
7.	/**
8.	 * This is a simple example of an HTTP Servlet.  It responds to the GET
9.	 * method of the HTTP protocol.
10.	 */
11.	public class ResponseServlet extends HttpServlet {
12.	    private static final long serialVersionUID = 6723471178342776147L;
13.
14.	    public void doGet(
15.	        HttpServletRequest request,
16.	        HttpServletResponse response) throws ServletException, IOException {
17.	        PrintWriter out = response.getWriter();
18.
19.	        // then write the data of the response
20.	        String username = request.getParameter("username");
21.
22.	        if ((username != null) && (username.length() > 0)) {
23.	            out.println("<h2>Hello, " + username + "!</h2>");
24.	        }
25.	    }
26.
27.	    public String getServletInfo() {
28.	        return "The Response servlet says hello.";
29.	    }
30.	}
 	    

This example can be easily understood by the explanation of the code GreetingServlet.java above.

==========The End==========