[go: up one dir, main page]

0% found this document useful (0 votes)
17 views107 pages

1 Servlets-2021

The document outlines the syllabus for an Advanced Java programming course, covering topics such as Servlets, JSP, Annotations, JDBC, and EJB, with a total of 45 hours of instruction. It includes a detailed breakdown of each module, the question paper pattern, and recommended textbooks and references. Additionally, it provides an introduction to servlet technology, its advantages over CGI, and the servlet lifecycle, along with a simple servlet example.

Uploaded by

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

1 Servlets-2021

The document outlines the syllabus for an Advanced Java programming course, covering topics such as Servlets, JSP, Annotations, JDBC, and EJB, with a total of 45 hours of instruction. It includes a detailed breakdown of each module, the question paper pattern, and recommended textbooks and references. Additionally, it provides an introduction to servlet technology, its advantages over CGI, and the servlet lifecycle, along with a simple servlet example.

Uploaded by

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

Advanced JAVA

Programming
SubjectCode: 18MCA41 I.A. Marks : 40
Hours/Week : 3 ExamHours: 3
TotalHours : 45 ExamMarks: 60
Model 1:Servlets: 9Hours
Servlet Structure, Servlet packaging, HTML building utilities, Lifecycle, Single
Thread model interface,
Handling Client Request: Form Data, Handling Client Request: HTTP Request
Headers. Generating server Response: HTTP Status codes, Generating server
Response: HTTP Response Headers, Handling Cookies, Session Tracking.
Overview of JSP Technology, Need of JSP, Benefits of JSP, Advantages of JSP,
Basic syntax,

Model 2: JSP & Controlling the Structure of generated servlets :


9Hours
Invoking java code with JSP scripting elements,creating Template Text,
Invoking java code from JSP,Limiting java codein JSP, using
jspexpressions,comparing servlets and jsp, writing scriptlets. For example Using
Scriptlets to make parts of jsp conditional, using declarations, declaration
example.
The JSPpage directive, import attribute, session attribute, is Elign or e attribute,
buffer and auto flush attributes, info attribute, error Page and is error Page
attributes, is Thread safe Attribute, extends attribute, language attribute,
Including files and applets in jsp Pages, using java beans components in JSP
documents.

Model 3: Annotations: 9Hours

Creating Packages, Interfaces, JAR files and Annotations. The core java API
package, New java.Lang Subpackage, Built-in Annotations. Working with Java
Beans. Intro spection, Customizers, creating java bean, manifestfile, Bean
Jarfile, new bean, adding controls, Bean properties, Simple properties, Design
Pattern events, creating bound properties, Bean Methods, Bean an Icon,Bean
info class, Persistence ,Java Beans API.
Model 4:JDBC: 9Hours
Talking to Database, Immediate Solutions, Essential JDBC program, using
prepared Statemen tObject, Interactive SQL tool. JDBC In Action Resultsets,
Batch updates, Mapping, Basic JDBC data types, Advanced JDBC data types,
Immediate solutions. Interducation to EJB: The Problem domain, Break up
responsibilities, Code Smart nothard, the Enterprise java bean specification.
Components Types.

Model 5: EJB & Server side component Model: 9 Hours


Server Side Component Types, Session Beans, Message Driven Beans, Entity
Beans,The Java Persistence Model. Container services.Dependency Injection,
Concurrency, Instance pooling ncaching, Transactions, security, Timers, Naming
and objectstores, Interoperability, LifeCycle Callbacks, Interceptors, platform
integration. Developing your first EJB.preparation, Definitions, naming
conventions, convention for the Examples,coding the EJB, the contract, the bean
Implementation class, out of ContainerTesting,Integration Testing.
The State less Session Bean, the Stateful Session Bean, the Singleton Session
Bean, Message-Driven Beans.EJB and PERSISTENCE. Persistence
Entitymanager Mapping Persistence objects, Entity Relationships.

Question paper pattern:


· The question paper will have ten questions.
· Each full question consists of 16 marks.
·There will be 2full questions (with a maximum of four sub
questions) from each module.
· Each full question will have sub questions covering all the topics
under a module.
· The students will have to answer 5 full questions, selecting one full
question from each module.
Text Books:
1. Marty Hall, Larry Brown. Core Servlets and Java Server Pages. Volume 1: Core
Technologies. 2nd Edition. (Chapter 3,4,5,6,7,8,9,10,11,12,13,14).
2. Java 6 Programming Black Book, Dreamtech Press. 2012 (Chapter
17,18,19,20,21,22,27,28,29,30).
3. Andrew LeeRubinger, Bill Burke. Developing Enterprise Java Components.
Enterprise JavaBeans 3.1.O’reilly. (Chapter 1,2,3,4,5,6,7,8,9,10,11).
Reference Books:
1. Michael Sikora, EJB 3 Developer Guide, A practical guide for developers and
architects to the Enterprise Java Beans Standard, Shroff Publishers &
Distributors PVT LTD. July 2008.
2. Herbert Schildt, Java The Complete Reference, 8th Edition. Comprehensive
coverage of the Java Language. Tata McGraw-Hill Edition – 2011.

