Unit 2
Unit 2
Unit 2
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
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 javax.servlet package provides basic interfaces
The javax.servlet.http these interfaces, provides classes
and interfaces derived to provides specific means for
servicing HTTP requests.
Servlet
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 received.For
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 java.lang.String getServletName()
public ServletContext getServletContext()
public Enumeration getInitParameterNames()
public String getInitParameter(String name)
Servlet get its Initilialization Information from web.xml
Inside the <servlet> tag for the given servlet in web.xml :
Add <init-param> tag
For each <init-param> tag
there is one <param-name> and <param-value>
Web.xml
<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 = config.getInitParameter(“myName");
}
getInitParameterNames()
This method returns the all parameter names from the web.xml
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 = sc.getInitParameterNames();
while (en.hasMoreElements())
{
String st = en.nextElement();
out.print("<br>" + st + "------" + sc.getInitParameter(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 web.xml
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 web.xml.
It can send configuration information to all servlets in a web application
Web.xml
<context-param>
<param-name>myName</param-name>
<param-value>myValue</param-value>
</context-param
ServletContext methods
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.
A POST request results from an HTML form that specifically lists POST as the METHOD and it should be
handled by doPost() 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: request.getParameter(“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 = request.getParameterValues(paramName);
Reading All Parameter Names
getParameterNames() or getParameterMap()
Returns Enumeration or Map of request params
Usually reserved for debugging
Examples:
Enumeration paramNames=request.getParameterNames();
while(paramNames.hasMoreElements())
{
String paramName=(String)paramNames.nextElement();
out.println(request.getParameter(paramName));
}
Reading Request Headers
(Methods in HttpServletRequest)
getCookies: Returns the contents of cookie header, parsed and stored in
an array of Cookie objects.
getContentLength : Returns the value of the content length header (in int)
getRequestURI : Returns the part of the URL that comes after the
host and port but before form data.
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.
Host : Indicates the host and port as given in the original URL.
Web Server
Web Client
1) Status code
response 2) Response header
3) Content-Type
4) HTML pages / Other files
39
Setting Status Codes
response.setStatus(intstatusCode)
response.sendError(int code, String message)
response.sendRedirect(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
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’
‘http://java.sun.com/dtd/web-app_2_3.dtd’>
<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>/error9001.html</location> page for error code
</error-page>
</web-app>
Send Redirect
Redirect to another page to handle error
HttpServletResponse
It can work within the server only. It can be used within and outside
the server.
Example: Example:
request.getRequestDispacher("servl response.sendRedirect("servlet2");
et2").forward(request,response);
Setting Arbitrary Response Headers
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