CH4-Servlet and JSP
CH4-Servlet and JSP
Servlet Technology:
Servlet technology is used to create a web application (resides at server side and generates a
dynamic web page).
Servlet technology is robust and scalable because of jav
java language.
Before Servlet, CGI (Common Gateway Interface) scripting language was common as a server-
server
side programming language.
There are many interfaces and classes in the Servlet API such as Servlet, GenericServlet,
HttpServlet, ServletRequest, Servle
ServletResponse, etc.
Servlets:
Servlets are small programs that execute on the server side.
Servlets are pieces of Java source code that add functionality to a web server.
Servlet provides full support for sessions
sessions,, a way to keep track of a particular user over
ove time as a
website’s pages are being viewed.
They also can communicate directly with a web server using a standard interface.
Servlets can be created using the javax.servlet and javax.servlet.http packages, which are a
standard part of the Java’s enterp
enterprise edition.
Running servlets requires a server that supports the technologies. Several web serverssupport
Servlets.
The most popular one is the Tomcat- an open source server developed by the Apache
Software Foundation supports Java Servlet.
Advantages of Servlet
There are many advantages of Servlet. 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 com
communication
munication between the threads are low. 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.
Servlet Container
Servlet container, also known as Servlet engine, is an integrated set of objects that provide a run time
environment for Java Servlet components. In simple words, it is a system that manages Java Servlet
componentson top of the Web server to handle the Web client requests.
Services provided by the Servlet container:
Network Services: Loads a Servlet class. The loading may be from a local file system, a remote
file system or other network services. The Servlet container provides the network services over
which the request and response are sent.
Decode and Encode MIME-based messages: Provides the service of decoding and encoding
MIME-based messages.
Manage Servlet container: Manages the lifecycle of a Servlet.
Resource management Manages the static and dynamic resources, such as HTML files,
Servlets, and JSP pages.
Security Service: Handles authorization and authentication of resource access.
Session Management: Maintains a session by appending a session ID to the URL path.
Servlet API
The javax.servlet and javax.servlet.http packages represent interfaces and classes for servlet
api.
The javax.servlet package contains many interfaces and classes that are used by the servlet
or web container. These are not specific to any protocol.
The javax.servlet.http package contains interfaces and classes that are responsible for http
requests only.
Servlet Interface
Servlet interface provides common behavior to all the servlets.
Servlet interface defines methods that all servlets must implement.
Servlet interface needs
eeds to be implemented for creating any servlet (either directly or indirectly).
Servlet interface provides 3 life cycle methods ((init, service destroy) that are used to initialize the
servlet, to service the requests, and to destroy the servlet and 2 non non-life
life cycle methods
(getServletConfig,getServletInfo)
getServletConfig,getServletInfo).
Types of Servlet
GenericServletclass :
o GenericServlet class implements Servlet, ServletConfig and Serializable interfaces.
o It provides the implementation of all the methods of these interfaces except the
service method.
o GenericServlet class can handle any type of request so it is protocol-independent.
independent.
HttpServlet class:
o The HttpServlet class extends the GenericServlet class and implements Serializable
interface.
o HttpServletprovides
provides http specific meth
methods such as doGet, doPost, doHead, doTrace etc
Loading a Servlet:
o The first stage of the Servlet lifecycle involves loading and initializing the Servlet by the
Servlet container.
o The Servlet container performs two operations in this stage :
Loading : Loads the Servlet class
class.
Instantiation : Creates an instance of the Servlet. To create a new instance of
the Servlet, the container uses the no
no-argument constructor.
Initializing a Servlet:
o After the Servlet is instantiated successfully, the Servlet container initializes the
instantiated Servlet object
object. The container initializes
alizes the Servlet object by invoking
the Servlet.init(ServletConfig) method which accepts ServletConfig object reference as
parameter.
o The Servlet container invokes the Servlet.init(ServletConfig) method only once,
immediately after the Servlet.init(ServletConfig) object is instantiated successfully.
This method is used to initialize the resources, such as JDBC datasource.
o Now, if the Servlet fails to initialize, then it informs the Servlet container by throwing
the ServletException or UnavailableException.
Handling request:
o After initialization, the Servlet instance is ready to serve the client requests.
o The Servlet container performs the following operations when the Servlet instance is
located to service a request :
It creates the ServletRequest and ServletResponse objects.
In this case, if this is a HTTP request, then the Web container
creates HttpServletRequest and HttpServletResponse objects which are
subtypes of the ServletRequest and ServletResponse objects respectively.
After creating the reque request
st and response objects it invokes the
Servlet.service(ServletRequest, ServletResponse) method by passing the
request and response objects.
o The service() method while processing the request may throw
the ServletException or UnavailableException or IOException.
Destroying a Servlet:
o When a Servlet container decides to destroy the Servlet, it performs the following
operations,
o It allows all the threads currently running in the service method of the Servlet instance
to complete their jobs and get released.
o After
fter currently running threads have completed their jobs, the Servlet container calls
the destroy() method on the Servlet instance.
o After the destroy() method is executed, the Servlet container releases all the references
of this Servlet instance so that iitt becomes eligible for garbage collection.
init():
The init method is called only once.
It is called only when the servlet is created, and not called for any user requests afterwards.
it is used for one-time
time initializations, just as with the init method of applets
Syntax:
publicvoidinit()throwsServletException{
// Initialization code...
}
service()
method is the main method to perform the actual task.
servlet container (i.e. web server) calls the service() method to handle requests coming from the
client( browsers) and to write the formatted response back to the client.
Each time the server receives a request for a servlet, the server spawns a new thread and calls
service.
service() method checks the HTTP request type (GET, POST, PUT, DELETE, etc.) and calls
doGet, doPost, doPut, doDelete, etc. methods as appropriate.
Syntax:
publicvoidservice(ServletRequest request,ServletResponse response)
throwsServletException,IOException{
}
The doGet() and doPost() are most frequently used methods with in each service request.
destroy() Method
destroy() method is called only once at the end of the life cycle of a servlet.
This method gives your servlet a chance to close database connections, halt background
threads, write cookie lists or hit counts to disk, and perform other such cleanup activities.
After destroy() method is called, the servlet object is marked for garbage collection.
1. A client (e.g., a Web browser) accesses a Web server and makes an HTTP request.
2. The request is received by the Web server and handed off to the servlet container. The servlet
container can be running in the same process as the host Web server, in a different process on the
same host, or on a different host from the Web server for which it processes requests.
3. The servlet container determines which servlet to invoke based on the configuration of its servlets,
and calls it with objects representing the request and response.
4. The servlet uses the request object to find out who the remote user is, what HTTP POST parameters
may have been sent as part of this request, and other relevant data. The servlet performs whatever
logic it was programmed with, and generates data to send back to the client. It sends this data back to
the client via the response object.
5. Once the servlet has finished processing the request, the servlet container ensures that the response is
properly flushed, and returns control back to the host Web server.
SendRedirect in servlet
The sendRedirect() method of HttpServletResponse interface can be used to redirect response to another
resource, it may be servlet, jsp or html file.
It accepts relative as well as absolute URL.
It works at client side because it uses the url bar of the browser to make another request. So, it can
work inside and outside the server.
There are many differences between the forward() method of RequestDispatcher and sendRedirect()
method of HttpServletResponse interface.
EX: //search.html
<html>
<head>
<title>Insert title here</title>
</head>
<body>
<form action="./SearchSerrvlet" method="get">
<input type="text" name="name">
<input type="submit" value="Google Search">
</form>
</body>
</html>
//SearchServlet.java
publicclassSearchSerrvletextendsHttpServlet {
privatestaticfinallongserialVersionUID = 1L;
//…..
protectedvoiddoGet(HttpServletRequest request, HttpServletResponse response) throwsServletException,
IOException {
// TODO Auto-generated method stub
//response.getWriter().append("Served at: ").append(request.getContextPath());
Session Tracking used: To recognize the user It is used to recognize the particular user.
Session Tracking Techniques
There are four techniques used in Session tracking:
1. Cookies
2. Hidden Form Field
3. URL Rewriting
4. HttpSession
Cookies in Servlet
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.
How Cookie works
By default, each request is considered as a new request.
In cookies technique, we add cookie with response from the servlet.
So cookie is stored in the cache of the browser.
After that if request is sent by the user, cookie is added with request by default. Thus, we recognize the user
as the old user.
Method Description
public void setMaxAge(int Sets the maximum age of the cookie in seconds.
expiry)
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 changes the value of the cookie.
value)
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 used to add cookie in
response object.
2. public Cookie[] getCookies():method of HttpServletRequest interface is used to return all the cookies
from the browser.
Disadvantages of cookies
Space character and image are considered invalid.
Security is less.
EX: Referred example of lab-book AddCokkies.java and GetCookies.java
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.
Advantage of URL Rewriting
o It will always work whether cookie is disabled or not (browser independent).
o Extra form submission is not required on each pages.
Disadvantage of URL Rewriting
o It will work only with links.
o It can send Only textual information.
EX: //File 1: TestUserName.html
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="./HF_Servlet1" method="get">
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>
</body>
</html>
//File 2: URL_Servlet1.java
publicclass URL_Servlet1 extendsHttpServlet {
privatestaticfinallongserialVersionUID = 1L;
//…….
protectedvoiddoGet(HttpServletRequest request, HttpServletResponse response)
throwsServletException, IOException {
// TODO Auto-generated method stub
try
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);
}
catch(Exception e){System.out.println(e);}
}
//File 3: URL_Servlet2.java
publicclass URL_Servlet2 extendsHttpServlet {
privatestaticfinallongserialVersionUID = 1L;
//…
protectedvoiddoGet(HttpServletRequest request, HttpServletResponse response)
throwsServletException, IOException {
// TODO Auto-generated method stub
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.close();
}catch(Exception e){System.out.println(e);}
}
}
//File 2: HF_Servlet1.java
publicclass HF_Servlet1 extendsHttpServlet {
privatestaticfinallongserialVersionUID = 1L;
//………
protectedvoiddoGet(HttpServletRequest request, HttpServletResponse response) throwsServletException,
IOException {
// TODO Auto-generated method stub
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String str=request.getParameter("userName");
out.print("Welcome "+str);
try
{
//creating form that have invisible textfield
out.print("<form action='./HF_Servlet2' method='get'>");
out.print("<input type='hidden' name='uname' value='"+str+"'>");
out.print("<input type='submit' value='go'>");
out.print("</form>");
out.close();
}
catch(Exception e)
{System.out.println(e);}
}
//File 3: HF_Servlet2.java
publicclass HF_Servlet2 extendsHttpServlet {
privatestaticfinallongserialVersionUID = 1L;
//…..
protectedvoiddoGet(HttpServletRequest request, HttpServletResponse response) throwsServletException,
IOException {
// TODO Auto-generated method stub
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.close();
}
catch(Exception e)
{System.out.println(e);}
}
}
HttpSession interface
Container creates a session id for each user.
The container uses this id to identify the particular user.
An object of HttpSession can be used to perform two tasks:
1. bind objects
2. view and manipulate information about a session, such as the session identifier, creation time, and last
accessed time.
The HttpServletRequest interface provides two methods to get the object of HttpSession:
1. public HttpSessiongetSession():Returns the current session associated with this request, or if the request
does not have a session, creates one.
2. public HttpSessiongetSession(boolean create):Returns the current HttpSession associated with this
request or, if there is no current session and create is true, returns a new session.
Commonly used methods of HttpSession interface
1. public String getId():Returns a string containing the unique identifier value.
2. public long getCreationTime():Returns the time when this session was created, measured in milliseconds
3. public long getLastAccessedTime():Returns the last time the client sent a request associated with this
session, as the number of milliseconds.
4. public void invalidate():Invalidates this session then unbinds any objects bound to it.
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);
HttpSession session=request.getSession();
session.setAttribute("uname",n);
out.print("<a href='./Session_Servlet2'>visit</a>");
out.close();
}catch(Exception e){System.out.println(e);}
}
}
//File 3: Session_Servlet2.java
publicclass Session_Servlet2 extendsHttpServlet {
privatestaticfinallongserialVersionUID = 1L;
//……..
protectedvoiddoGet(HttpServletRequest request, HttpServletResponse response)
throwsServletException, IOException {
// TODO Auto-generated method stub
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
HttpSession session=request.getSession(false);
String n=(String)session.getAttribute("uname");
out.print("Hello "+n);
out.close();
}catch(Exception e){System.out.println(e);}
}
}
Java Server Pages (JSP)
JSP technology is used to create web application just like Servlet technology.
It can be thought of as an extension to Servlet because it provides more functionality than servlet
such as expression language, JSTL, etc.
A JSP page consists of HTML tags and JSP tags.
The JSP pages are easier to maintain than Servlet because we can separate designing and
development. It provides some additional features such as Expression Language, Custom Tags, etc.
JSP Processing:
The following steps explain how the web server creates the web page using JSP:
As with a normal page, your browser sends an HTTP request to the web server.
The web server recognizes that the HTTP request is for a JSP page and forwards it to a JSP engine.
This is done by using the URL or JSP page which ends with .jsp instead of .html.
The JSP engine loads the JSP page from disk and converts it into a servlet content. This conversion is
very simple in which all template text is converted to println( ) statements and all JSP elements are
converted to Java code that implements the corresponding dynamic behavior of the page.
The JSP engine compiles the servlet into an executable class and forwards the original request to a
servlet engine.
A part of the web server called the servlet engine loads the Servlet class and executes it. During
execution, the servlet produces an output in HTML format, which the servlet engine passes to the web
server inside an HTTP response.
The web server forwards the HTTP response to your browser in terms of static HTML content.
Finally web browser handles the dynamically generated HTML page inside the HTTP response
exactly as if it were a static page.
JSP LIFE CYCLE:
A JSP life cycle can be defined as the entire process from its creation till the destruction which is similar
to a servlet life cycle with an additional step which is required to compile a JSP into servlet.
Compilation
Initialization
Execution
Cleanup
JSP Compilation:
When a browser asks for a JSP, the JSP engine first checks to see whether it needs to compile the page. If
the page has never been compiled, or if the JSP has been modified since it was last compiled, the JSP
engine compiles the page.
The compilation process involves three steps:
Parsing the JSP.
Turning the JSP into a servlet.
Compiling the servlet.
JSP Initialization:
When a container loads a JSP it invokes the jspInit() method before servicing any requests. If you need to
perform JSP-specific initialization, override the jspInit() method:
public void jspInit()
{
// Initialization code...
}
Typically initialization is performed only once and as with the servlet init method, you generally initialize
database connections, open files, and create lookup tables in the jspInit method.
JSP Execution:
This phase of the JSP life cycle represents all interactions with requests until the JSP is destroyed.
Whenever a browser requests a JSP and the page has been loaded and initialized, the JSP engine
invokes the _jspService() method in the JSP.
The _jspService() method takes an HttpServletRequest and an HttpServletResponse as its
parameters as follows:
void _jspService(HttpServletRequest request, HttpServletResponse response)
{
// Service handling code...
}
The _jspService() method of a JSP is invoked once per a request and is responsible for generating the
response for that request and this method is also responsible for generating responses to all seven of
the HTTP methods ie. GET, POST, DELETE etc.
JSP Cleanup:
The destruction phase of the JSP life cycle represents when a JSP is being removed from use by a
container.
The jspDestroy() method is the JSP equivalent of the destroy method for servlets. Override
jspDestroy when you need to perform any cleanup, such as releasing database connections or closing
open files.
The jspDestroy() method has the following form:
public void jspDestroy()
{
// Your cleanup code goes here.
}
Sample JSP Program:
Hello World!<br/>
<%
out.println("Your IP address is " + request.getRemoteAddr());
%>
<p>Today's date: <%= (newjava.util.Date()).toLocaleString()%></p>
</body>
</html>
JSP supports nine automatically defined variables, which are also called implicit objects. These variables
are:
Objects Description
request This is the HttpServletRequest object associated with the request.
response This is the HttpServletResponse object associated with the response to the client.
out This is the PrintWriter object used to send output to the client.
session This is the HttpSession object associated with the request.
application This is the ServletContext object associated with application context.
config This is the ServletConfig object associated with the page.
pageContext This encapsulates use of server-specific features like higher performance JspWriters.
page This is simply a synonym for this, and is used to call the methods defined by the translated
servlet class.
Exception The Exception object allows the exception data to be accessed by designated JSP.
JSP Elements:
1. JSP Comments
2. JSP Scriptlets
3. JSP Expression
4. JSP Directives
5. JSP Declaration
JSP Comments :
JSP Comments Since JSP is built on top of HTML, we can write comments in JSP file like html
comments as <-- This is HTML Comment -->
These comments are sent to the client and we can look it with view source option of browsers.
We can put comments in JSP files as:<%-- This is JSP Comment --%>
This comment is suitable for developers to provide code level comments because these are not
sent in the client response.
JSP Scriptlets
Scriptlet tags are the easiest way to put java code in a JSP page.
A scriptlet tag starts with <% and ends with %>.
Any code written inside the scriptlet tags go into the _jspService() method.
EX:
<%
Date d = new Date();
System.out.println("Current Date="+d);
%>
JSP Expression
Most of the times we print dynamic data in JSP page using out.print() method, this can be done
through JSP Expressions.
JSP Expression starts with <% out.print("Indira"); %>. can be written using JSP Expression as
<%=”Indira” %>
Notice that anything between is sent as parameter to out.print() method.
Scriptlets can contain multiple java statements and always ends with semicolon (;) but expression
doesn’t end with semicolon.
JSP Directives
JSP Directives are used to give special instructions to the container while JSP page is getting
translated to servlet source code.
JSP directives starts with <%@ and ends with %>
It usually has the following form:
<%@ directive attribute="value" %>
For examplepage directive can be used to import the Date class.
A JSP directive affects the overall structure of the servlet class.
There are three types of directive tag:
Directive Description
<%@ page ... %> Defines page-dependent attributes, such as scripting language, error
page, and buffering requirements.
<%@ include ... %> Includes a file during the translation phase.
<%@ taglib ... %> Declares a tag library, containing custom actions, used in the page
JSP Declaration
JSP Declarations are used to declare member methods and variables of servlet class. JSP
Declarations starts with <%! and ends with %>.
For example we can create an int variable in JSP at class level as
<%! public static int count=0; %>
<%! public void Display()
{}
%>
JSP Action Tags
There are many JSP action tags or elements. Each JSP action tag is used to perform some specific tasks.
The action tags are used to control the flow between pages and to use Java Bean. The Jsp action tags are given
below.
JSP Action Description
Tags
jsp:forward forwards the request and response to another resource.
jsp:include includes another resource.
jsp:useBean creates or locates bean object.
jsp:setProperty sets the value of property in bean object.
jsp:getProperty prints the value of property of the bean.
jsp:plugin embeds another components such as applet.
jsp:param sets the parameter value. It is used in forward and include mostly.
jsp:fallback can be used to print the message if plugin is working. It is used in
jsp:plugin.
index.jsp
<html>
<body>
<h2>this is index page</h2>
<jsp:forward page="printdate.jsp" />
</body>
</html>
printdate.jsp
<html>
<body>
<% out.print("Today is:"+java.util.Calendar.getInstance().getTime()); %>
</body>
</html>
index.jsp
<html>
<body>
<h2>this is index page</h2>
<jsp:forward page="printdate.jsp" >
<jsp:param name="name" value="Indira College" />
</jsp:forward>
</body>
</html>
printdate.jsp
<html>
<body>
<% out.print("Today is:"+java.util.Calendar.getInstance().getTime()); %>
<%= request.getParameter("name") %>
</body>
</html>
File: printdate.jsp
<% out.print("Today is:"+java.util.Calendar.getInstance().getTime()); %>
JavaBean
A JavaBean is a Java class that should follow the following conventions:
o It should have a no-arg constructor.
o It should be Serializable.
o It should provide methods to set and get the values of the properties, known as getter and setter methods.
Why use JavaBean?
JavaBean is a reusable software component. A bean encapsulates many objects into one object so that we can
access this object from multiple places. It provides easy maintenance.
Simple example of JavaBean class
//Employee.java
package mypack;
public class Employee implements java.io.Serializable{
private int id;
private String name;
public Employee(){}
public void setId(int id){this.id=id;}
public int getId(){return id;}
public void setName(String name){this.name=name;}
public String getName(){return name;}
}
How to access the JavaBean class?
To access the JavaBean class, we should use getter and setter methods.
package mypack;
public class Test{
public static void main(String args[]){
Employee e=new Employee();//object is created
e.setName("Arjun");//setting value to the object
System.out.println(e.getName());
}}
Note: There are two ways to provide values to the object. One way is by constructor and second is by setter method.
JavaBean Properties
A JavaBean property is a named feature that can be accessed by the user of the object. The feature
can be of any Java data type, containing the classes that you define
A JavaBean property may be read, write, read-only, or write-only. JavaBean features are accessed through
two methods in the JavaBean's implementation class:
getPropertyName ()
For example, if the property name is firstName, the method name would be getFirstName() to read that
property. This method is called the accessor.
2. setPropertyName ()
For example, if the property name is firstName, the method name would be setFirstName() to write that
property. This method is called the mutator.
Advantages of JavaBean
Disadvantages of JavaBean
Example of jsp:useBean action tag : invoking the method of the Bean class.
package com.javatpoint;
public class Calculator{
public int cube(int n){return n*n*n;}
}
index.jsp file
index.html
<form action="process.jsp" method="post">
Name:<input type="text" name="name"><br>
Password:<input type="password" name="password"><br>
Email:<input type="text" name="email"><br>
<input type="submit" value="register">
</form>
process.jsp
<jsp:useBean id="u" class="JSPPrograms.User"></jsp:useBean>
<jsp:setProperty property="*" name="u"/>
Record:<br>
<jsp:getProperty property="name" name="u"/><br>
<jsp:getProperty property="password" name="u"/><br>
<jsp:getProperty property="email" name="u" /><br>
<a href="second.jsp">Visit Page</a>
User.java
package JSPPrograms;
public class User {
private String name,password,email;
second.jsp
<jsp:useBean id="u" class="JSPPrograms.User" scope="session"></jsp:useBean>
Record:<br>
<jsp:getProperty property="name" name="u"/><br>
<jsp:getProperty property="password" name="u"/><br>
<jsp:getProperty property="email" name="u" /><br>
WEBLINKS:
https://www.geeksforgeeks.org/life-cycle-of-a-servlet/?ref=header_search
https://www.geeksforgeeks.org/introduction-java-servlets/
https://www.geeksforgeeks.org/introduction-java-servlets/
https://www.javatpoint.com/life-cycle-of-a-servlet
----------------xxxxxxxxxxxxx-----------------