You are on page 1of 52

Servlet: Introduction

Contents
1 2 3 4 5 6 7 8 9 Definition Servlet Request Response Mechanism JSDK Servlet interface Servlet Life Cycle Servlet instance Servlet Class hierarchy GenericServlet HTTPServlet

10 New methods added in HTTPServlet

Contents
11 12 13 14 15 16 17 18 19 20 Request and Response object A Simple Servlet Steps to deploy a web application HTML file with a link to servlet Deployment Descriptors Brief introduction to XML web.xml Writing web.xml Packaging Deploying

Contents
21 22 23 24 25 26 27 28 29 30 Packaging and deploying the servlet Steps for packaging Deployment Execution Request and Response hierarchy ServletRequest HttpServletRequest Interface ServletResponse Interface HttpServletResponse Interface Getting single parameters

Contents
31 32 33 34 Getting multiple parameters Servlet to get multiple param Servlet variable initialization SingleThreadModel Interface

Know
What a servlet is and its lifecycle The Request Response Mechanism Servlet classes HttpServletRequest and HttpServletResponse classes

Be Able To
Write a simple servlet

Definition
A servlet is a server side program written in Java that resides and executes in an application server It enables the delivery of dynamic content

Servlet Request Response Mechanism


If request is for static page return the page as response Else Pass the request to application server
Request Response Application Server

Servlet

Client

Web Server Database

JSDK
Java Servlet Development Kit (JSDK) contains the class library that is required to create servlets and JSP. The 2 packages that are required to create servlets are javax.servlet and javax.servlet.http. A java class is a servlet if it directly or indirectly implements the Servlet interface.

Servlet interface
public void init(ServletConfig config) throws ServletException public void service(ServletRequest req, ServletResponse res) throws ServletException, java.io.IOException public void destroy() public ServletConfig Life cycle methods getServletConfig() public String getServletInfo()

Servlet Life Cycle


First request Servlet
Instantiation

Application Server Servlet instance


Initialization New instance created on first request init() is called

Subsequent requests

Initialized Servlet
Begin service

Request servicing Servlet


Destruction

service() is called

Destroyed Servlet

destroy() is called

Servlet instance
Only one instance of a particular servlet class is created. The same instance is used for all the requests. When the container shuts down, this instance is destroyed.

Servlet instance
The container runs multiple threads on the service() method to process multiple requests. Only a single instance of servlet of each type ensures minimum number of servlet objects created and destroyed on the server
adds to scalability

Servlet Class hierarchy


javax.servlet.Servlet

javax.servlet.GenericServlet

javax.servlet.http.HttpServlet

GenericServlet
GenericServlet class provides basic implementation of the Servlet interface. This is an abstract class. It implements all the methods except service() method.

GenericServlet
Other methods included are:
public void log(String message) public void init() throws ServletException

The implementation of init(ServletConfig config)calls init()method.

HTTPServlet
HTTPServlet inherits from the GenericServlet and provides a HTTP specific implementation of the Servlet interface. The service(ServletRequest req, ServletResponse res) method is implemented.

HTTPServlet
Since this implementation specific to HTTP protocol, there are methods that specific to each HTTP methods like GET, POST, TRACE etc. It is an abstract class and is subclassed to create an HTTP servlet suitable for a Web site.

New methods added in HTTPServlet


protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, java.io.IOException protected void doXXX(HttpServletRequest req, HttpServletResponse res) XXX is GET, POST, TRACE, PUT, DELETE A subclass of HttpServlet must override at least one method, usually one of doGet, doPost, doDelete, doPut, doHead init and destroy to manage resources that are held for the life of the servlet.

Our focus

Request and Response object


Request for servlet A Response Client Web Server HTTP request packet HTTP response packet

Web Container

Servlet A

HttpServletRequest Object

Application server

HttpServletResponse Object

