Streamlining Python Development: A Guide to a Modern Project Setup
Servlets
1. Servlets
1
By: Abdalla Mahmoud .
Contents
Servlets .............................................................................................. 1
1. Introduction ................................................................................... 2
2. First Servlet ................................................................................... 2
2.1. Servlet class. ............................................................................ 2
2.2. Deployment Descriptor .............................................................. 3
2.3. Packaging the Web Module ............................................................ 4
3. Analyzing the Request ..................................................................... 4
3.1. Analyzing Request Headers......................................................... 4
3.2. Analyzing Request Parameters .................................................... 4
3.3. Analyzing Agent's Cookies .......................................................... 5
4. Sending the Response ..................................................................... 6
4.1. Sending Response Headers......................................................... 6
4.2. Sending Response Content ......................................................... 6
4.3. Sending Agent Cookies .............................................................. 7
5. Hoax Example - Add Two Numbers.................................................... 8
5.1. HTML Form............................................................................... 8
5.1.1. Packaging Static Resources ................................................... 8
5.2. Process Servlet ......................................................................... 8
5.2.1. Mapping Process Servlet ....................................................... 9
6. Hoax Example Revisited - Separate Controller from View ..................... 9
6.1. Process Servlet ........................................................................ 10
6.2. View Servlet ............................................................................ 10
7. HTTP Sessions............................................................................... 11
7.1. Creating HTTP Session .............................................................. 11
7.2. Sharing Data ........................................................................... 12
1. http://www.abdallamahmoud.com/.
1
2. 1. Introduction
Servlets are web components that generate dynamic content to user agents. Like other
enterprise components, servlets are deployed on and managed by the application server.
Any Java EE compliant application server provides an implementation for HTTP server. JBoss
comes with Apache Tomcat embedded as the HTTP server.
Servlets are java classes that extend HttpServlet. The HttpServlet is a generic prototype for
a typical web component. The Java EE developer extends the class to create custom web
components. The class, by default, provides seven methods that can be overriden to satisfy
every possible HTTP method:
HTTP Methods Methods Provided by the HttpServlet Class.
void doGet(HttpServletRequest req, HttpServletResponse resp)
void doPost(HttpServletRequest req, HttpServletResponse resp)
void doDelete(HttpServletRequest req, HttpServletResponse resp)
void doHead(HttpServletRequest req, HttpServletResponse resp)
void doOptions(HttpServletRequest req, HttpServletResponse resp)
void doPut(HttpServletRequest req, HttpServletResponse resp)
void doTrace(HttpServletRequest req, HttpServletResponse resp)
The role of a servlet is to analyze the request and respond to it.
2. First Servlet
2.1. Servlet class.
The servlet class is a java class that extends the HttpServlet class and overrides one or
more HTTP methods methods in the super class. All servlet classes should be located under
WEB-INF/classes/ in the web module.
2
3. file: WEB-INF/classes/webapp/MyFirstServlet.java
package webapp ;
import javax.servlet.* ;
import javax.servlet.http.* ;
import java.io.*;
public class MyFirstServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse
response) throws IOException, ServletException {
PrintWriter out = response.getWriter() ;
out.println("<html>") ;
out.println("<head>") ;
out.println("<title>First Servlet</title>") ;
out.println("</head>") ;
out.println("<body>") ;
out.println("<h1>My First Servlet</h1>") ;
out.println("Hello world") ;
}
}
2.2. Deployment Descriptor
Every web module is accossiated with a deployment descriptor file that describes the
components of the web application. The configuration file should be located in WEB-INF/
web.xml in the web module.
file: WEB-INF/web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
<servlet-name>MyFirstServlet</servlet-name>
<servlet-class>webapp.MyFirstServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MyFirstServlet</servlet-name>
<url-pattern>/foo</url-pattern>
</servlet-mapping>
3
4. </web-app>
2.3. Packaging the Web Module
Unlike business modules, web modules are packaged into war files (Web ARchive) rather than
jar files (Java ARchive). Same command is used here:
Command Prompt
C:workspace> jar cf foo.war WEB-INF/classes/webapp/*.class WEB-INF/web.xml
3. Analyzing the Request
The web server is responsible for listening to agent connections, read and understand
HTTP request, then encapsulates it structured in an object. The object is then passed to the
servlet's HTTP method's method as an argument to the request parameter. The following
sections show the request object and how it can be used in different contexts.
3.1. Analyzing Request Headers
Request headers can be retrieved using method String getHeader(String name).
file: WEB-INF/classes/webapp/MyFirstServlet.java
package webapp ;
import javax.servlet.* ;
import javax.servlet.http.* ;
import java.io.*;
public class MyFirstServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse
response) throws IOException, ServletException {
String agent = request.getHeader("User-Agent") ;
}
}
3.2. Analyzing Request Parameters
Request parameters can be retrieved using method String getParameter(String name).
file: WEB-INF/classes/webapp/MyFirstServlet.java
4
5. package webapp ;
import javax.servlet.* ;
import javax.servlet.http.* ;
import java.io.*;
public class MyFirstServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse
response) throws IOException, ServletException {
int id = Integer.parseInt(request.getParameter("id")) ;
PrintWriter out = response.getWriter() ;
out.println("You have requested topic with id:" + id) ;
}
}
3.3. Analyzing Agent's Cookies
Agent cookies can be retrieved using method Cookie[] getCookies(). Objects of class
Cookie used to represent an agent's cookie. Cookie's name and value are encapsulated in
methods getName() and getValue() respectively.
file: WEB-INF/classes/webapp/MyFirstServlet.java
package webapp ;
import javax.servlet.* ;
import javax.servlet.http.* ;
import java.io.*;
public class MyFirstServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse
response) throws IOException, ServletException {
Cookie[] cookies = request.getCookies() ;
for(int i = 0 ; i < cookies.length ; i++) {
String cookieName = cookies[i].getName() ;
String cookieValue = cookies[i].getValue() ;
//process the cookie
}
}
5
6. }
4. Sending the Response
The web server is responsible for sending response to agents, then close the connection.
It provides a response object that encapsulates different response data and actions.The
following sections show the response object and how it can be used in different contexts.
4.1. Sending Response Headers
Response headers can be added to the response using the method void addHeader(String
name, String value).
file: WEB-INF/classes/webapp/MyFirstServlet.java
package webapp ;
import javax.servlet.* ;
import javax.servlet.http.* ;
import java.io.*;
public class MyFirstServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse
response) throws IOException, ServletException {
response.addHeader("Content-Type", "text/html");
}
}
4.2. Sending Response Content
Response content can be written to the agent using the response's output stream. It can be
retrieved using the method PrintWriter getWriter().
file: WEB-INF/classes/webapp/MyFirstServlet.java
package webapp ;
import javax.servlet.* ;
import javax.servlet.http.* ;
import java.io.*;
public class MyFirstServlet extends HttpServlet {
6
7. public void doGet(HttpServletRequest request, HttpServletResponse
response) throws IOException, ServletException {
//get a reference to the stream of the output to the agent
PrintWriter out = response.getWriter() ;
//write to the stream >> the output
out.println("<html>") ;
out.println("<head>") ;
out.println("<title>First Servlet</title>") ;
out.println("</head>") ;
out.println("<body>") ;
out.println("<h1>My First Servlet</h1>") ;
out.println("Hello world") ;
out.println("</body>") ;
out.println("</html>") ;
}
}
4.3. Sending Agent Cookies
Cookies can be sent to be added or modified at the agent using the method
addCookie(Cookie cookie). A cookie object should be passed encapsulating the cookie's
data. A cookie object can be instantiated using constructor Cookie(String name, String
value).
file: WEB-INF/classes/webapp/MyFirstServlet.java
package webapp ;
import javax.servlet.* ;
import javax.servlet.http.* ;
import java.io.*;
public class MyFirstServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse
response) throws IOException, ServletException {
response.addCookie(new Cookie("user_id", "125"));
}
}
7
8. 5. Hoax Example - Add Two Numbers
Our target is to develop a web application that allows a user to add two numbers. The
application will consist of the following resources:
• A form page (page.html).
• A servlet that process and display the output (ProcessServlet).
5.1. HTML Form
file: page.html
<html>
<head><title>Add Two Numbers</title></head>
<body>
<form method="POST" action="/process">
Number 1:<input type="textfield" name="num1"/><br/>
Number 2:<input type="textfield" name="num2"/><br/>
<input type="submit" value="Add"/>
</form>
</body>
</html>
5.1.1. Packaging Static Resources
Static resources such as html pages (.html) and images (.jpeg, .png, .gif) are packages in
the root of the web archive, and need not to be mapped in the .
5.2. Process Servlet
file: WEB-INF/classes/webapp/ProcessServlet.java
package webapp ;
import javax.servlet.* ;
import javax.servlet.http.* ;
import java.io.*;
public class ProcessServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse
response) throws IOException, ServletException {
8
9. float num1 = Float.parseFloat(request.getParameter("num1")) ;
float num2 = Float.parseFloat(request.getParameter("num2")) ;
float result = num1 + num2 ;
String message = "Result = " + result ;
PrintWriter out = response.getWriter() ;
out.println("<html>") ;
out.println("<head>") ;
out.println("<title>Result by Process Servlet</title>") ;
out.println("</head>") ;
out.println("<body>") ;
out.println(message) ;
out.println("</body>") ;
out.println("</html>") ;
}
}
5.2.1. Mapping Process Servlet
Add the following mappings in the web.xml file:
file: WEB-INF/web.xml
...
<servlet>
<servlet-name>ProcessServlet</servlet-name>
<servlet-class>webapp.ProcessServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ProcessServlet</servlet-name>
<url-pattern>/process</url-pattern>
</servlet-mapping>
...
6. Hoax Example Revisited - Separate Controller from View
Our target is to redevelop the previous web application so as to consist of the following
resources:
• A form page (page.html).
• A servlet that process and display the output (ProcessServlet).
• Another servlet that display the output (ViewServlet).
9
10. The web application will work in the following scenario: the user requests page.html, fill
the form, post the data. The data is processed by ProvessServlet, which will forward the
request to the ViewServlet to view the data. Although a trivial example, it's the main
concept in separating the controller from the view in web design patterns.
6.1. Process Servlet
file: WEB-INF/classes/webapp/ProcessServlet.java
package webapp ;
import javax.servlet.* ;
import javax.servlet.http.* ;
import java.io.*;
public class ProcessServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse
response) throws IOException, ServletException {
float num1 = Float.parseFloat(request.getParameter("num1")) ;
float num2 = Float.parseFloat(request.getParameter("num2")) ;
float result = num1 + num2 ;
//set attribute to be shared with the delegates
request.setAttribute("result", result) ;
//create a request dispatcher from the request object
RequestDispatcher rd = request.getRequestDispatcher("/view") ;
//forward the request passing request and response objects
rd.forward(request, response) ;
}
}
6.2. View Servlet
file: WEB-INF/classes/webapp/ViewServlet.java
package webapp ;
import javax.servlet.* ;
import javax.servlet.http.* ;
import java.io.*;
public class ViewServlet extends HttpServlet {
10
11. public void doPost(HttpServletRequest request, HttpServletResponse
response) throws IOException, ServletException {
float result = (Float) request.getAttribute("result") ;
String message = "Result = " + result ;
PrintWriter out = response.getWriter() ;
out.println("<html>") ;
out.println("<head>") ;
out.println("<title>Result by Process Servlet</title>") ;
out.println("</head>") ;
out.println("<body>") ;
out.println(message) ;
out.println("</body>") ;
out.println("</html>") ;
}
}
7. HTTP Sessions
As we saw later, HTTP is a stateless protocol. To overcome this in stateful web applications,
session concept should be implemented. In Java EE, session concept is abstracted and
provided via the HttpSession interface. A reference to a session object can obtained using
the method HttpSession getSession() in the request object.
7.1. Creating HTTP Session
file: WEB-INF/classes/webapp/MyFirstServlet.java
package webapp ;
import javax.servlet.* ;
import javax.servlet.http.* ;
import java.io.*;
public class MyFirstServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse
response) throws IOException, ServletException {
HttpSession session = request.getSession() ;
session.setAttribute("user_id", "505") ;
}
11
12. }
7.2. Sharing Data
Data can be shared using the method void setAttribute(String name, Object value).
Any other page can retrieve shared data using the method Object getAttribute().
12