GRNICA 6
Servlets
Servlet: Introduction to Web
Web consists of billions of clients and server connected through wires
and wireless networks. The web clients make requests to web server. The web
server receives the request, finds the resources and return the response to the
client.
When a server answers a request, it usually sends some type of content
to the client. The client uses web browser to send request to the server. The
server often sends response to the browser with a set of instructions written in
HTML( HyperText Markup Language ). All browsers know how to display
HTML page to the client.
Web Application
A website is a collection of static files(webpages) such as HTML pages,
images, graphics etc. A Web application is a web site with dynamic
functionality on the server. Google, Facebook, Twitter are examples of web
applications.
HTTP (Hypertext Transfer Protocol)
•HTTP is a protocol that clients and servers use on the web to communicate.
•It is similar to other internet protocols such as SMTP(Simple Mail Transfer
Protocol) and FTP(File Transfer Protocol) but there is one fundamental
difference.
•HTTP is a stateless protocol i.e HTTP supports only one request per
connection. This means that with HTTP the clients connect to the server to send
one request and then disconnects. This mechanism allows more users to connect
to a given server over a period of time.
•The client sends an HTTP request and the server answers with an HTML page
to the client, using HTTP.
Servl
etsside
Servlet technology is used to create web application (resides at server
and generates dynamic web page).

Servlet technology is robust and scalable because of java language.


Before Servlet, CGI (Common Gateway Interface) scripting language was
popular as a server-side programming language.
There are many interfaces and classes in the servlet API such as Servlet,
GenericServlet, HttpServlet, ServletRequest, ServletResponse etc.

A servlet is a java class that extends an application hosted on a web


server.

GRNICA 12
GRNICA 13
Java Servlets are programs that run on a Web or Application server and act
as a middle layer between a requests coming from a Web browser or other
HTTP client and databases or applications on the HTTP server.
Using Servlets, we can collect input from users through web page forms,
present records from a database or another source, and create web pages
dynamically.

Java Servlets often serve the same purpose as programs implemented using
the Common Gateway Interface (CGI). But Servlets offer several advantages
in comparison with the CGI.
several advantages in comparison with the CGI.

CGI (Common Gateway Interface)


CGI technology enables the web server to call an external program and
pass HTTP request information to the external program to process the
request. For each request, it starts a new process.
Disadvantages of CGI
There are many problems in CGI technology:
•If the number of clients increases, it takes more time for sending the
response.
•For each request, it starts a process, and the web server is limited to start
processes.
•It uses platform dependent language e.g. C, C++, perl.

GRNICA 16
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.

GRNICA 17
The advantages of Servlet are as follows:
•Better performance: because it creates a thread for each request, not
process.
•Portability: because it uses Java language.
•Robust: JVM manages Servlets, so we don't need to worry about the
memory leak, garbage collection, etc.
•Secure: because it uses java language.

GRNICA 18
Servlets Architecture

GRNICA 19
What is a Servlet?
Servlet can be described in many ways, depending on the context.
1.Servlet is a technology i.e. used to create web application.
2.Servlet is an API that provides many interfaces and classes including
documentations.
3.Servlet is an interface that must be implemented for creating any servlet.
4.Servlet is a class that extend the capabilities of the servers and respond to the
incoming request. It can respond to any type of requests.
5.Servlet is a web component that is deployed on the server to create dynamic
web page.

GRNICA 20
6. Servlets are small programs that execute on the server side of a
Web connection.
7. Servlets are server side components that provides a powerful
mechanism for developing server web applications for server side.
8. Just as applets dynamically extend the functionality of a Web
browser, servlets dynamically extend the functionality of a Web
server.
9. Using servlets web developers can create fast and efficient server side
applications and can run it on any servlet enabled web server.
10. Servlet runs entirely inside the Java Virtual Machine.
11. Since the servlet runs on server side so it does not depend on
browser compatibility.

GRNICA 21
Background
• In order to understand the advantages of servlets, you must have a
basic understanding of how Web browsers and servers cooperate to
provide content to a user.

Webserver maps this request to a specific


Requests for a static web page through web file & is returned in a HTTP response to
browser & it will generate the HTTP request to the browser.
appropriate web server.

Client
Server
The HTTP header in response indicate the
type of the content & MIME is used for
this purpose.

GRNICA 22
• But the content of the dynamic web pages need to be generated
dynamically.
• In the early days of the Web, a server could dynamically construct a
page by creating a separate process to handle each client request.
• The process would open connections to one or more databases in
order to obtain the necessary information.
• It communicated with the Web server via an interface known as the
Common Gateway Interface (CGI).
• CGI allowed the separate process to read data from the HTTP
request and write data to the HTTP response.
• However, CGI suffered serious performance problems. It was
expensive in terms of processor and memory resources to create a
separate process for each client request.
GRNICA 23
GRNICA 24
GRNICA 25
The Life Cycle of a Servlet
• init( ), service( ), and destroy( ) are the three methods which are central to the life cycle of a servlet &
one more doGet( ) or doPost( )
• They are implemented by every servlet and are invoked at specific times by the server.
• Let us consider a user scenario to understand when these methods are called.
• First, user enters URL, 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 web server, web server maps this request to a particular servlet.
The servlet is dynamically retrieved & loaded into the address space of the server.

• Third, server invokes init( ) method of the servlet. This method is invoked only when the servlet is first
loaded into memory. It is possible to pass initialization parameters to the servlet so it may configure itself.
• Fourth, the server invokes the service( ) method of the servlet. This method is called to process the
HTTP request. It may also formulate an HTTP response for the client. The service( ) method is called for
each HTTP request.
• Finally, the server may decide to unload the servlet from its memory. The server calls the destroy( )
method to any resources such as file handles that are allocated for the servlet.
GRNICA 26
GRNICA 26
Do Get( ) or doPost( )

