0% found this document useful (0 votes)
37 views40 pages

Chapter 6

Uploaded by

Aayush Chalke
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
37 views40 pages

Chapter 6

Uploaded by

Aayush Chalke
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 40

Advanced Java Programming

Servlets

Archana Gopnarayan
Lecturer , Department of Information Technology (NBA Accrediated)
Vidyalankar Polytechnic
Servlets

Servlets are the platform independent server side programs that execute within the
address space of the web server and which can handle multiple client requests
without creating separate processes for each.
Need of Servlet
• A user enters a Uniform Resource Locator (URL) into a browser. The browser
generates an HTTP request to the appropriate Web server.
• The Web server maps this request to a specific file.
• That file is returned in an HTTP response to the browser.
• The HTTP header in the response indicates the type of the content. The
Multipurpose Internet Mail Extensions (MIME) are used for this purpose.
• For example, ordinary ASCII text has a MIME type of text/plain.
• The Hypertext Markup Language (HTML) source code of a Web page has a MIME
type of text/html.
• In case of dynamic content The contents of those Web pages must be dynamically
generated in order to reflect the latest information in the database.
• Common Gateway Interface (CGI) allowed the separate process to read data from
the HTTP request and write data to the HTTP response.
• CGI suffered serious performance problems. It was expensive in terms of
processor and memory resources to create a separate process for each
client request.
• It was also expensive to open and close database connections for each
client request.
• Servlets offer several advantages in comparison with CGI.
• Servlets execute within the address space of a Web server.
• It is not necessary to create a separate process to handle each client
request.
• servlets are platform-independent because they are written in Java.
The Life Cycle of a Servlet
The Life Cycle of a Servlet
• Three methods are central to the life cycle of a servlet. These are init( ),
service( ), and destroy( ).
• First, A user enters a Uniform Resource Locator (URL) to a Web browser. The
browser then generates an HTTP request for this URL. This request is then
sent to the appropriate server.
• Second, this HTTP request is received by the Web server. The server maps this
request to a particular servlet. The servlet is dynamically retrieved and loaded
into the address space of the server.
• Third, the server invokes the init( ) method of the servlet. This method is
invoked only when the servlet is first loaded into memory.
• Fourth, the server invokes the service( ) method of the servlet. This method is
called to process the HTTP request. You will see that it is possible for the
servlet to read data that has been provided in the HTTP request. It may also
formulate an HTTP response for the client.
• Finally, the server may decide to unload the servlet from its memory. The server
calls the destroy( ) method to relinquish any resources such as file handles that are
allocated for the servlet.
import java.io.*;
import javax.servlet.*;
public class HelloServlet extends GenericServlet
{
public void service(ServletRequest request, ServletResponse response) throws
ServletException, IOException
{
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>Hello!");
pw.close();
}
}
Servlet Hierarchy
JAVAX.SERVLET PACKAGE
The javax.servlet Package
• Interface Description
• Servlet Declares life cycle methods for a servlet.
• ServletConfig Allows servlets to get initialization parameters.
• ServletContext Enables servlets to log events and access
information
about their environment.
• ServletRequest Used to read data from a client request.
• ServletResponse Used to write data to a client response.
• SingleThreadModel Indicates that the servlet is thread safe.
Class Description
GenericServlet Implements the Servlet and ServletConfiginterfaces.
ServletInputStream Provides an input stream for reading requests from
a client.
ServletOutputStream Provides an output stream for writing responses to
a client.
ServletException Indicates a servlet error occurred.
UnavailableException Indicates a servlet is unavailable.
The Servlet Interface

void destroy( ) Called when the servlet is unloaded.


ServletConfig getServletConfig( ) Returns a ServletConfig object that
contains any initialization parameters.

void init(ServletConfig sc)throws ServletException Called when the servlet is


initialized.
void service(ServletRequest req, ServletResponse res) throws
ServletException,
IOException
Called to process a request from a client. The request from the client can be read
from req.
The response to the client can be written to res.
The ServletConfig Interface
• The ServletConfig interface is implemented by the server. It allows a servlet to
obtain
• configuration data when it is loaded
Method Description
ServletContext getServletContext( ) Returns the context for this servlet.
String getServletName( )
Returns the name of the invoking servlet.
The ServletContext Interface