A Simple Servlet
import javax.servlet.http.*; import javax.servlet.*; import java.io.*; public class GreetingServlet extends HttpServlet { String welcomeMsg =Welcome to simple servlet; java.util.Date currDate;
greet.war

public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException { currDate=new java.util.Date(); PrintWriter out = response.getWriter(); response.setContentType("text/html"); out.println("<html><head><title>Greeting s Servlet </title></head>); out.println("<body>+ welcomeMsg+<br>+currDate+ </body></html>"); }}

Steps to deploy a web application


Write servlets. Compile them. Write html and jsp files. Write deployment descriptor web.xml. Package the application Deploy the application

HTML file with a link to servlet


index.html <html><head> <title>Greet</title> </head> <body> <h1>Simple Example</h1> Click to invoke the servlet <a href=greet.do>Greetings</a> </body> </html> We will map the servlet and the url shortly

Deployment Descriptor
Deployment descriptors is an xml file that helps in managing the configuration of an application. This is the file using which an application can communicate with the container and vice versa. For a web application, the deployment descriptor file name is web.xml. The Java Servlet specifies a document type definition for deployment descriptor which is available at
http://java.sun.com/j2ee/dtds/web_app_2_2.dtd

Brief introduction to XML


XML stands for EXtensible Markup Language. XML is a markup language much like HTML. XML was designed to describe data. XML was created to structure, store and to send information. XML is a cross-platform, software and hardware independent tool for transmitting information. XML tags are not predefined. You must define your own tags. One of the uses of XML is to exchange data.

Servlet components that are used in web application along with their fully qualified class names URLs for servlets Welcome file name Initialization parameters if any Session Configuration Our focus in this chapter Application Lifecycle Listener classes Filter Definitions and Filter Mappings Error Pages Environment Variable Mappings Mime type mapping

web.xml

Writing web.xml
<web-app> <display-name>Greet</display-name> Optional. IDEs use it for listing web <servlet>
application name

<servlet-name>Greet</servlet-name> <display-name>simple</display-name> <servlet-class> GreetingServlet</servlet-class> </servlet>


Fully qualified name for the servlet

dentifier for this servlet in the web appliaction

specify the identifier for which component url is going to be mapped

<servlet-mapping> <servlet-name>Greet</servlet-name> <url-pattern> Append a / for tomcat /greet.do</url-pattern> </servlet-mapping>


URL that is going to used to access this component

</web-app> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list>

Optional because index.html is welcome file by default

index.html is not found, container will look for default.jsp.

Packaging
Packaging application means placing the files in the appropriate placeholders (directory).

Packaging
Servlet specification lays out the rules of how enterprise applications should be packaged. This is necessary so that the container (any j2ee container) knows where to find the files (the servlet class files, html class files etc.) Since a web application is composed of many files, the specification also tells us how to archive the files and deploy it as single file application.

Deploying
Deploying means uploading the application on the server. If there is any problem with the packaging, the application will not be uploaded. There are many J2EE IDEs that help in developing and packaging the application.

Deploying
Most of the application servers support hot deployment. Most of the application servers support start and stop of applications that are deployed.

Packaging and deploying the servlet


Components forming the web application.
Web Application 1 Servlets Java Classes Web Application 2 Servlets Java Classes

JSPs/HTML

JSPs/HTML

xxx.war

Deployment Descriptor (web.xml)

Deployment Descriptor (web.xml)

Steps for packaging


Create a folder. Let us name the folder as slide1ex1. Place htmls and jsps in folder Place the index.html inside slide1ex1 Create a folder called WEB-INF. Created! Note the case is important here. Place web.xml inside the folder Placed! Create a folder called classes inside WEB-INF and all the java classes created inside it. Created and placed GreetingServlet.class.

Deployment
As per j2ee specification, a jar file should be created with the extension .war. This war file has to be then deployed depending on the application server. Jar Command to create war path/simple:> jar cvf simple.war *.* For tomcat, just copy the simple folder into the folder called webapps.

Deployment
Start the tomcat server. Type in the following url in the address bar
http://localhost:8080/slide1ex1 /index.html Or simply http://localhost:8080/slide1ex1
Folder name protocol

Default protocol where tomcat run Server name

According to j2ee specs, war file has to be created. For tomcat we dont do so. So, does this mean that tomcat does not strictly follow j2ee specs? Tomcat follows j2ee specs! It just gives you a simple way to deploy your application. Another option to deploy would be to place the war file

Request and Response hierarchy


ServletResponse ServletRequest HttpServletResponse HttpServletRequest

ServletRequest

BufferedReader getReader() ServletInputStreamAllows you to read raw bytes getInputStream() or characters from the stream int getContentLength() Enumeration getParameterNames() String getParameter(String name) String[] getParameterValues(String name)
Example ahead

HttpServletRequest Interface
String getMethod() String getHeader(String name) Enumeration getHeaderNames() String getQueryString() Cookies[] getCookies() Later HttpSession getSession()
HTTP protocol specific method s

ServletResponse Interface
void setContentType(String type) void setContentLength(int len) ServletOutputStream Allows us to write getOutputStream() into the response PrintWriter getWriter() stream
We have seen this !

HttpServletResponse Interface
void addCookies(Cookie c) String addHeader(String name,String value) void sendRedirect(String url) void sendError(int ecode)

Getting single parameters


<h1>Locate Books</h1> <form action=book.do> <input type=text name=name> <input type=submit> Default is GET </form> In the doGet() method we can get the value entered by the user in the html form using: String booktitle= request.getParameter(name);
book.war

Question?
What will happen if your form has a post method, and the servlet that the form calls has only doGet() method?

Getting multiple parameters


<form method="POST" action="display.do"> <p>Select Colors:<br> <input type="checkbox" name="color" value="Red">Red<br> <input type="checkbox" name="color" value="Green"> Green<br> <input type="checkbox" name="color" value="Blue">Blue</p> <p><input type="submit" value="Submit" name="B1"><input type="reset" value="Reset" name="B2"></p> </form>

Servlet to get multiple param


public class Colors extends javax.servlet.http.HttpServlet{ public void doPost( javax.servlet.http.HttpServletRequest req, javax.servlet.http.HttpServletResponse res) throws java.io.IOException, javax.servlet.ServletException{ java.io.PrintWriter out=res.getWriter(); out.println("<html>");

String colors[]=req.getParameterValues("color"); out.println("<body>"); for(int i=0;i<colors.length;i++) out.println("<font color='"+ colors[i]+"'>Hello </font><br>" ); out.println("</body></html>"); } }

greet.war

Question?
What happens if you dont select any of the checkboxes?

Servlet variable initialization


Initialization of servlet variables is generally done in init() method. In the normal class, initialization happens in the constructor. But since the container calls the constructor in this case, having parameterized constructor has no meaning. The initialization values are passed to servlet through DD and are available only from init() method onwards. Therefore, the initialization is done in init() method.
Generally one never writes a constructor for a servlet!!

SingleThreadModel Interface
In the servlet model that we have seen so far, a single servlet processes multiple requests simultaneously. This means that the doGet and doPost methods must be careful to synchronize access to fields and other shared data, since multiple threads may be trying to access the data simultaneously. On the other hand, you can have your servlet implement the SingleThreadModel interface, as below. public class YourServlet extends HttpServlet implements And say goodbye to Scalability SingleThreadModel {...}

You might also like