Servlet Technology Is Used To Create A Web Application (Resides at Server Side and Generates A Dynamic Web Page)

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 41

• Servlet technology is used to create a web application (resides at

server side and generates a dynamic web page).


The servlet example can be created by three ways:
• By implementing Servlet interface,
• By inheriting GenericServlet class, (or)
• By inheriting HttpServlet class
Servlet Life cycle
• Load Servlet class
• Create servlet instance
• Call to the init( ) method
• Call to the service( ) method
• Call to the destroy( ) method
• 
Handling Client Request: HTTP Request Headers

• The HTTP information that is sent from the browser to the server in
the form of request headers.
• HTTP request headers are distinct from the form data.
• Form data results directly from user input and is sent as part of the
URL for GET requests and on a separate line for POST requests.
• Request headers, are indirectly set by the browser and are sent
immediately following the initial GET or POST request line.
•  Reading Request Headers from Servlets
Header names are not case sensitive
The list of headers that are generally used
Header names Description
getCookies The getCookies method returns the contents of the Cookie
header, parsed and stored in an array of Cookie objects.
getAuthType() and break the Authorization header into its component pieces.
getRemoteUser()
getContentLength() returns int value of the Content-Length header
getContentType() Returns string value of the Content-Type header
getDateHeader() read the specified header and then convert them to Date and int values
getIntHeader()
getHeaderNames() to get an Enumeration of the values of all occurrences of the header names received
on this particular request.
getHeaders() If a header name is repeated in the request,
• version 2.1 servlets cannot access: returns the value of the
first occurrence of the header only
• version 2.2, returns an Enumeration of the values of all
occurrences of the header.
getMethod() returns the main request method(Get, Post . . . . )
getRequestURI() returns the part of the URL that comes after the host and port but before the form
data
getProtocol() returns the third part of the request line, [HTTP/1.0 or HTTP/1.1]
• Example1:
public class mca extends HttpServlet
{
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException

res.setContentType("text/html");
PrintWriter out = response.getWriter(); 
String title = "Servlet Example: Showing Request Headers";
out.println(ServletUtilities.headWithTitle(title) + "<BODY>\n" +
"<H1>" + title + "</H1>\n" +
"<B>Request Method: </B>"+request.getMethod() +"<BR>\n" +
“<B>Request URI: </B>"+request.getRequestURI()+"<BR>\n" +
“<B>Request Protocol: </B>" +request.getProtocol());
Enumeration <String> headerNames= request.getHeaderNames();
while(headerNames.hasMoreElements())
{
String headerName = headerNames.nextElement();
out.println(“Header Name: <em>”+headerName);
String headerValue = request.getHeader(headerName);
out.print(“</em>, Header Value: <em>”+ headerValue);
out.println(“</em><br/>”);
out.println("</BODY></HTML>");
}
}}
• Example2:
public class rnsit extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "HTTP Header Request Example";
String docType =
"<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n";
out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n"+
"<body bgcolor = \"#f0f0f0\">\n" +
"<h1 align = \"center\">" + title + "</h1>\n" +
"<table width = \"100%\" border = \"1\" align = \"center\">\n" +
"<tr bgcolor = \"#949494\">\n" +
"<th>Header Name</th><th>Header Value(s)</th>\n"+
"</tr>\n"
);
Enumeration headerNames = request.getHeaderNames();
while(headerNames.hasMoreElements())
{
String paramName = (String)headerNames.nextElement();
out.print("<tr><td>" + paramName + "</td>\n");
String paramValue = request.getHeader(paramName);
out.println("<td> " + paramValue + "</td></tr>\n");
}
out.println("</table>\n</body></html>");
}
}
HTTP 1.1 Request Headers
• HTTP 1.1 also allows you to have persistent(always) connections
which means that you can have more than one request/response on
the same HTTP connection.

• In HTTP 1.0 you had to open a new connection for each


request/response pair.

• And after each response the connection would be closed.


