What is a Java Servlets?
•AJavaservletisaserver-sideprogramthatiscalled
bytheuserinterfaceoranotherJ2EEcomponentand
containsthebusinesslogictoprocessarequest.
•AJavaServerPageisalsoaserver-sideprogramthat
performspracticallythesamedutiesasaJavaservlet
usingadifferenttechnique.
•BothaJavaservletandaJavaServerPagecallother
componentsthathandleprocessingdetails.
Why Use Servlets?
•Portability
Write once, serve everywhere
•Power
Can take advantage of all Java APIs
•Elegance
Simplicity due to abstraction
•Efficiency & Endurance
Highly scalable
Servlets Architecture
•The HttpServletRequestobject
Contains the request data from the client
HTTP request headers
Form data and query parameters
Other client data (cookies, path, etc.)
•The HttpServletResponseobject
Encapsulates data sent back to client
HTTP response headers (content type, cookies,
etc.)
Response body (as OutputStream)
Servlets Architecture
•The HTTP GET method is used when:
The processing of the request does not change the state of
the server
The amount of form data is small
You want to allow the request to be bookmarked
•The HTTP POST method is used when:
The processing of the request changes the state of the
server, e.g. storing data in a DB
The amount of form data is large
The contents of the data should not be visible in the URL
(for example, passwords)
Java Servlets
Life Cycle
Servlets Life-Cycle
•Youcanprovideanimplementationofthesemethods
inHttpServletdescendentclassestomanipulatethe
servletinstanceandtheresourcesitdependson
•The Web container
manages the life cycle
of servlet instances
•The life-cycle methods
should not be called by
your code
init()
...()
service()
doGet()
doPost()
doDelete()
destroy()
doPut()
New Destroyed
Running
The destroy() Method
•Called by the Web container when the servlet
instance is being eliminated
•The Servlet specification guarantees that all
requests will be completely processed before this
method is called
•Override the destroy method when:
You need to release any servlet-specific
resources that you had opened in the init()
method
You need to persist the state of the servlet
publicvoiddestroy()
Servlets API
The javax.servlet Package
Servlets API
•Two packages contain the classes and interfaces that
are required to build the servlets .
•These are javax.servletand javax.servlet.http. They
constitute the core of the Servlet API.
•Keep in mind that these packages are not part of the
Java core packages.
•Therefore, they are not included with Java SE. Instead,
they are provided by Tomcat.
•They are also provided by Java EE.
The javax.servletPackage
•Thiscontainsanumberofinterfacesandclassesthatestablish
theframeworkinwhichservletsoperate
The Servlet Interface
•All servlets must implement the Servlet interface.
•It declares the init( ), service( ), and destroy( ) methods that
are called by the server during the life cycle of a servlet.
•A method is also provided that allows a servlet to obtain any
initialization parameters.
•These methods are invoked by the server.
•The getServletConfig( ) method is called by the servlet to
obtain initialization parameters.
•A servlet developer overrides the getServletInfo( ) method
to provide a string with useful information (for example, the
version number). This method is also invoked by the server.
The Methods Defined by Servlet
The ServletConfigInterface
•TheServletConfiginterfaceallowsaservlettoobtain
configurationdatawhenitisloaded.
•Themethodsdeclaredbythisinterfacearesummarizedhere:
The ServletContextInterface
•TheServletContextinterfaceenablesservletstoobtain
informationabouttheirenvironment.
The ServletRequestInterface
•TheServletRequestinterfaceenablesaservlettoobtain
informationaboutaclientrequest.
The ServletRequestInterface
The ServletResponseInterface
•TheServletResponseinterfaceenablesaservlettoformulatea
responseforaclient.
Reading Servlet
Parameters
Examples
Processing Parameters –Hello
Servlet
•We want to create a servlet that takes an user name
as a parameter and says "Hello, <user_name>"
•We need HTML form with a text field
•The servlet can later retrieve the value entered in the
form field
<form method="GET or POST" action="the servlet">
<input type="text" name="user_name">
</form>
String name =request.getParameter("user_name");
Hello Servlet –Example
<html><body>
<form method="GET" action="HelloServlet">
Please enter your name:
<input type="text" name="user_name">
<input type="submit" value="OK">
</form>
</body></html>
HelloForm.html
The javax.servlet.httpPackage
•Theclassesandinterfacesdefinedinjavax.servlet,suchas
ServletRequest,ServletResponse,andGenericServlet,will
illustratethebasicfunctionalityofservlets.
•However,whenworkingwithHTTP,youwillnormallyusethe
interfacesandclassesinjavax.servlet.http.
Servlets API
•The most important servlet functionality:
RetrievetheHTMLformparametersfromthe
request(bothGETandPOSTparameters)
Retrieve a servlet initialization parameter
Retrieve HTTP request header information
HttpServletRequest.getParameter(String)
ServletConfig.getInitParameter()
HttpServletRequest.getHeader(String)
Servlets API
Set an HTTP response header/content type
Acquire a text stream for the response
Acquire a binary stream for the response
Redirect an HTTP request to another URL
HttpServletResponse.setHeader(<name>, <value>) /
HttpServletResponse.setContentType(String)
HttpServletResponse.getWriter()
HttpServletResponse.getOutputStream()
HttpServletResponse.sendRedirect()
The Cookie Class
•TheCookieclassencapsulatesacookie.Acookieisstored
onaclientandcontainsstateinformation.Cookiesare
valuablefortrackinguseractivities.
•Aservletcanwriteacookietoauser’smachineviathe
addCookie()methodoftheHttpServletResponseinterface.
Thedataforthatcookieisthenincludedintheheaderofthe
HTTPresponsethatissenttothebrowser.
•Thenamesandvaluesofcookiesarestoredontheuser’s
machine.
1.Thenameofthecookie
2.Thevalueofthecookie
3.Theexpirationdateofthecookie
4.Thedomainandpathofthecookie
Handling HTTP
Requests and
Responses
The javax.servlet.http Package
What happens to a JSP page when it is
translated into Servlet
JSP Tags (Elements)
•EXPRESSIONenclosedin<%=and%>markers
AexpressionisusedtoinserttheresultofaJava
expressiondirectlyintotheoutput.
•SCRIPTLETenclosedin<%and%>markers:
AscriptletcancontainanynumberofJAVAlanguage
statements,variableormethoddeclarations,or
expressionsthatarevalidinthepagescripting
language.
<%
String message = “Hello World”;
out.println (message);
%>
The time is : <%= new java.util.Date() %>
JSP Tags (Elements)
•DIRECTIVES syntax -<%@ directive attribute = "value" %>
A JSP directive gives special information about the JSP page to the
JSP Engine.
There are three main types of directive :-
page : processing information for this page
include : files to be included
taglib : tag library to be used in the page