Ajp Notes Chap6
Ajp Notes Chap6
Servlet(14M)
Servlets are small programs that execute on the server side of a Web
connection.
Applets dynamically extend the functionality of a Web browser,
servlets dynamically extend the functionality of a Web server
Servlet technology is used to create a web application (resides at
server side and generates a dynamic web page).
Servlet is a web component that is deployed on the server to create a
dynamic web page.
Disadvantages of CGI
1. If the number of clients increases, it takes more time for sending the
response.
2. For each request, it starts a process, and the web server is limited to
start processes.
3. It uses platform dependent language e.g. C, C++, perl.
Advantages of Servlet
There are many advantages of Servlet over CGI. The web container creates
threads for handling the multiple requests to the Servlet. Threads have many
benefits over the Processes such as they share a common memory area,
lightweight, cost of communication between the threads are low. The
advantages of Servlet are as follows:
The web container maintains the life cycle of a servlet instance. Let's see the life
cycle of the servlet:
Two packages contain the classes and interfaces that are required to build
servlets. These are javax.servlet and javax.servlet.http
Interface Description
Servlet Declares life cycle methods for a servlet.
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.
Class Description
GenericServlet Implements the Servlet and ServletConfig interfaces.
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.
There are 5 methods in Servlet interface. The init, service and destroy are the life cycle
methods of servlet.
Method Description
public void initializes the servlet. It is the life cycle method of servlet and
init(ServletConfig config) invoked by the web container only once.
public void provides response for the incoming request. It is invoked at
service(ServletRequest each request by the web container.
request,ServletResponse
response)
public void destroy() is invoked only once and indicates that servlet is being
destroyed.
public ServletConfig returns the object of ServletConfig.
getServletConfig()
public String returns information about servlet such as writer, copyright,
getServletInfo() version etc.
The ServletConfig Interface
An object of ServletConfig is created by the web container for each servlet. This object can
be used to get configuration information from web.xml file.
If the configuration information is modified from the web.xml file, we don't need to change
the servlet. So it is easier to manage the web application if any specific content is modified
from time to time.
Method Description
Method Description
Object getAttribute(String attr) Returns the value of the server attribute named
attr.
String getMimeType(String file) Returns the MIME type of file.
String getRealPath(String vpath) Returns the real path that corresponds to the
virtual path vpath.
String getServerInfo( ) Returns information about the server.
void log(String s, Throwable e) Write s and the stack trace for e to the servlet log.
void setAttribute(String attr, Object val) Sets the attribute specified by attr to the value
passed in val.
The ServletRequest Interface
The ServletRequest interface is implemented by the server. It enables a servlet to obtain information
about a client request.
Method Description
Object getAttribute(String attr) Returns the value of the attribute named attr
BufferedReader getReader( ) throws Returns a buffered reader that can be used to read text
IOException from the request. An IllegalStateException is thrown
if getInputStream( ) has already been invoked for this
request.
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.
Method Description
void setContentType(String type) Sets the content type for the response to type.
The GenericServlet class provides implementations of the basic life cycle methods for a servlet and is
typically subclassed by servlet developers. GenericServlet implements the Servlet and ServletConfig
interfaces.
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. The following table summarizes the core interfaces that are provided in
this package:
Interface Description
Class Description
Method Description
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.
int getIntHeader(String field) Returns the int equivalent of the header field named
field.
String getMethod( ) Returns the HTTP method for this request.
String getPathInfo( ) Returns any path information that is located after the
servlet path and before a query string of the URL
String getPathTranslated( ) Returns any path information that is located after the
servlet path and before a query string of the URL
after translating it to a real path.
String getQueryString( ) Returns any query string in the URL
String getRemoteUser( ) Returns the name of the user who issued this
request.
String getRequestedSessionId( ) Returns the ID of the session.
String getRequestURI( ) Returns the URI
String getServletPath( ) Returns that part of the URL that identifies the
servlet.
HttpSession getSession( ) Returns the session for this request. If a session does
not exist, one is created and then returned.
HttpSession getSession(boolean new) If new is true and no session exists, creates and
returns a session for this request. Otherwise, returns
the existing session for this request.
boolean isRequestedSessionIdFromCookie( Returns true if a cookie contains the session ID.
) Otherwise, returns false.
boolean isRequestedSessionIdFromURL( ) Returns true if the URL contains the session ID.
Otherwise, returns false.
boolean isRequestedSessionIdValid( ) Returns true if the requested session ID is valid in the
current session context.
Method Description
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. If so, returns the modified
version of url. Otherwise, returns url. All URLs
generated by a servlet should be processed by this
method.
String encodeRedirectURL(String url) Determines if the session ID must be encoded in the
URL identified as url. If so, returns the modified
version of url. Otherwise, returns url. All URLs passed
to sendRedirect( ) should be processed by this
method.
void sendError(int c) throws IOException Sends the error code c to the client.
void sendError(int c, String s) throws Sends the error code c and message s to the client.
IOException
void sendRedirect(String url) throws Redirects the client to url.
IOException
void setDateHeader(String field, long msec) Adds field to the header with date value equal to
msec (milliseconds since midnight, January 1, 1970,
GMT).
void setHeader(String field, String value) Adds field to the header with value equal to value.
void setIntHeader(String field, int value) Adds field to the header with value equal to value.
void setStatus(int code) Sets the status code for this response to code.
Method Description
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.
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:
There is one constructor for Cookie. It has the signature shown here:
Method Description
boolean getSecure( ) Returns true if the cookie must be sent using only a
secure protocol. Otherwise, returns false.
String getValue( ) Returns the value.
void setSecure(boolean secure) Sets the security flag to secure, which means that
cookies will be sent only when a secure protocol is
being used.
void setValue(String v) Sets the value to v.
The HttpServlet class extends GenericServlet. It is commonly used when developing servlets that
receive and process HTTP requests. The methods of the HttpServlet class are summarized in Table.
Method Description
14.Run your application, right click on your Project and select Run
15.Click on the link created, to open your Servlet.
16.Hurray! Our First Servlet class is running.
The servlet can be created by three ways:
DoGet DoPost
In doGet Method the parameters are In doPost, parameters are sent in
appended to the URL and sent along separate line in the body
with header information
Maximum size of data that can be sent There is no maximum size for data
using doget is 240 bytes
Parameters are not encrypted Parameters are encrypted
DoGet method generally is used to Dopost is generally used to update or
query or to get some information from post some information to the server
the server
DoGet is faster if we set the response DoPost is slower compared to doGet
content length since the same since doPost does not write the content
connection is used. Thus increasing length
the performance
DoGet should be idempotent. i.e. This method does not need to be
doget should be able to be repeated idempotent. Operations requested
safely many times through POST can have side effects
for which the user can be held
accountable, for example, updating
stored data or buying items online.
DoGet should be safe without any side This method does not need to be either
effects for which user is held safe
responsible
doGet Method
Indexget.html
<html>
<body>
<center>
<form name="Form1" method=”get”
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>
ColorGetServlet.java
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
{
String color = request.getParameter("color");
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>The selected color is: ");
pw.println(color);
pw.close();
}
}
doPost Method
Indexpost.html
<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>
ColorPostServlet.java
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
{
String color = request.getParameter("color");
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>The selected color is: ");
pw.println(color);
pw.close();
}
}
HTTP is stateless that means each request is considered as the new request. It is
shown in the figure given below:
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
HttpServletResponse response)
// Get writer.
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.print("<B>");
if(date != null) {
hs.setAttribute("date", date);
}
Cookies in Servlet
A cookie has a name, a single value, and optional attributes such as a comment,
path and domain qualifiers, a maximum age, and a version number.
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 class
There are given some commonly used methods of the Cookie class.
Method Description
For adding cookie or getting the value from the cookie, we need some methods
provided by other interfaces.
They are:
1. public void addCookie(Cookie ck):method of HttpServletResponse interface is
program-
indexcookie.html
<html>
<body>
<center>
<form name="Form1"
method="post"
action="AddCookieServlet">
<B>Enter a value for MyCookie:</B>
<input type=textbox name="data" size=25 value="">
<input type=submit value="Submit">
</form>
</body>
</html>
AddCookieServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class AddCookieServlet extends HttpServlet
{
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
// Get parameter from HTTP request.
String data = request.getParameter("data");
// Create cookie.
Cookie cookie = new Cookie("MyCookie", data);
// Add cookie to HTTP response.
response.addCookie(cookie);
// Write output to browser.
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>MyCookie has been set to");
pw.println(data);
pw.close();
}
}