Header Names Description
Accept specifies the MIME types that the browser or other client can handle. Returns more
than one format
Accept-Charset indicates the character sets (e.g., ISO-8859-1) the browser can use.
Accept-Encoding designates the types of encodings that the client knows how to handle. If it receives
this header, the server is free to encode the page by using the format, sending the
Content-Encoding response header to indicate that it has done so
Accept-Language specifies the client’s preferred languages, in case the servlet can produce results in
more than one language. The value of the header should be one of the standard
language codes such as en, en-us, da, etc.
Authorization is used by clients to identify themselves when accessing password-protected Web
pages.
Cache-Control used by the client to specify a number of options for how pages should be cached by
proxy servers.
Connection tells whether or not the client can handle persistent HTTP Connections.
Content-Length only applicable to POST requests and gives the size of the POST data in bytes.
Simply use request.getContentLength().
Content-Type It is used in responses from the server, it can also be part of client requests
when the client attaches a document as the POST data or when making PUT
requests. You can access this header with the shorthand getContentType method
of HttpServletRequest.
Cookie This header is used to return cookies to servers that previously sent them to the
browser.
Expect This rarely used header lets the client tell the server what kinds of
behaviors it expects.
From This header gives the e-mail address of the person responsible for the HTTP
request.
Host Browsers are required to specify this header, which indicates the host and port
as given in the original URL.
If-Match This rarely used header applies primarily to PUT requests. The client
can supply a list of entity tags as returned by the ETag response header, and the
operation is performed only if one of them matches.
If-Modified-Since This header indicates that the client wants the page only if it has been changed
after the specified date. This option is very useful because it lets browsers cache
documents and reload them over the network only when they’ve changed.
Proxy-Authorization This header lets clients identify themselves to proxies that require it.
Servlets typically ignore this header, using Authorization instead.
Range This rarely used header lets a client that has a partial copy of a document ask for
only the parts it is missing.
Referer This header indicates the URL of the referring Web page. it is a useful way of
tracking where requests came from
Upgrade The Upgrade header lets the browser or other client specify a communication
  protocol it prefers over HTTP 1.1
User-Agent This header identifies the browser or other client making the request.
Via This header is set by gateways and proxies to show the intermediate
  sites the request passed through.
Warning This rarely used catchall header lets clients warn about caching or content
Transformation errors.
Pragma A Pragma header with a value of no-cache indicates that a servlet that is acting
  as a proxy should forward the request even if it has a local copy.
Sending Compressed Web pages
• Gzip is a text compression scheme that can dramatically reduce the
size of HTML pages.

• Several recent browsers know how to handle gzipped content, so the


server can compress the document and send the smaller document
over the network, after which the browser will automatically reverse
the compression and treat the result in the normal manner.

• Sending such compressed content can be a real timesaver, since the


time required to compress the document on the server and then
uncompress it on the client is typically dwarfed by the savings in
download time, especially when dialup connections are used.
• To send compressed content, a servlet must send a Content-Encoding
header to tell the client scheme by which the content has to be
encoded.
• Browsers that support this feature indicate that they do so by
setting the Accept-Encoding request header.

• void setHeader(String name, String value)


• Sets a response header with the given name and value.

• Wrap the response.getOutputStream() in a GZIPOutputStream().


