Java Servlets
A technical description of Servlet is it is a Java object that is based on Servlet framework and extends the functionality of a web server basically being responsible for creating dynamic contents. A Servlet is mapped to a corresponding URL and its life-cycle is managed by the container. The URL is the address to which a client send HTTP request. Servlet technology is available and running on all major web servers and app servers. Since it is based on Java, it is platform and server independent.
Public class HelloServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<title>Hello World!</title>");
}
...
}
Advantages of Servlet
- No CGI limitations
- Abundant third-party tools and Web servers supporting Servlet
- Access to entire family of Java APIs
- Reliable, better performance and scalability
- Platform and server independent
- Secure
- Most servers allow automatic reloading of Servlet’s by administrative action
JSP (Java Server Pages)
JSP enables separation of business logic from presentation. JSP, Java Server Pages, was introduced as a follow-on technology to the Servlet. Even though the Servlet solves many problems associated with CGI for dynamic contents generation, it has one downside. The downside is that, under Servlet, the presentation, typically HTML pages, has to be generated as part of the servlet Java code, for example, using printf statement.
<html> Hello World! <br> <jsp:useBean id="clock" class="calendar.JspCalendar" /> Today is <ul> <li>Day of month: <%= clock.getDayOfMonth() %> <li>Year: <%= clock.getYear() %> </ul> </html>

Advantages of JSP
- Content and display logic are separated
- Simplify development with JSP, JavaBeans and custom tags
- Supports software reuse through the use of components
- Recompile automatically when changes are made to the source file
- Easier to author web pages
- Platform-independent
When to use Servlet over JSP
Extend the functionality of a Web server such as supporting a new file format. Generate objects that do not contain HTML such as graphs or pie charts. Avoid returning HTML directly from your servlets whenever possible.
In practice, servlet and JSP are used together via MVC (Model, View, Controller) architecture, Servlet handles Controller and JSP handles View.
What does Servlet Do?
Servlets receives client request (mostly in the form of HTTP request), extract some information from the request. Then they do content generation or business logic process (possibly by accessing database, invoking EJBs, etc). Finally, create and send response to client (mostly in the form of HTTP response) or forward the request to another servlet or JSP page.
The most common form of client requests are HTTP GET and HTTP POST requests. In the HTTP GET request, the user entered information is appended to the URL as a query string. One caveat of the HTTP GET request is that only limited amount of data can be sent because of the limited space at the end of the URL. In the HTTP POST request, on the other hand, the user entered information is sent as data. And since it is sent as data, there is no limitation to the amount of data you can send in using HTTP POST.
First Servlet – An Example
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class HelloServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<title>First Servlet</title>");
out.println("<big>Hello Code Camp!</big>");
}
}
So in this simple servlet program, the request comes in in the form of HTTPServetRequest object and response is created in the form of HttpServletResponse object.

Servlet Life Cycle

