Servlet: Introduction
Dec 28, 2015
Servlet: Introduction
New methods added in HTTPServlet10
HTTPServlet9
GenericServlet8
Servlet Class hierarchy7
Servlet instance6
Servlet Life Cycle5
Servlet interface4
JSDK3
Servlet Request Response Mechanism2
Definition1
Contents
Deploying20
Packaging19
Writing web.xml18
web.xml17
Brief introduction to XML16
Deployment Descriptors15
HTML file with a link to servlet14
Steps to deploy a web application13
A Simple Servlet 12
Request and Response object11
Contents
Getting single parameters30
HttpServletResponse Interface29
ServletResponse Interface28
HttpServletRequest Interface27
ServletRequest26
Request and Response hierarchy25
Execution24
Deployment23
Steps for packaging22
Packaging and deploying the servlet21
Contents
SingleThreadModel Interface34
Servlet variable initialization33
Servlet to get multiple param32
Getting multiple parameters31
Contents
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
Servlet
Database
Client Web Server
Application ServerRequest
Response
If request is for static page return the page as responseElsePass the request to application server
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 getServletConfig()
• public String getServletInfo()
Life cycle methods
Servlet instanceServletInstantiation
New instance created on first request
Initialized Servlet init() is called
Application Server
Request servicing Servlet
service() is called
Destroyed Servlet
destroy() is called
Initialization
Begin service
Destruction
Servlet Life Cycle
First request
Subsequent requests
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.GenericServlet
javax.servlet.http.HttpServlet
javax.servlet.Servlet
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
Servlet A
Request for servlet A
Response
Client
Web Server
Application server
HTTP request packet
HttpServletRequest Object
HttpServletResponse Object
Web Container
HTTP response packet
A Simple Servletimport 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>Greetings 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
<html><head><title>Greet</title></head><body><h1>Simple Example</h1>Click to invoke the servlet<a href=“greet.do”>Greetings</a></body></html>
index.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.
web.xml• 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• Application Lifecycle Listener classes• Filter Definitions and Filter Mappings• Error Pages
• Environment Variable Mappings• Mime type mapping
Our focus in this chapter
Writing web.xml <web-app> <display-name>Greet</display-name> <servlet>
<servlet-name>Greet</servlet-name>
<display-name>simple</display-name>
<servlet-class>GreetingServlet</servlet-class>
</servlet>
Optional. IDE’s use it for listing web application name
Identifier for this servlet in the web appliaction
Fully qualified name for the servlet
<servlet-mapping> <servlet-name>Greet</servlet-name> <url-pattern>
/greet.do</url-pattern> </servlet-mapping>
</web-app>
Append a / for tomcat
URL that is going to used to access this component
specify the identifier for which component url is going to be mapped
<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!
If 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
Web Application 1
Servlets
JSPs/HTML
Java Classes
Deployment Descriptor(web.xml)
Web Application 2
Servlets
JSPs/HTML
Java Classes
Deployment Descriptor(web.xml)
Components forming the web application.
xxx.war
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
Server nameDefault protocol where tomcat runsprotocol
Folder name
According to j2ee specs, war file has to
be created. For tomcat we don’t 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 in the webapps
folder!
Request and Response hierarchy
HttpServletResponse
ServletResponse
HttpServletRequest
ServletRequest
ServletRequest
• BufferedReader getReader()• ServletInputStream getInputStream()
• int getContentLength()• Enumeration getParameterNames()• String getParameter(String name)• String[] getParameterValues(String name)
Example ahead
Allows you to read raw bytes or characters from the stream
HttpServletRequest Interface
• String getMethod()• String getHeader(String name)• Enumeration getHeaderNames()• String getQueryString()• Cookies[] getCookies()• HttpSession getSession()
HTTP protocol specific methods
Later
ServletResponse Interface
• void setContentType(String type)• void setContentLength(int len)• ServletOutputStream getOutputStream()
• PrintWriter getWriter()
Allows us to write into the response 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
In the doGet() method we can get the value entered by the user in the html form using:String booktitle= request.getParameter(“name”);
…<h1>Locate Books</h1><form action=“book.do”><input type=“text” name=“name”><input type=“submit”></form>…
Default is GET
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 parampublic 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 don’t 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 SingleThreadModel {...}
And say goodbye to Scalability