• The content-Encoding entity header is used to compress the file.
• Implementing compression
• java.util.zip: package contains classes that support reading and writing
the GZIP and ZIP compression formats.
• The servlet first checks the Accept-Encoding header to see if it
contains an entry for gzip.
• If so, it uses a GZIPOutputStream to generate the page, specifying
gzip as the value of the Content-Encoding header.
• explicitly call close when using a GZIPOutputStream.
• If gzip is not supported, the servlet uses the normal PrintWriter to
send the page
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.zip.GZIPOutputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class zgip extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse
response)throws ServletException, IOException
{
response.setContentType("text/html");
String encodings = request.getHeader("Accept-Encoding");
PrintWriter out;
String title;
if ((encodings != null))
{
title = "Page Encoded with GZip";
OutputStream out1 = response.getOutputStream();
out = new PrintWriter(new GZIPOutputStream(out1));
response.setHeader("Content-Encoding", "gzip");
}
else
{
title = "Unencoded Page";
out = response.getWriter();
}
out.println(title + "<BODY BGCOLOR=\"#FDF5E6\">\n" + "<H1 ALIGN=CENTER>" + title +
"</H1>\n");
String line = “rnsit" + “mca";
for(int i=0; i<100; i++)
{
out.println(line);
}
out.println("</BODY></HTML>");
out.close();
}
}
• Generating server Response: HTTP Status codes
• Generating server Response: HTTP Response Headers
cookies
• A cookie is a small piece of information that is persisted between the
multiple client requests.
• 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.
Advantage of Cookies
• Simplest technique of maintaining the state(data).
• Cookies are maintained at client side.
Disadvantage of Cookies
• It will not work if cookie is disabled from the browser.
• Only textual information can be set in Cookie object.
• Types of Cookies
• We can classify the cookie based on their expiry time:
Session
Persistent
• SessionCookies:
Session cookies do not have expiration time. It lives in the browser
memory. As soon as the web browser is closed this cookie gets
destroyed.
• Persistent Cookies:
Unlike Session cookies they have expiration time, they are stored in
the user hard drive and gets destroyed based on the expiry time.
• How to send Cookies to the Client
• Here are steps for sending cookie to the client:
Create a Cookie object.
Set the maximum Age.
Place the Cookie in HTTP response header
Create a Cookie object:
• Cookie ck=new Cookie("user",“raghu");//creating cookie object 
Set the maximum Age:
• By using setMaxAge () method we can set the maximum age for the
particular cookie in seconds.
 ck.setMaxAge(1800);
•  Place the Cookie in HTTP response header:
• We can send the cookie to the client browser through
response.addCookie() method.
response.addCookie(ck);//adding cookie in the response  

• How to delete Cookie?


• The Servlet API doesn't provide a direct way to delete a cookie in
a Servlet application.
• If you want to delete a cookie you have to create a cookie that have the
same name with the cookie that you want to delete and set the value to an
empty string.
• You also need to set the max age of the cookie to 0
Cookie class
• javax.servlet.http.Cookie class provides the functionality of
using cookies. It provides a lot of useful methods for cookies.
• Constructor of Cookie class
Constructor Description

Cookie() constructs a cookie.

Cookie(String name, String constructs a cookie with a


value) specified name and value.
Useful Methods of Cookie class
• There are given some commonly used methods of the Cookie class.
Method Description

public void setMaxAge(int expiry) Sets the maximum age of the


cookie in seconds.
public String getName() Returns the name of the cookie.
The name cannot be changed
after creation.
public String getValue() Returns the value of the cookie.

public void setName(String changes the name of the cookie.


name)
public void setValue(String value) changes the value of the cookie.
How to create Cookie?
Cookie ck=new Cookie("user",“raghu");//creating cookie object  
response.addCookie(ck);//adding cookie in the response  
How to delete Cookie?
Cookie ck=new Cookie("user","");//deleting value of cookie  
ck.setMaxAge(0);//changing the maximum age to 0 seconds  
response.addCookie(ck);//adding cookie in the response  
sessions

• Cookies and session both store information about the user but the difference is
that cookies store information on the client-side (browser) and sessions store
information on the server-side.
• the time between the user logging in and logging out is a session.
Session Tracking
• Session Tracking is a way to maintain state (data) of an user. It is also known as session
management in servlet.
• There are four different techniques used by Servlet application for session
management. They are as follows:
• Cookies
• URL-rewriting
• Hidden form fields
• HttpSession
URL Rewriting
• In URL rewriting, we append a token or identifier to the URL of the
next Servlet or the next resource.
• We can send parameter name/value pairs using the following format:
url?name1=value1&name2=value2&??
• A name and a value is separated using an equal = sign, a parameter
name/value pair is separated from another parameter using the
ampersand(&).
• When the user clicks the hyperlink, the parameter name/value
pairs will be passed to the server.
• From a Servlet, we can use getParameter() method to obtain a
parameter value.
• In this example, we are maintaning the state of the user using link.
• For this purpose, we are appending the name of the user in the query
string and getting the value from the query string in another page.
• Example see below program
index.html
<form action="servlet1">  
Name:<input type="text" name="userName"/><br/>  
<input type="submit" value="go"/>  
</form>  
servlet1
public class servlet1 extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);
out.print("<a href='servlet2?uname="+n+"'>visit</a>");
}
}
servlet2
public class servlet2 extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("uname");
out.println("Hello "+n);
out.println(“This site is under construction”);
}
}
Hidden Form Field
• in case of Hidden Form Field a hidden (invisible) textfield is used for
maintaining the state of an user.
• In such case, we store the information in the hidden field and get it from
another servlet.
• This approach is better if we have to submit form in all the pages and we
don't want to depend on the browser.
• Let's see the code to store value in hidden field.
• <input type="hidden" name="uname" value=“raghu">  
• Here, uname is the hidden field name and raghu is the hidden field
value.
• Example see below program
index.html
<form action="servlet1">  
Name:<input type="text" name="userName"/><br/>  
<input type="submit" value="go"/>  
</form>  
servlet1
public class servlet1 extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);
contd……
out.print("<form action='servlet2'>");
out.print("<input type='hidden' name='uname' value='"+n+"'>");
out.print("<input type='submit' value='go'>");
out.print("</form>");
}}
servlet2
public class servlet2 extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("uname");
out.print("Hello "+n);
out.println(“This site is under construction”);
}
}
• HttpSession
• Creating a new session
HttpSession session =request.getSession();
• // getsession() method returns a session. If the session already exists, it
returns the existing session else create a new session

HttpSession session = request.getSession(true);


• // getsession(true) always returns new session
• Getting a pre-existing session
HttpSession session = request.getSession(false);

• //getSession(false)will check existence of session, If session


exists, then it returns the reference of that session object, if not,
this methods will return null
• Destroying a session
session.invalidate( );
//destroy a session
Example see lab program 5

You might also like