• Method Description
Object getAttribute(String attr) Returns the value of the server attribute
named attr.
String getServerInfo( ) Returns information about the server.
void log(String s) Writes s to the servlet log.
void setAttribute(String attr, Object val) Sets the attribute spe
The ServletRequest Interface
Object getAttribute(String attr) Returns the value of the attribute named attr.
String getCharacterEncoding( ) Returns the character encoding of the request.
int getContentLength( ) Returns the size of the request. The value –1 is
returned if the size is unavailable.
String getContentType( ) Returns the type of the request. A null value is
returned if the type cannot be determined.

String getParameter(String pname) Returns the value of the parameter named


pname.
.
String getProtocol( ) Returns a description of the protocol.
String getRemoteAddr( ) Returns the string equivalent of the client IP address.
String getRemoteHost( ) Returns the string equivalent of the client host name.
String getScheme( ) Returns the transmission scheme of the URL used for the request
for example, “http”, “ftp”).
String getServerName( ) Returns the name of the server.
int getServerPort( ) Returns the port number.
The ServletResponse Interface

ServletOutputStream getOutputStream( ) throws IOException Returns a


ServletOutputStream that can be used to write binary data to the response.

void setContentLength(int size) Sets the content length for the response to size.

void setContentType(String type) Sets the content type for the response to type.
The ServletOutputStream Class
• The ServletOutputStream class extends OutputStream.
• It is implemented by the servlet container and provides an output stream that a
servlet developer can use to write data to a client response.
• It also defines the print( ) and println( ) methods, which output data to the
stream.
The Servlet Exception Classes
• javax.servlet defines two exceptions.
• The first is ServletException, which indicates that a servlet problem has
occurred.
• The second is UnavailableException, which extends ServletException. It
indicates that a servlet is unavailable.
The javax.servlet.http Package

• The javax.servlet.http package contains a number of interfaces and classes


that are commonly used by servlet developers.
• You will see that its functionality makes it easy to build servlets that work with
HTTP requests and responses.
Interfaces
• HttpServletRequest Enables servlets to read data from an HTTP request.
• HttpServletResponse Enables servlets to write data to an HTTP response.
• HttpSession Allows session data to be read and written.
• HttpSessionBindingListener Informs an object that it is bound to or unbound from a
session.
Classes
• Cookie Allows state information to be stored on a client machine.
• HttpServlet Provides methods to handle HTTP requests and responses.
• HttpSessionEvent Encapsulates a session-changed event.
• HttpSessionBindingEvent Indicates when a listener is bound to or unbound from a session
• value, or that a session attribute changed.
The HttpServletRequest Interface
• The HttpServletRequest interface enables a servlet to obtain information about a client
request.

String getAuthType( ) Returns authentication scheme.


Cookie[ ] getCookies( ) Returns an array of the cookies in this request.
long getDateHeader(String field) Returns the value of the date header field named field.
String getHeader(String field) Returns the value of the header field named field.
String getRemoteUser( ) Returns the name of the user who issued this request.
The HttpServletResponse
Interface
The HttpServletResponse interface enables a servlet to formulate an HTTP
response to a client.
void addCookie(Cookie cookie) Adds cookie to the HTTP response.
boolean containsHeader(String field) Returns true if the HTTP response header
contains a field named field.
String encodeURL(String url) Determines if the session ID must
be encoded in the URL identified as url.

void sendError(int c) Sends the error code c to the


client.
void sendRedirect(String url) Redirects the client to url.
The HttpSession Interface
• The HttpSession interface enables a servlet to read and write the state information
thatis associated with an HTTP session.

• Object getAttribute(String attr) Returns the value associated with the name passed
in attr. Returns null if attr is not found.

• Enumeration getAttributeNames( ) Returns an enumeration of the attribute names


associated with the session.
• long getCreationTime( ) Returns the time (in milliseconds since midnight, January 1,
1970, GMT) when this session was created.
• String getId( ) Returns the session ID.
long getLastAccessedTime( ) Returns the time (in milliseconds since midnight, January
1, 1970, GMT) when the client last made a request for this session.