• protected void doGet(HttpServletRequest req.HttpServletResponse res)


throws ServletException.IOException

• protected void doPost(HttpServletRequest req.HttpServletResponse res)


throws ServletException.IOException

GRNICA 27
A Simple Servlet
• The basic steps to be followed:
1.Create and compile the servlet source code.
2.Start Tomcat.
3.Start a Web browser and request the servlet.

GRNICA 28
A Simple Servlet Code This The
package contains the class
GenericServlet classes and interfaces
provides functionality
required
that to builditservlets.
makes easy to handle requests and
import java.io.*; responses.
import javax.servlet.*;

public class HelloServlet extends GenericServlet


{println() is used to write some simple
HTMLpublic
sourcevoid
codeservice(ServletRequest
as the HTTP request, ServletResponse
response. response)throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>Hello!");
pw.close(); service method is overridden, handles requests
Enables the servlet to read data that is provided via the
} from a client, inherited from GenericServlet
client request.
} Enables the servlet to formulate a response for the
client.
Call to this method establishes MIMEobtains
getWriter() type ofPrintWriter. Anything written to
the HTTP response. Here MIME
this streamtype is to the client as part of HTTP
is sent
text/html. Browser should interpret the content
response.
as HTML source code.

GRNICA 29
Servlet Packaging
• In a production environment, multiple programmers can be
developing servlets for the same server.
• So, placing all the servlets in the same directory results in a
massive, hard-to-manage collection of classes and risks name
conflicts when two developers choose the same name for a servlet
or a utility class.
• Web applications helps to solve with this problem by dividing
things up into separate directories, each with its own set of
servlets, utility classes, JSP pages, and HTML files.
• Sometimes even a single Web application can be large, we still
need the standard Java solution for avoiding name conflicts:
packages.
The Servlet API (Servlet Packaging)
•javax.servlet
•javax.servlet.http are the two packages that
contains the classes required to build servlet.
• These packages are not part of Java core packages, they are standard
extensions provided by Tomcat.
• The current servlet specification is version 2.4.
• The Servlet API is supported by most Web servers, such as those
from Sun, Microsoft, and others.

 Contains 20 interfaces and 16 classes


 Prevalence of interfaces allows servlet implementation to be customized to
container
Check at http://java.sun.com for the latest information. 31
1. The javax.servlet Package : The javax prefix is used
by the Java programming language for a package of standard Java
extensions. These include extensions such as javax.servlet.
• The javax.servlet package contains a number of interfaces and
classes that establish the framework in which servlets operate.
• The following table summarizes the core interfaces that are provided
in this package.

GRNICA 32
B. The ServletConfig Interface
•All servlets must implement the Servlet interface.
•It allows a servlet to obtain configuration data when it is loaded.
• The methods declared by this interface are summarized here:

33
C. The ServletContext Interface
• ServletContext is a interface which helps us to communicate with
the servlet container.
• It enables servlets to obtain information about their environment.
• Each servlet will have its own ServletConfig.
• The ServetContext is created by the container when the web
application is deployed and after that only the context is available to
each servlet in the web application.

GRNICA 34
• Several of its methods are summarized in table below.

GRNICA 35
D. The ServletRequest Interface
• It enables a servlet to obtain information about a client request.
• Several of its methods are summarized in table below.

GRNICA 36
E. The ServletResponse Interface
• It enables a servlet to formulate a response for a client.
• Several of its methods are summarized in table below.

GRNICA 37
• The following table summarizes the core classes that are provided
in the javax.servlet package.

GRNICA 38
A. The GenericServlet Class
• The GenericServlet class provides implementations of the basic
life cycle methods for a servlet.
• GenericServlet implements the Servlet and ServletConfig
interfaces.
• In addition, a method to append a string to the server log file is
available. The signatures of this method are shown here:
void log(String s)
void log(String s, Throwable e)

• Here, s is the string to be appended to the log, and e is an exception


that occurred.
GRNICA 39
B. The ServletInputStream Class
• The ServletInputStream class extends InputStream. It is
implemented by the server and provides an input stream that a
servlet developer can use to read the data from a client request.
• A method is provided to read bytes from the stream. Its signature is
shown here:
int readLine(byte[ ] buffer, int offset, int size) throws
IOException
• Here, buffer is the array into which size bytes are placed starting at
offset.

GRNICA 40
C. The ServletOutputStream Class
• The ServletOutputStream class extends OutputStream.
• It is implemented by the server and provides an output stream that a
servlet developer can use to write data to a client response.
• A default constructor is defined. It also defines the print( ) and
println( ) methods, which output data to the stream.

D. 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 GRNICA
servlet is unavailable. 41
Reading Servlet Parameters
• The ServletRequest class includes methods that allow you to
read the names and values of parameters that are included in
a client request.
• The example contains two files. A Web page is defined in
PostParameters.htm and a servlet is defined in
PostParametersServlet.java.

GRNICA 42
2. The javax.servlet.http Package
• The javax.servlet.http package contains a number of interfaces and
classes that are commonly used by servlet developers.

GRNICA 43
The HttpServletRequest Interface
• The HttpServletRequest interface is implemented by the server. It
enables a servlet to obtain information about a client request.
• Several of its methods are shown in Table below.