Example: init() reading Configuration parameters
public void init(ServletConfig config) throws ServletException {
super.init(config);
String driver = getInitParameter("driver");
String fURL = getInitParameter("url");
try {
openDBConnection(driver, fURL);
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e){
e.printStackTrace();
}
}
Setting Init Parameters in web.xml
<web-app> <servlet> <servlet-name>chart</servlet-name> <servlet-class>ChartServlet</servlet-class> <init-param> <param-name>driver</param-name> <param-value> COM.cloudscape.core.RmiJdbcDriver </param-value> </init-param> <init-param> <param-name>url</param-name> <param-value> jdbc:cloudscape:rmi:CloudscapeDB </param-value> </init-param> </servlet> </web-app>
Servlet Life Cycle Methods
service() and doGet(), doPost() are methods which you put your business logic or dynamic contents generation logic. service() method is an abstract method in GenericServlet class which is then implemented in a subclass. And HTTPServlet is a subclass that is already provided for the developers. The service() method implementation of the HTTPServlet class then dispatches the call to doXXX() methods depending on the HTTP request type. As a servlet developer, you want to override the doXXX() methods to implement a desired behavior of your servlet.
- Set (Save) and get (read) attributes to/from Scope objects. Perform some business logic or access database
- Optionally forward the request to other Web components (Servlet or JSP)
- Populate HTTP response message and send it to client
Example: Simple doGet()
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class HelloServlet extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
// Just send back a simple HTTP response
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<title>First Servlet</title>");
out.println("<big>Hello J2EE Programmers! </big>");
}
}
Example: Simple Response
Public class HelloServlet extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
// Fill response headers
response.setContentType("text/html");
// Set buffer size
response.setBufferSize(8192);
// Get an output stream object from the response
PrintWriter out = response.getWriter();
// Write body content to output stream
out.println("<title>First Servlet</title>");
out.println("<big>Hello J2EE Programmers! </big>");
}
}
Four Scope Objects: Accessibility
The four scopes objects are (1) web context scope object, (2) session scope object, (3) request object, and (4) page object.
Each of these four scope objects have difference scope of accessibility. For example, web context scope object has a scope of web application, that is, a web context object is shared by all web components within a single web application. And a session object is shared by web components that share a same session. Request object is shared by web components that handle the same request. And page object is an object used within a JSP page.
- Web context javax.servlet.ServletContext
- Session javax.servlet.http.HttpSession
- Request subtype of javax.servlet.ServletRequest: javax.servlet.http.HttpServletRequest
- Page javax.servlet.jsp.PageContext
Example: Getting Attribute Value from ServletContext
public class CatalogServlet extends HttpServlet {
private BookDB bookDB;
public void init() throws ServletException {
// Get context-wide attribute value from
// ServletContext object
bookDB = (BookDB)getServletContext().
getAttribute("bookDB");
if (bookDB == null) throw new
UnavailableException("Couldn't get database.");
}
}
Example: Getting and Using RequestDispatcher Object
public void doGet (HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
HttpSession session = request.getSession(true);
ResourceBundle messages = (ResourceBundle)session.getAttribute("messages");
// set headers and buffer size before accessing the Writer
response.setContentType("text/html");
response.setBufferSize(8192);
PrintWriter out = response.getWriter();
// then write the response
out.println("<html>" +
"<head><title>" + messages.getString("TitleBookDescription") +
"</title></head>");
// Get the dispatcher; it gets the banner to the user
RequestDispatcher dispatcher =
session.getServletContext().getRequestDispatcher("/banner");
if (dispatcher != null)
dispatcher.include(request, response);
...
HttpSession
We need a mechanism to maintain client state across a series of requests from a same user (or originating from the same browser) over some period of time. HttpSession is the way to maintain states for clients. Used by Servlets to set and get the values of session scope attributes. Via getSession() method of a Request object (HttpServletRequest) we get the HttpSession.
Example: Online shopping cart
Example: HttpSession
public class CashierServlet extends HttpServlet {
public void doGet (HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
// Get the user's session and shopping cart
HttpSession session = request.getSession();
ShoppingCart cart =
(ShoppingCart)session.getAttribute("cart");
...
// Determine the total price of the user's books
double total = cart.getTotal();
Servlet Request
Contains data passed from client to servlet. All servlet requests implement ServletRequest interface which defines methods for accessing:
- Client sent parameters
- Object-valued attributes
- Locales
- Client and server
- Input stream
- Protocol information
- Content type
- If request is made over secure channel (HTTPS)
A Sample FORM using GET
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML> <HEAD> <TITLE>Collecting Three Parameters</TITLE> </HEAD> <BODY BGCOLOR="#FDF5E6"> <H1 ALIGN="CENTER">Please Enter Your Information</H1> <FORM ACTION="/sample/servlet/ThreeParams"> First Name: <INPUT TYPE="TEXT" NAME="param1"><BR> Last Name: <INPUT TYPE="TEXT" NAME="param2"><BR> Class Name: <INPUT TYPE="TEXT" NAME="param3"><BR> <CENTER> <INPUT TYPE="SUBMIT"> </CENTER> </FORM> </BODY> </HTML>

A FORM Based Servlet: Get
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
/** Simple servlet that reads three parameters from the html form */
public class ThreeParams extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Your Information";
out.println("<HTML>" +
"<BODY BGCOLOR=\"#FDF5E6\">\n" +
"<H1 ALIGN=CENTER>" + title + "</H1>\n" +
"<UL>\n" +
" <LI><B>First Name in Response</B>: "
+ request.getParameter("param1") + "\n" +
" <LI><B>Last Name in Response</B>: "
+ request.getParameter("param2") + "\n" +
" <LI><B>NickName in Response</B>: "
+ request.getParameter("param3") + "\n" +
"</UL>\n" +
"</BODY></HTML>");
}
}
A Sample FORM using POST
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML> <HEAD> <TITLE>A Sample FORM using POST</TITLE> </HEAD> <BODY BGCOLOR="#FDF5E6"> <H1 ALIGN="CENTER">A Sample FORM using POST</H1> <FORM ACTION="/sample/servlet/ShowParameters" METHOD="POST"> Item Number: <INPUT TYPE="TEXT" NAME="itemNum"><BR> Quantity: <INPUT TYPE="TEXT" NAME="quantity"><BR> Price Each: <INPUT TYPE="TEXT" NAME="price" VALUE="$"><BR> First Name: <INPUT TYPE="TEXT" NAME="firstName"><BR> <TEXTAREA NAME="address" ROWS=3 COLS=40></TEXTAREA><BR> Credit Card Number: <INPUT TYPE="PASSWORD" NAME="cardNum"><BR> <CENTER> <INPUT TYPE="SUBMIT" VALUE="Submit Order"> </CENTER> </FORM> </BODY> </HTML>

A Form Based Servlet: POST
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ShowParameters extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
...
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
HTTP Servlet Request
It contains data passed from HTTP client to HTTP servlet. The HTTP Servlet request is represented by HTTPServletRequest object which is created by the container and then passed to the servlet as a parameter of doGet() or doPost() methods. HTTPServletRequest type is an extension of ServletRequest Java interface type and provides the additional methods for accessing the information mentioned above, for example, HTTP request URL, HTTP header entries, authentication and user security information, and session information, and so on.
HTTP Request URL: [query string]
http://[host]:[port]/[request path]?[query string]
- A query string can explicitly appear in a web page <a href=”/bookstore1/catalog?Add=101″>Add To Cart</a> String bookId = request.getParameter(“Add”);
- A query string is appended to a URL when a form with a GET HTTP method is submitted http://localhost/hello1/greeting?username=Helary+Clinton String userName=request.getParameter(“username”)
Servlet Response
Servlet response contains data that is supplied by the servlet or container. All servlet responses implement ServletResponse Java interface, which contains methods for retrieving an output stream, indicating content type, indicating whether to buffer output or not, for setting localization information. Now HttpServletResponse is Java interface that extends ServletResponse. The HttpServletResponse interface contains methods for setting HTTP response status code and cookies.

So how does HTTP response status code get used? First, it could be used as an instruction to the browser to forward the client to another page. Second it could be used to indicate resource is missing. Third, it could be used to instruct the browser to use cached copy of data.
Methods for Setting HTTP Response Status Codes
- public void setStatus(int statusCode)
- Status codes are defined in HttpServletResponse
- Status codes are numeric fall into five general categories:
- 100-199 Informational
- 200-299 Successful
- 300-399 Redirection
- 400-499 Incomplete
- 500-599 Server Error
- Default status code is 200 (OK)
Example of HTTP Response Status
HTTP/ 1.1 200 OK Content-Type: text/ html <! DOCTYPE ...> <HTML ... </ HTML>
Why HTTP Response Headers?
- Give forwarding location
- Specify cookies
- Supply the page modification date
- Instruct the browser to reload the page after a designated interval
- Give the file size so that persistent HTTP connections can be used
- Designate the type of document being generated
Refresh Sample Code
public class DateRefresh extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/plain");
PrintWriter out = res.getWriter();
res.setHeader("Refresh", "5");
out.println(new Date().toString());
}
}
Example: Setting Error Pages in web.xml
<error-page> <exception-type> exception.BookNotFoundException </exception-type> <location>/errorpage1.html</location> </error-page> <error-page> <exception-type> exception.BooksNotFoundException </exception-type> <location>/errorpage2.html</location> </error-page> <error-page> <exception-type>exception.OrderException</exception-type> <location>/errorpage3.html</location> </error-page>
Related Posts
Popular Posts (last 30 days)
- Attendance Management System 1500 view(s)
- Advanced Java Tutorial (For Intermediate) 763 view(s)
- JAVA Graphical User Interface (GUI) 726 view(s)
- Graph Implementation in C++ 536 view(s)
- File Handling using Input-Output Streams in Java 477 view(s)
- Linked lists in C++ 461 view(s)
- Sockets and Network Programming in Java 380 view(s)
- Applications of Stack in data structures 371 view(s)
- UDP Datagram Sockets in Java 363 view(s)
- Circular Linked Lists 337 view(s)