void invalidate( ) Invalidates this session and removes it from the context.
boolean isNew( ) Returns true if the server created the session and it has not yet been
accessed by the client.
void removeAttribute(String attr) Removes the attribute specified by attr from the
session.
void setAttribute(String attr, Object val) Associates the value passed in val with the
attribute name passed in attr.
The Cookie Class
• The Cookie class encapsulates a cookie.
• A cookie is stored on a client and contains state information. Cookies are valuable
for tracking user activities.
• A servlet can write a cookie to a user’s machine via the addCookie( ) method of the
HttpServletResponse interface.
The data for that cookie is then included in the header of the HTTP response that is
sent to the browser.
• The names and values of cookies are stored on the user’s machine.
• Some of the information that is saved for each cookie includes the following:
• The name of the cookie
• The value of the cookie
• The expiration date of the cookie
• The domain and path of the cookie
Cookie(String name, String value)
Method Description
Object clone( ) Returns a copy of this object.
String getComment( ) Returns the comment.
String getDomain( ) Returns the domain.
int getMaxAge( ) Returns the maximum age (in seconds).
String getName( ) Returns the name.
String getPath( ) Returns the path.
boolean getSecure( ) Returns true if the cookie is secure. Otherwise, returns
false.
String getValue( ) Returns the value.
int getVersion( ) Returns the version.
void setComment(String c) Sets the comment to c.
void setDomain(String d) Sets the domain to d.
void setMaxAge(int secs) Sets the maximum age of the cookie to secs. This is the
number of seconds after which the cookie is deleted.
• void setPath(String p) Sets the path to p.
• void setSecure(boolean secure) Sets the security flag to secure.
• void setValue(String v) Sets the value to v.
• void setVersion(int v) Sets the version to v.
The HttpServlet Class
• The HttpServlet class extends GenericServlet.
• It is commonly used when developing servlets that receive and process HTTP
requests.
void doDelete(HttpServletRequest req, HttpServletResponse res) throws
IOException, ServletException
Handles an HTTP DELETE request.
void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException,
ServletException
Handles an HTTP GET request.
void doHead(HttpServletRequest req, HttpServletResponse res) throws
IOException,
ServletException
Handles an HTTP HEAD request.
void doOptions(HttpServletRequest req, HttpServletResponse res) throws
IOException, ServletException
Handles an HTTP OPTIONS request.
void doPost(HttpServletRequest req, HttpServletResponse res) throws
IOException, ServletException
Handles an HTTP POST request.
void doPut(HttpServletRequest req, HttpServletResponse res) throws IOException,
ServletException
Handles an HTTP PUT request.
void doTrace(HttpServletRequest req, HttpServletResponse res) throws
IOException, ServletException
Handles an HTTP TRACE request.
Long getLastModified(HttpServletRequest req)
Returns the time (in milliseconds since midnight, January 1, 1970, GMT) when the
requested resource was last modified.
void service(HttpServletRequest req, HttpServletResponse res) throws
IOException, ServletException
Called by the server when an HTTP request arrives for this servlet. The arguments
provide access to the HTTP request and response, respectively.
The HttpSessionBindingEvent Class
The HttpSessionBindingEvent class extends HttpSessionEvent.
It is generated when a listener is bound to or unbound from a value in an HttpSession
object
The getName( ) method obtains the name that is being bound or unbound. It is shown
String getName( )

The getSession( ) method, obtains the session to which the listener is being bound or
unbound:
HttpSession getSession( )

The getValue( ) method obtains the value of the attribute that is being bound or unbound.
Object getValue( )
Handling HTTP GET Requests
<html>
<body>
<center>
<form name="Form1“ action=“ColorGetServlet">
<B>Color:</B>
<select name="color" size="1">
<option value="Red">Red</option>
<option value="Green">Green</option>
<option value="Blue">Blue</option>
</select>
<br><br>
<input type=submit value="Submit">
</form>
</body>
</html>
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ColorGetServlet extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException
{
response.setContentType("text/html");
String color = request.getParameter("color");
PrintWriter pw = response.getWriter();
pw.println("<B>The selected color is: ");
pw.println(color);
pw.close();
}
}
http://localhost:8080/servlets-examples/servlet/ColorGetServlet?color=Red

The characters to the right of the question mark are known as the query string.
<html>
<body>
<center>
<form name="Form1“ method="post“ action="ColorPostServlet">
<B>Color:</B>
<select name="color" size="1">
<option value="Red">Red</option>
<option value="Green">Green</option>
<option value="Blue">Blue</option>
</select>
<br><br>
<input type=submit value="Submit">
</form>
</body>
</html>
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ColorPostServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException
{
response.setContentType("text/html");
String color = request.getParameter("color");
PrintWriter pw = response.getWriter();
pw.println("<B>The selected color is: ");
pw.println(color);
pw.close();
}
}
Session Tracking
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class DateServlet extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
HttpSession hs = request.getSession(true);
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.print("<B>");
Date date = (Date)hs.getAttribute("date");
if(date != null) {
pw.print("Last access: " + date + "<br>");
}
date = new Date();
hs.setAttribute("date", date);
pw.println("Current date: " + date);
}
}

You might also like