GRNICA 44
GRNICA 45
GRNICA 46
The HttpServletResponse Interface
• The HttpServletResponse interface is implemented by the server. It
enables a servlet to formulate an HTTP response to a client.
• Several constants are defined. These correspond to the different
status codes that can be assigned to an HTTP response.
• For example, SC_OK indicates that the HTTP request succeeded
and SC_NOT_FOUND indicates that the requested resource is not
available.

GRNICA 47
GRNICA 48
GRNICA 49
The HttpSession Interface
• The HttpSession interface is implemented by the server. It enables a
servlet to read and write the state information that is associated with
an HTTP session.

GRNICA 50
GRNICA 51
Simple HTML-Building Utilities
<!DOCTYPE.......>
<HTML>
<HEAD><TITLE>........</TITLE></HEAD>
<BODY>.......</BODY>
</HTML>

• When using servlets to build the HTML, we might be tempted to omit the
DOCTYPE line, virtually all major browsers ignore it even though the HTML
specifications require it.

• The advantage of the DOCTYPE line is that it tells HTML


validators which version of HTML we are using so we
know which specification to check your document against.

• These validators are valuable debugging services, helping us to


catch HTML syntax errors that our browser guesses well, but that
other browsers will have trouble displaying.
• The two most popular online validators are the ones from the
World Wide Web Consortium (http://validator.w3.org/) and from
the Web Design Group
(http://www.htmlhelp.com/tools/validator/).

• They let us submit a URL, then they retrieve the page, check the
syntax against the formal HTML specification, and report any
errors to us.
package coreservlets;
import javax.servlet.*;
import javax.servlet.http.*;

public class ServletUtilities {


public static final String DOCTYPE =
"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " +
"Transitional//EN\">";
public static String headWithTitle(String title) {
return(DOCTYPE + "\n" +
"<HTML>\n" +
"<HEAD><TITLE>" + title + "</TITLE></HEAD>\n");
}
...
}
package coreservlets;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class HelloServlet3 extends HttpServlet {


public void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Hello (3)";
out.println(ServletUtilities.headWithTitle(title)
+
"<BODY BGCOLOR=\"#FDF5E6\">\n" +
"<H1>" + title + "</H1>\n" +
"</BODY></HTML>");
}
}
The SingleThreadModel Interface

It is an interface from javax.servlet package used with Servlets. It is


marker interface(empty interface in java is called marker interface/ no fields
or methods) having no methods. Few servlets may require this to implement.

The servlet programmer should implement SingleThreadModel interface to


ensure that servlet can handle only one request at a time. It is a marker interface,
means have no methods.

First time when a request comes to a Web server for a Servlet, the Web
container loads the Servlet, creates a Servlet object, executes the
callback service() method.
• This means that if a new request comes in while a previous
request is still executing, multiple threads can concurrently be
accessing the same servlet object.
For the other visitor, a thread is created in the same process
(in the same service() method). To be more clear, if 100 requests
come concurrently for the same servlet, 100 threads are created within
the same process (or one process). We know each thread maintains its
own set of instance variables.

• We can prevent multithreaded access by having our servlet


implement the SingleThreadModel interface, as below :

public class YourServlet extends HttpServlet


implements SingleThreadModel
{ ... }

• If we implement this interface, the system guarantees that


there is never more than one request thread accessing a single
instance of our servlet.
The Role of Form Data
If we have come across many situations when we need to pass
some information from our browser to web server and ultimately to
our backend program. The browser uses two methods to pass this
information to web server. These methods are GET Method and
POST Method.
GET Method :
The GET method sends the encoded user information appended
to the page request. The page and the encoded information are
separated by the ?(question mark) symbol as follows −

http://www.test.com/hello?key1 = value1&key2 = value2


The GET method is the default method to pass information from
browser to web server and it produces a long string that appears in
our browser's Location:box.
Never use the GET method if you have password or other
sensitive information to pass to the server.
The GET method has size limitation: only 1024 characters can
be used in a request string.
This information is passed using QUERY_STRING header and
will be accessible through QUERY_STRING environment variable
and Servlet handles this type of requests using doGet() method.

POST Method :
A generally more reliable method of passing information to a
backend program is the POST method. This packages the
information in exactly the same way as GET method, but instead of
sending it as a text string after a ? (question mark) in the URL it
sends it as a separate message..
This message comes to the backend program in the form of the
standard input which we can parse and use for our processing. Servlet
handles this type of requests using doPost()method
Reading Form Data using Servlet
Servlets handles form data parsing automatically using the following
methods depending on the situation −

getParameter() − we call request.getParameter() method to get the


value of a form parameter.

getParameterValues() − Call this method if the parameter appears


more than once and returns multiple values, for example checkbox.

getParameterNames() − Call this method if we want a complete list


of all parameters in the current request.
<HTML><HEAD><TITLE>Collecting Three Parameters
</TITLE>
</HEAD>
<BODY BGCOLOR="#FDF5E6">
<H1 ALIGN="CENTER">Collecting Three Parameters</H1>
<FORM ACTION="ThreeParams">
First Parameter: <INPUT TYPE="TEXT"
NAME="param1"><BR>
Second Parameter: <INPUT TYPE="TEXT"
NAME="param2"><BR>
Third Parameter: <INPUT TYPE="TEXT"
NAME="param3"><BR>
<CENTER><INPUT TYPE="SUBMIT"></CENTER>
</FORM>
</BODY></HTML>
package coreservlets;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class ThreeParams extends HttpServlet {


public void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {

response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Reading Three Request Parameters";
out.println("<HTML>\n" +
"<HEAD><TITLE>" + title + "</TITLE></HEAD>\n" +
"<BODY BGCOLOR=\"#FDF5E6\">\n" +
"<H1 ALIGN=\"CENTER\">" + title + "</H1>\n" +
"<UL>\n" +
" <LI><B>param1</B>: "
+ request.getParameter("param1") + "\n" +
" <LI><B>param2</B>: "
+ request.getParameter("param2") + "\n" +
" <LI><B>param3</B>: "
+ request.getParameter("param3") + "\n" +
"</UL>\n" +
"</BODY></HTML>");
}
}
HANDLING THE CLIENT REQUEST:
HTTP REQUEST HEADERS

• 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, on the other hand, are indirectly set by the browser
and are sent immediately following the initial GET or POST request
line.
HTTP 1.1 Request Headers
• Accept : This header 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 : This header indicates the character sets (e.g.,
ISO-8859-1) the browser can use.
• Accept-Encoding : This header designates the types of
encodings that the client knows how to handle. If the server
receives this header, it is free to encode the page by using one of
the formats specified.
• Accept-Language : This header specifies the client’s preferred
languages in case the servlet can produce results in more than one
language.
• Authorization : This header is used by clients to identify
themselves when accessing password-protected Web pages.
• Connection : This header indicates whether the client can handle
persistent HTTP connections.
• Content-Length : This header is applicable only to POST requests
and gives the size of the POST data in bytes.
• Cookie : This header returns cookies to servers that previously sent

them to the browser.

• Host : In HTTP 1.1, browsers and other clients are required


to specify this header, which indicates the host and port as given in

the original URL.


• If-Modified-Since : This header indicates that the client wants the

page only if it has been changed after the specified date.


• If-Unmodified-Since : This header is the reverse of If-Modified-
Since; it specifies that the operation should succeed only if the
document is older than the specified date.
• Referer : This header indicates the URL of the referring Web
page. For example, if we are at Web page 1 and click on a link to
Web page 2, the URL of Web page 1 is included in the Referer
header when the browser requests Web page 2.
• User-Agent : This header identifies the browser or other client
making the request and can be used to return different content to
different types of browsers.
GENERATING THE SERVER RESPONSE:
HTTP STATUS CODES
• A request from a browser or other client consists of an HTTP
command (usually GET or POST), zero or more request headers, a
blank line, and, only in the case of POST requests, some query data.

A typical request looks like the following:


GET /servlet/SomeName HTTP/1.1
Host: ...
Header2: ...
...
HeaderN:
Blank Line)
Specifying Status Codes
• The HTTP response status line consists of an HTTP version,
a status code, and an associated message.
• Since the message is directly associated with the status code
and the HTTP version is determined by the server, all a
servlet needs to do is to set the status code.
• A code of 200 is set automatically, so servlets don’t usually
need to specify a status code at all. When we want to, we use

