Servlet
Servlet
Servlets are programs that run on a web or
application server
It act as a middle layer between a request coming
from a web browser or other HTTP client and
databases or applications on the HTTP server.
Role of Middleware
Read the explicit data sent by the client.
Read the implicit HTTP request data sent by the
browser.
Generate the results.
Send the explicit data to the client.
Send the implicit HTTP response data.
Simple Servlet
import [Link].*;
import [Link].*;
import [Link].*;
public class HelloServlet extends HttpServlet
{ public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException,IOException
{
PrintWriter out=[Link]();
[Link](“Hello World”);
}
}
[Link]
<web-app>
<display-name>HelloWorld</display-name>
<servlet>
<servlet-name>HelloServlet</servlet-name>
<servlet-class>HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloServlet</servlet-name>
<url-pattern>/HelloServlet</url-pattern>
</servlet-mapping>
</web-app>
Compiling and Invoking Servlet
Set PATH to jdk –bin , jre-bin,tomcat-bin
Set CLASSPATH to jdk-lib,jre-lib, tomcat\lib\[Link]
Set JAVA_HOME to jdk path
Set JRE_HOME to jre path
Set CATALINA_HOME to tomcat directory
Put your servlet classes in proper location
installdir/webapps/ROOT/Web-INF/classes
Invoke your servlets
[Link]
Why Servlets?
Are loaded into memory once and run from memory thereafter.
Are spawned as a thread, not as a process.
Are a powerful object-oriented abstraction of HTTP.
Are portable across multiple Web servers and platforms.
Are Simple to desing and implement.
Are tightly integrated with the Web server.
Service client requests efficiently.
Run within the secure and reliable scope of a JVM.
Obey the rules of a standard servlet API.
Return vanilla HTML to the requesting Browser.
Are robust, scalable, secure CGI replacement.
Provide direct Database Access using native and ODBC based Db drivers.
Being on the serverside provides code protection.
Are supported by several Web servers.
What Servlets can do???
It can be used as a plug-ins.
It can be used to process data POSTed over HTTP(S) using an HTML
form and apply appropriate business logic.
It can handle multiple requests concurrently and these requests can
be synchronized to support systems allowing collaboration between
people.
Servlets can forward requests to other Servers and Servlets.
Servlets can maintain and track session .
Servlets can pass data between themselves.
Servlets can be used to serve as the HTTP speaking middle tier
between any kind of client and large enterprise services being made
available vis EJB’s.
Servlet vs CGI
CGI Servlet
CGI are not as much powerful as Servlets are more efficient, easier to use,
Servlets more powerful ,more portable and cheaper
New process is started for each request Request is handled by thread
For n simultaneous requests , CGI N thread a but only a single copy of the
program is loaded into memory n times Servlet class
CGI programs cannot talk directly Servlet can talk directly to the Web Server
CGI cannot track sessions Servlet can manage sessions
CGI are not supported directly on every Servlets are supported directly on almost
web server every Web server
Servlet API
It provides the interfaces and classes that support
servlets.
These interfaces an classes are grouped into two
packages
The [Link] package provides basic interfaces
The [Link] these interfaces, provides classes
and interfaces derived to provides specific means for
servicing HTTP requests.
Servlet
Packages [Link] [Link]
Servlet HttpServletRequest
ServletRequest HttpServletResponse
ServletResponse HttpSession
Interfaces
ServletConfig HttpSessionBindingListener
ServletContext HttpSessionContext
SingleThreadModel
GenericServlet Cookie
Classes ServletInputStream HttpServlet
ServletOutputStream HttpSessionBindingEvent
HttpUtils
GenericServlet
Generic Servlet class defines a generic and protocol independent.
It implements Servlet and ServletConfig.
ServletConfig is an interface that defines four methods
getInitParameter
getInitParameterNames
getServletContext
getServletName
for passing information to a servlet during initialization.
All methods in Servlet and ServletConfig are implemented in GenericServlet
except service.
Therefore, GenericServlet is an abstract class.
HttpServlet
The HttpServlet class defines a servlet for the HTTP protocol.
It extends GenericServlet and implements the service method.
The service method is implemented as a dispatcher of HTTP requests.
The HTTP requests are processed in the following methods:
doGet()
doPost()
doDelete()
doPut()
doOptions()
doTrace()
Methods Required for Creating a Functional HttpServlet
Method Description
service() The server calls this method whenever a Servlet request is [Link]
HTTP Servlets’s this method is usually not overridden.
doGet() Invoked to respond to a GET request.
doHead() Invoked to reponse to an HTTP HEAD request.
doPost() Invoked to respond to a POST request
doPut() Invoked to respond to a PUT request. Such a request is normally used to
send a file to the server.
doDelete() Invoked to respond to a DELETE request. Such a request is normally used to
delete a file on the server from the server.
doOptions() Invoked to respond to an OPTIONS request. This returns the information
about the server, such as which HTTP methods the server supports.
doTrace() Invoked to respond to a TRACE request. Such a request is normally used for
debugging. This method returns an HTML page that contains appropriate
trace information.
Common Servlet Methods
Method Description
init() Called once when the servlet is loaded.
Used to initialize resources to be used by a servlet when
requests are received.
destroy() Called immediately before the servlet is unloaded.
Override this method in order to free up any resources being
used by the servlet.
getServletInfo() Implement this method so that a Servlet can identify itself
when queried by the servlet engine.
service() Invoked each time when the server receives the request for the
servlet.
The server spawns a new thread and invokes service method.
Servlet Interface
The Servlet Interface defines the methods that all servlets must implement.
/*** Invoked for every servlet constructed */
public void init(ServletConfig servcf) throws ServletException
/*** Invoked to respond to incoming request */
public void service(ServletRequest serreq,ServletResponse serres)throws ServletException, IOException
/*** Invoked to release resource by the servlet **/
public void destroy()
/** Return information about the servlet */
public String getServletInfo()
/*** Return configuration objects of the servlet */
public ServletConfig getServletConfig()
ServletConfig Interface
It is an interface
It is used to provide initialization information to the servlet.
There is one servletconfig for one servlet.
It has following Methods:
public [Link] getServletName()
public ServletContext getServletContext()
public Enumeration getInitParameterNames()
public String getInitParameter(String name)
Servlet get its Initilialization Information from [Link]
Inside the <servlet> tag for the given servlet in [Link] :
Add <init-param> tag
For each <init-param> tag
there is one <param-name> and <param-value>
[Link]
<servlet>
<init-param>
<param-name>myName</param-name>
<param-value>myValue</param-value>
</init-param>
</servlet>
String name;
public void init(ServletConfig config) throws ServletExc
eption {
name = [Link](“myName");
}
getInitParameterNames()
This method returns the all parameter names from the [Link]
It returns the values in the form of Enumeration.
These names can be retrieved using hasNext() method.
Using getParameter() method all values can also be retrieved.
ServletConfig sc = getServletConfig();
Enumeration<String> en = [Link]();
while ([Link]())
{
String st = [Link]();
[Link]("<br>" + st + "------" + [Link](st));
}
ServletContext
It is an interface.
It is used to communicate with ServletContainer.
Due to this there is oly one servletContext for the whole project/application.
It is used to
set the attribues for application level
and get the initialization parameter values from [Link]
It is used to
get dispatch requests
and write to a log file
Like servletconfig paramter there is servlet context parameter .
This is called as contextParameter.
These parameters are defined in the [Link].
It can send configuration information to all servlets in a web application
[Link]
<context-param>
<param-name>myName</param-name>
<param-value>myValue</param-value>
</context-param
ServletContext methods
String getInitParameter(String name)
Enumeration getInitParameterNames()
Object getAttribute(String name)
Enumeration getAttributeNames()
void setAttribute(String name, Object object)
void removeAttribute(String name)
Servlet Life Cycle
A servlet life cycle can be defined as the entire process from its creation till
the destruction.
The servlet is initialized by calling the init () method.
The servlet calls service() method to process a client's request.
The servlet is terminated by calling the destroy() method.
Finally, servlet is garbage collected by the garbage collector of the JVM.
init() method
The init method is designed to be called only once.
It is called when the servlet is first created, and not called again for each user
request.
It is used for one-time initializations.
The servlet is normally created when a user first invokes a URL corresponding
to the servlet, but you can also specify that the servlet be loaded when the
server is first started.
When a user invokes a servlet, a single instance of each servlet gets created,
with each user request resulting in a new thread that is handed off to doGet
or doPost as appropriate.
The init() method simply creates or loads some data that will be used
throughout the life of the servlet.
service() method
The service() method is the main method to perform the actual task.
The servlet container (i.e. web server) calls the service() method to handle requests
coming from the client( browsers) and to write the formatted response back to the
client.
Each time the server receives a request for a servlet, the server spawns a new thread
and calls service.
The service() method checks the HTTP request type (GET, POST, PUT, DELETE, etc.) and
calls doGet, doPost, doPut, doDelete, etc. methods as appropriate.
The service () method is called by the container and service method invokes doGe,
doPost, doPut, doDelete, etc. methods as appropriate.
So you have nothing to do with service() method but you override either doGet() or
doPost() depending on what type of request you receive from the client.
doGet() Method
A GET request results from a normal request for a URL or from an HTML form that has no METHOD
specified and it should be handled by doGet() method.
public void doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException
{
// Servlet code
}
doPost() Method
A POST request results from an HTML form that specifically lists POST as the METHOD and it should be
handled by doPost() method.
public void doPost(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException
{
// Servlet code
}
destroy() method
The destroy() method is called only once at the end of the life cycle of a
servlet.
This method gives your servlet a chance to close database connections, halt
background threads, write cookie lists or hit counts to disk, and perform other
such clean up activities.
public void destroy() {
// Finalization code...
}
Reading Single Values
getParameter(name) method
Returns URL-decoded value of first occurrence of name
in query string
Works identically for GET and POST requests
Returns null if no such parameter is in query data
Example: [Link](“txtname”);
It will return txtname value in String format
Reading Multiple Values
getParameterValues()
Returns an array of the URL-decoded values of all occurrences of
name in query string
Returns a one-element array if param not repeated
Returns null if no such parameter is in query
Example:
String[] paramValues = [Link](paramName);
Reading All Parameter Names
getParameterNames() or getParameterMap()
Returns Enumeration or Map of request params
Usually reserved for debugging
Examples:
Enumeration paramNames=[Link]();
while([Link]())
{
String paramName=(String)[Link]();
[Link]([Link](paramName));
}
Reading Request Headers
(Methods in HttpServletRequest)
getCookies: Returns the contents of cookie header, parsed and stored in
an array of Cookie objects.
getAuthType and getRemoteUser : Breaks the authorization header into its
component pieces.
getContentLength : Returns the value of the content length header (in int)
getContentType : Returns the value of the content type header.
getDateHeader and getIntHeader : Read the specified headers and then
convert them to Date and int values respectively.
getHeaderNames : Returns an Enumeration of all header names.
getHeader : Returns the values of all occurrences of the header.
getMethod : Returns the main request method.
getRequestURI : Returns the part of the URL that comes after the
host and port but before form data.
getQueryString : Returns the form data.
getProtocol : Returns the protocol
HTTP 1.1 Request Headers
Accept : Specifies the MIME types that the browser or other clients can
handle.A Servlet that can return a resource in more than one format
can examine the Accept header to decide which format to use.
Accept-Charset : It indicates the character sets the browser can use.
Accept-Encoding : Designates the types of encoding that the client
knows how to handle.
Accept-Language : Specifies the client’s preferred languages in case
the servlet can produce the results in more than one language.
Authorization : Used by the clients to identify themselves when
accessing password-protected Web pages.
Connection : Indicates whether the client can handle persistent
HTTP connections.
Content-Length : Applicable only to POST requests and gives the
size of the POST data in bytes.
Cookie : Returns cookies to servers that previously sent them to
the browser.
Host : Indicates the host and port as given in the original URL.
If-Modified-Since : Indicates that the client wants the page only if
it has been changed after the specified table.
If-Unmodified-Since : Specifies that the operation should succeed
only if the document is older than the specified date.
Referer : Indicates the URL of the referring web pages.
User-Agent : Identifies the browser or other client making the
request and can be used to different content to different types of
browsers
Changing the Page according to how the
user got there
The Referer header designates the location of the page
users were on when they clicked a link to get to the
current page.
If users simply type the address of a page, the browser
sends no Referer at all and [Link](“Referer”)
returns null.
Accessing the Standard CGI variables
AUTH_TYPE : getAuthType()
CONTENT_LENGTH : getContentLength()
CONTENT_TYPE : getContentType()
DOCUMENT_ROOT : getServletContext()
PATH_INFO : getPathInfo()
PATH_TRANSLATED : getPathTranslated()
QUERY_STRING : getQueryString()
REMOTE_ADDR : getRemoteAddr()
REMOTE_HOST : getRemoteHost()
REMOTE_USER : getRemoteUser()
REQUEST_METHOD : getMethod()
SCRIPT_NAME : getServletPath()
SERVER_NAME : getServerName()
SERVER_PORT : getServerPort()
SERVER_PROTOCOL : getProtocol()
Understand HyperText Transfer Protocol (HTTP)
1) Specify Get / Post
2) Request header
3) Form Data (Parameters) request
Web Server
Web Client
1) Status code
response 2) Response header
3) Content-Type
4) HTML pages / Other files
39
Setting Status Codes
[Link](intstatusCode)
[Link](int code, String message)
[Link](String url)
40
SC general categories
100-199
Indicate the client should respond with some other
actions.
200-299
Indicate the request was successful.
300-399
Usually include a location header
400-499
Indicate an error by the client.
500-599 41
Indicate an error by the server.
Common HTTP 1.1 Status Codes
100(Continue)
Client is asking if it can send an attached document in follow-up
request.
200 (OK)
Everything is fine; document follows
Default for servlets
202(Accepted)
Tells the client that the request is being acted upon but processing
is not yet complete.
204 (No Content)
Browser should keep displaying previous document, no new document is
available. 42
205(Reset Content)
Thereis no document but the browser should reset the
document view.
301 (Moved Permanently)
Requested document permanently moved elsewhere (indicated in
Location header)
Browsers go to new location automatically
302 (Found)
Requested document temporarily moved elsewhere (indicated in
Location header)
Browsers go to new location automatically
Servlets should use sendRedirect, not setStatus, when setting this
header.
Common HTTP 1.1 Status Codes (Continued)
303(See Other)
Ifthe original request was POST, the new document should be retrieved with
GET.
400(Bad Request)
Bad syntax in the client request.
401 (Unauthorized)
Browser tried to access password protected page without proper
Authorization header.
404 (Not Found)
SC_NOT_FOUND
No such page.
Servlets should use sendError to set this header
44
403(Forbidden)
Bad file or directory permission on the server.
405(Method not Allowed)
Signifies that the request method was not allowed for this
particular resource.
415 (Unsupported Media)
Request had an attached document of a type the server doesn’t know
how to handle.
500 (Internal Server Error)
Server is confused for improper formatted headers.
501 (Not Implemented)
Notifies the client that the server does not support the functionality
to fulfill the request.
503(Service Unavailable)
Signifies the server cannot respond because of maintainance
or overloading.
505 (HTTP Version not supported)
The server doesn’t support the version of HTTP named in the request
line.
Generating the Server Response:
HTTP Response Headers
Purposes
Give forwarding location
Specify cookies
Supply the page modification date
Instruct the browser to reload the page after a designated interval
Give the document size so that persistent HTTP connections can be
used
Designate the type of document being generated
Default HTTP Error Page
Deployment Descriptor
<?xml version=“1.0” encoding=“UTF-8:?>
<<!DOCTYPE web-app PUBLIC ‘-//Sun Microsystems, Inc.//DTD Web Application
2.3//EN’
‘[Link]
<web-app>
<display-name>A Simple Application</display-name>
<servlet>
<servlet-name>Verify data</servlet-name>
<servlet-class>VerifyData</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>verifyData</servlet-name>
<url-pattern>/verifyData</url-pattern>
</servlet-mapping>
<error-page>
<error-code>9001</error-code> Define output error
<location>/[Link]</location> page for error code
</error-page>
</web-app>
Send Redirect
Redirect to another page to handle error
HttpServletResponse
public void sendError(int statusCode)
public void sendError(int statusCode,
String msg))
….
Import [Link].*; public void sendRedirect(String url);
import [Link].*;
import [Link].*;
publc class HtmlPage extends HttpServlet
{
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException
{
String name = [Link](“name”);
if ([Link]() < 1)
[Link](“/Servlets/invalidNamePage”);
}
}
forward() method sendRedirect() method
The forward() method works at The sendRedirect() method works at
server side. client side.
It sends the same request and It always sends a new request.
response objects to another servlet.
It can work within the server only. It can be used within and outside
the server.
Example: Example:
[Link]("servl [Link]("servlet2");
et2").forward(request,response);
Setting Arbitrary Response Headers
public void setHeader(String headerName,String headerValue)
Sets an arbitrary header
public void setDateHeader(String name, long millisecs)
Converts millis since 1970 to date in GMT format
public void setIntHeader(String name, int headerValue)
Prevents need to convert int to String
addHeader, addDateHeader, addIntHeader
Adds header instead of replacing
51
Setting Common Response Headers
Methods for specifying common headers
setContentType
Sets the Content-Type header (MIME Types).
setContentLength
Sets the Content-Length header.
addCookie
Adds a value to the Set-Cookie header.
sendRedirect
Sets Location header (plus changes status code)
52
Common HTTP 1.1 Response Headers
Cache-Control
A no-cache value prevents browsers from caching page. Send both
headers or check HTTP version
Content-Encoding
The way document is encoded. Browser reverses this encoding
before handling document (compression example).
Content-Length
The number of bytes in the response
Use ByteArrayOutputStream to buffer document so you can
determine size.
53
Common HTTP 1.1 Response Headers
(Continued)
Content-Type
The MIME type of the document being returned.
Use setContentType to set this header
Expires
The time at which document should be considered out-of-date and
thus should no longer be cached
Use setDateHeader to set this header
Last-Modified
The time document was last changed.
Don’t set this header explicitly; provide a getLastModified method
instead.
54
Common HTTP 1.1 Response Headers
(Continued)
Location
The URL to which browser should reconnect.
Use sendRedirect instead of setting this directly.
Refresh
The number of seconds until browser should reload page. Can
also include URL to connect to.
Set-Cookie
The cookies that browser should remember. Don’t set this
header directly; use addCookie instead
55