response.setStatus, response.sendRedirect, or
response.sendError.
HTTP 1.1 Status Codes

• This section describes the specific status codes available in HTTP


1.1. These codes fall into five general categories:

• 100–199 : Codes in the 100s are informational, indicating that the


client should respond with some other action.

• 200–299 : Values in the 200s signify that the request was


successful.

• 300–399 : Values in the 300s are used for files that have moved
and usually include a Location header indicating the new address.

• 400–499 : Values in the 400s indicate an error by the client.

• 500–599 : Codes in the 500s signify an error by the server.


• 100 (Continue) : If the server receives a request header with a
value of 100, it means that the client is asking if it can send an
attached document in a follow-up request.
• 200 (OK): A value of 200 (SC_OK) means that everything is
fine; the document follows for GET and POST requests.
• This status is the default for servlets; if we don’t use
set Status, we will get 200.

• 202 (Accepted) : A value of 202 (SC_ACCEPTED) tells the


client that the request is being acted upon but processing is
not yet complete.
• 204 (No Content) : A status code of 204 (SC_NO_CONTENT)
stipulates that the browser should continue to display the previous
document because no new document is available.

• 205 (Reset Content) : A value of 205


(SC_RESET_CONTENT) means that there is no new
document but the browser should reset the document view.

• 301 (Moved Permanently) : The 301


(SC_MOVED_PERMANENTLY) status indicates that the
requested document is elsewhere; the new URL for the document is
given in the Location response header. Browsers should
automatically follow the link to the new URL.

• 302 (Found) : This value is similar to 301, except that in


principle the URL given by the Location header should be
interpreted as a temporary replacement, not a permanent one.
• 303 (See Other) : The 303 (SC_SEE_OTHER) status is similar to
301 and 302, except that if the original request was POST, the new
document should be retrieved with GET.
• 304 (Not Modified) : When a client has a cached document, it can
perform a conditional request by supplying an If-Modified-Since
header to signify that it wants the document only if it has been
changed since the specified date.
• A value of 304 (SC_NOT_MODIFIED) means that the cached
version is up-to-date and the client should use it.
• 307 (Temporary Redirect) : It’s a temporary redirection to a new
location.
• 400 (Bad Request) : A 400 (SC_BAD_REQUEST) status indicates
bad syntax in the client request.
• 401 (Unauthorized) : A value of 401 (SC_UNAUTHORIZED)
signifies that the client tried to access a password-protected page but
that the request did not have proper identifying information in the
Authorization header.

• 403 (Forbidden) : A status code of 403 (SC_FORBIDDEN) means


that the server refuses to supply the resource, regardless of
authorization. This status is often the result of bad file or directory
permissions on the server.
• 404 (Not Found) : The infamous 404 (SC_NOT_FOUND) status
tells the client that no resource could be found at that address. This
value is the standard “no such page” response.
• 405 (Method Not Allowed) : A 405
(SC_METHOD_NOT_ALLOWED) value signifies that the request
method (GET, POST, HEAD, PUT, DELETE, etc.) was not allowed
for this particular resource.
• 415 (Unsupported Media Type) : A value of 415
(SC_UNSUPPORTED_MEDIA_TYPE) means that the request had
an attached document of a type the server doesn’t know how to
handle.
• 417 (Expectation Failed) : If the server receives an Expect request
header with a value of 100, it means that the client is asking if it can
send an attached document in a follow-up request.
• In such a case, the server should either respond with this status
(417) to tell the browser it won’t accept the document or use 100
(SC_CONTINUE) to tell the client to go ahead.
• 500 (Internal Server Error) : 500
(SC_INTERNAL_SERVER_ERROR) is the generic “server is
confused” status code.
• It often results from CGI programs or servlets that
crash or return improperly formatted headers.
• 501 (Not Implemented) : The 501 (SC_NOT_IMPLEMENTED)
status notifies the client that the server doesn’t support the
functionality to fulfill the request.

• 503 (Service Unavailable) : A status code of 503


(SC_SERVICE_UNAVAILABLE) signifies that the server cannot
respond because of maintenance or overloading.
• 505 (HTTP Version Not Supported) : The 505
(SC_HTTP_VERSION_NOT_SUPPORTED) code means that the
server doesn’t support the version of HTTP named in the request
line.
GENERATING THE SERVER RESPONSE:
HTTP RESPONSE HEADERS
• The most general way to specify headers is to use the setHeader
method of HttpServletResponse. This method takes two strings:
•The header name and
•The header value
• setHeader(String headerName, String headerValue) : This
method sets the response header with the designated name to the
given value.
• In addition to the general-purpose setHeader method,
HttpServlet-Response also has two specialized methods to set
headers that contain dates and integers:
• setDateHeader(String header, long milliseconds) : This
method saves you the trouble of translating a Java date in
milliseconds since 1970.
• setIntHeader(String header, int headerValue) : This method
spares you the minor inconvenience of converting an int to a String
before inserting it into a header.
• HttpServletResponse also supplies a number of convenience
methods for specifying common headers. These methods are
summarized as follows:
• setContentType(String mimeType) : This method sets the
Content-Type header and is used by the majority of servlets.
• setContentLength(int length) : This method sets the
Content-Length header, which is useful if the browser
supports persistent (keep-alive) HTTP connections.
• addCookie(Cookie c) : This method inserts a cookie into the
Set-Cookie header.
• sendRedirect(String address) : the sendRedirect method
sets the Location header as well as setting the status code to
302.
Understanding HTTP 1.1 Response Headers
Following is a summary of the most useful HTTP 1.1 response
headers:
• Allow : The Allow header specifies the request methods (GET,
POST, etc.) that the server supports. It is required for 405 (Method
Not Allowed) responses. The default service method of servlets
automatically generates this header for OPTIONS requests.
• Cache-Control : This useful header tells the browser or other
client the circumstances in which the response document can safely
be cached. It has the following possible values.
• public : Document is cacheable, even if normal rules (e.g., for
password-protected pages) indicate that it shouldn’t be.
• private : Document is for a single user and can only be stored in
private (nonshared) caches.
• no-cache : Document should never be cached.
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Pragma", "no-cache");
• no-store : Document should never be cached and should not even
be stored in a temporary location on disk. This header is intended to
prevent inadvertent copies of sensitive information.
• must-revalidate : Client must revalidate document with original
server (not just intermediate proxies) each time it is used.
• proxy-revalidate : This is the same as must-revalidate,
except that it applies only to shared caches.
• max-age=xxx : Document should be considered stale after xxx
seconds. This is a convenient alternative to the Expires header but
only works with HTTP 1.1 clients. If both max-age and Expires are
present in the response, the max-age value takes precedence.
• s-max-age=xxx : Shared caches should consider the document
stale after xxx seconds.
• Connection :
• Content-Disposition :
Content-Disposition: attachment; filename=some-file-
name
This header is particularly useful when we send the non-HTML
responses to the clients.
• Content-Encoding :
• Content-Language :
•Content-Length :
•Expires :
•Last-Modified :
•Location :
•Set-Cookie :
•Retry-After :
•Refresh : WWW-Authenticate :
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class ApplesAndOranges extends HttpServlet


{
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("application/vnd.ms-excel");
PrintWriter out = response.getWriter();
out.println("\tQ1\tQ2\tQ3\tQ4\tTotal");
out.println("Apples\t78\t87\t92\t29\t=SUM(B2:E2)");
out.println("Oranges\t77\t86\t93\t30\t=SUM(B3:E3)");
}
}
HANDLING COOKIES

Cookies are small pieces of information that are sent in response


from the web server to the client. Cookies are the simplest technique
used for storing client state.
Cookies are stored on client's computer. They have a lifespan and are
destroyed by the client browser at the end of that lifespan.
Using Cookies for storing client state has one shortcoming though, if
the client has turned of COokie saving settings in his browser then,
client state can never be saved because the browser will not allow the
application to store cookies. 83
Cookies API
Cookies are created using Cookie class present in Servlet API.
Cookies are added to response object using the addCookie()
method. This method sends cookie information over the HTTP
response stream.
getCookies() method is used to access the cookies that are added to
response object.

•Cookies are valuable for tracking user activities.


• For example, assume that a user visits an online store. A cookie
can save the user’s name, address, and other information. The user
does not need to enter this data each time he or she visits the store.
•A servlet can write a cookie to a user’s machine via the
addCookie( )
method of the HttpServletResponse interface.
• 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
GRNICA 85
• The expiration date determines when this cookie is deleted
from the user’s machine.
• If an expiration date is not explicitly assigned to a cookie, it is
deleted when the current browser session ends. Otherwise, the
cookie is saved in a file on the user’s machine.
• The domain and path of the cookie determine when it is
included in the header of an HTTP request.

• There is one constructor for Cookie. It has the signature


shown here:
Cookie(String name, String value)
• Here, the name and value of the cookie are supplied as
GRNICA 86

arguments to the constructor.


GRNICA 87
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, constructs a cookie with a specified name and
String value) value.

GRNICA 88
Servlet Cookies Methods:
Following is the list of useful methods which you can use while
manipulating cookies in servlet.

S.N. Method & Description

1 public void setDomain(String pattern)


This method sets the domain to which cookie applies, for example jnnce.ac.in.

2 public String getDomain()


This method gets the domain to which cookie applies, for example jnnce.ac.in.

3 public void setMaxAge(int expiry)


This method sets how much time (in seconds) should elapse before the cookie expires. If you don't set
this, the cookie will last only for the current session.

4 public int getMaxAge()


This method returns the maximum age of the cookie, specified in seconds, By default,
-1 indicating the cookie will persist until browser shutdown.

5 public String getName()


This method returns the name of the cookie. The name cannot be changed after creation.
6 public void setValue(String newValue)
This method sets the value associated with the cookie.
7 public String getValue()
This method gets the value associated with the cookie.
8 public void setPath(String uri)
This method sets the path to which this cookie applies. If you don't specify a path,
the cookie is returned for all URLs in the same directory as the current page as well
as all subdirectories.
9 public String getPath()
This method gets the path to which this cookie applies.

10 public void setSecure(boolean flag)


This method sets the boolean value indicating whether the cookie should only be
sent over encrypted (i.e. SSL( Secure Sockets Layer)) connections.

11 public void (String purpose)


This method specifies a comment that describes a cookie's purpose. The comment
is useful if the browser presents the cookie to the user.
12 public String getComment()
This method returns the comment describing the purpose of this cookie, or null if the
GRNICA 90
cookie has no comment.
How to create Cookie?
Let's see the simple code to create cookie.
Cookie ck=new Cookie("user","sonoo jaiswal");
//creating cookie object
response.addCookie(ck); //adding cookie in the response

How to delete Cookie?


Let's see the simple code to delete cookie.
It is mainly used to logout or signout the user.
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

GRNICA 91
How to get Cookies?
Let's see the simple code to get all the cookies.
Cookie ck[]=request.getCookies();
for(int i=0; i<ck.length; i++)
{
out.print("<br>"+ck[i].getName()+" "+ck[i].getValue());
//printing name and value of cookie
}

GRNICA 92
Benefits of Cookies
• Identifying a user during an e-commerce session : HTTP cookies
are used by web servers to differentiate users and to maintain data
related to the user during navigation, possibly across multiple visits.

• Remembering usernames and passwords : Cookies let a user log

in to a site automatically, providing a significant convenience for


users of unshared computers.
• Customizing sites : Sites can use cookies to remember user
preferences.
• Focusing advertising : Cookies let the site remember which topics
interest certain users and show advertisements relevant to those
interests.
Sending and Receiving Cookies
Sending Cookies to the Client

• Sending cookies to the client involves three :


1. Creating a Cookie object : We call the Cookie constructor with
a cookie name and a cookie value, both of which are strings.

2. Setting the maximum age : If we want the browser to store the


cookie on disk instead of just keeping it in memory, we use
setMaxAge to specify how long (in seconds) the cookie should be
valid.
3. Placing the Cookie into the HTTP response headers : We use
response.addCookie to accomplish this. If we forget this step, no
cookie is sent to the browser!
Creating a Cookie Object
• We create a cookie by calling the Cookie constructor, which
takes two strings: the cookie name and the cookie value.
• Neither the name nor the value should contain white space or
any of the following characters:
[]()=,"/?@:;

• For example, to create a cookie named userID with a value


a1234,
we would use the following:
Cookie c = new Cookie("userID",
"a1234"); GRNICA 95
Setting the Maximum Age
• If we create a cookie and send it to the browser, by default it
is a session-level cookie: a cookie that is stored in the
browser’s memory and deleted when the user quits the
browser.
• If we want the browser to store the cookie on disk, use
setMaxAge with a time in seconds, as below:
c.setMaxAge(60*60*24*7); // One week

GRNICA 96
Placing the Cookie in the Response Headers
• To send the cookie, insert it into a Set-Cookie HTTP response
header by means of the addCookie method of HttpServletResponse.
• The method is called addCookie, not setCookie, because any
previously specified Set-Cookie headers are left alone and a new
header is set.
• The response headers must be set before any document content is
sent to the client.

• Here is an example:
Cookie userCookie = new Cookie("user", "uid1234");
userCookie.setMaxAge(60*60*24*365);//Store cookie for
1 year
response.addCookie(userCookie);
GRNICA 97
Session Tracking
Session simply means a particular interval of time.
Session Tracking is a way to maintain state (data) of an user. It is also
known as session management in servlet.
Http protocol is a stateless so we need to maintain state using session
tracking techniques. Each time user requests to the server, server treats the
request as the new request. So we need to maintain the state of an user to
recognize to particular user.
HTTP is stateless that means each request is considered as the new
request. It is shown in the figure given below:

Each request is
independent of the
GRNICA 98
previous one.
However, in some applications, it is necessary to save state
information so that information can be collected from several
interactions between a browser and a server. Sessions provide
such a mechanism.
• A session can be created via the getSession( ) method of
HttpServletRequest.
• An HttpSession object is returned. This object can store a set of
bindings that associate names with objects.
• The setAttribute( ), getAttribute( ), getAttributeNames( ), and
removeAttribute( ) methods of HttpSession manage these
bindings.

GRNICA 99
Snooping the server

•Demonstrates how to obtain the server information.


• To display the name of the server we are using the
method getServerName() of theServletRequest interface.
• To display the server port number use the
method getServerPort().
• To display the protocol used, method getProtocol() is used.

• To display the scheme, getScheme() method is used.


•There are three typical solutions to the problem:
1. Cookies
2. URL rewriting, and
3. Hidden form fields.
1. Cookies
•We can use cookies to store an ID for a shopping session; with each
subsequent connection, we can look up the current session ID and
then use that ID to extract information about that session from a
lookup table on the server machine.
By doing this, there would really be two tables:
• one that associates session IDs with user tables, and
• second one The user tables themselves that store user-specific data.
GRNICA 101
2. URL Rewriting
• With this approach, the client appends some extra data on the end of
each URL. That data identifies the session, and the server associates
that identifier with user-specific data it has stored.
• For example, with http://host/path/file.html;jsessionid=a1234, the
session identifier is attached as jsessionid=a1234, so a1234 is the ID
that uniquely identifies the table of data associated with that user.

3. Hidden Form Fields


<INPUT TYPE="HIDDEN" NAME="session" VALUE="a1234">
• This entry means that, when the form is submitted, the specified
name and value are automatically included in the GET or POST
data.
• This hidden field can be used to store information about the session
but has the major disadvantage that it only works if every page is
dynamically generated by a form submission.
GRNICA 102
Session Tracking Basics
Using sessions in servlets involves four basic steps :
1. Accessing the session object associated with the current
Request : Call request.getSession to get an HttpSession object,
which is a simple hash table for storing user-specific data.

2. Looking up information associated with a session : Call


getAttribute on the HttpSession object, cast the return value
to the appropriate type, and check whether the result is null.
3. Storing information in a session : Use setAttribute with a key
and a value.

4. Discarding session data : Call removeAttribute to discard a specific


value. Call invalidate to discard an entire session. Call
logout to log the client out of the Web server and invalidate all
sessions associated with that user GRNICA 103
The Session-Tracking API
Here is a summary of the methods available in the HttpSession class:
• public Object getAttribute(String name) : This method extracts a
previously stored value from a session object. It returns null if no
value is associated with the given name.
• public Enumeration getAttributeNames() : This method returns
the names of all attributes in the session.
• public void setAttribute(String name, Object value) : This
method associates a value with a name. If the object supplied to
setAttribute implements the HttpSessionBindingListener interface,
the object’s valueBound method is called after it is stored in the
session.
• public void removeAttribute(String name) : This method removes
any values associated with the designated name. If the value being
removed implements HttpSessionBindingListener, its valueUnbound
method is called. GRNICA 104
• public void invalidate() : This method invalidates the session and
unbinds all objects associated with it. The sessions are associated
with users (i.e., clients), not with individual servlets or JSP pages.
So, if we invalidate a session, we might be destroying data that
another servlet or JSP page is using.
• public void logout() : This method logs the client out of the Web
server and invalidates all sessions associated with that client.
• public String getId() : This method returns the unique identifier
generated for each session. It is useful for debugging or logging or,
in rare cases, for programmatically moving values out of memory
and into a database.
• public boolean isNew() : This method returns true if the client
(browser) has never seen the session, returns false for preexisting
GRNICA 105
sessions.
• public long getCreationTime() : This method returns the time in
milliseconds since midnight, January 1, 1970 (GMT) at which the
session was first built.
• public long getLastAccessedTime() : This method returns the time

in milliseconds since midnight, January 1, 1970 (GMT) at which


the session was last accessed by the client.
• public int getMaxInactiveInterval() , public void
setMaxInactiveInterval(int seconds) :
•These methods get or set the length of time, in seconds, that a
session should go without access before being automatically
invalidated.

GRNICA 106
In normal Java Application we have to invoke Java Interpter, it
will start through main.?
Servlets have live cycle
Client Request->Container->Invokes the HTTP method automatically

As per the specs of Java, the only standalone program should


implement/have the methods main() so that interpreter will
understand the starting point of execution. If you consider Servlets
it is not standalone program so id doesn’t require main.

GRNICA 107

You might also like