0% found this document useful (0 votes)
11 views25 pages

CH4-Servlet and JSP

The document provides an overview of web applications, focusing on Servlet and JSP technologies. It explains the structure and lifecycle of Servlets, their advantages, and the role of the Servlet container, along with session tracking techniques and cookie management. Additionally, it covers methods for redirecting responses and managing attributes within Servlets.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views25 pages

CH4-Servlet and JSP

The document provides an overview of web applications, focusing on Servlet and JSP technologies. It explains the structure and lifecycle of Servlets, their advantages, and the role of the Servlet container, along with session tracking techniques and cookie management. Additionally, it covers methods for redirecting responses and managing attributes within Servlets.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

Unit

it 4: Servlet and JSP


Web Application
A web application is an application accessible from the web. A web application is composed of web
components like Servlet, JSP, Filter, etc. and other elements such as HTML, CSS, and JavaScript. The
web components typically execute in Web Server and respond to the HTTP request.

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

Life Cycle of a Servlet (Servlet Life Cycle)


The Servlet life cycle mainly goes through four stages,
 Loading a Servlet.
 Initializing the Servlet.
 Request handling.
 Destroying the Servlet.

 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.

Servlet Life Cycle Methods


There are three life cycle methods of a Servlet :

 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.

The following is a typical sequence of events:

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());

// Redirecting using response.sendRedirect()


String name=request.getParameter("name");
//response.sendRedirect("https://www.google.com");//.in/#q="+name);
response.sendRedirect("https://www.google.com/search?q="+name);
}
}
Attribute in Servlet
 An attribute in servlet is an object that can be set, get or removed from one of the following scopes:
1. request scope
2. session scope
3. application scope
 The servlet programmer can pass informations from one servlet to another using attributes.
 It is just like passing object from one class to another so that we can reuse the same object again and
again.
 Attribute specific methods of ServletRequest, HttpSession and ServletContext interface
 There are following 4 attribute specific methods. They are as follows:
1. public void setAttribute(String name,Object object):sets the given object in the application
scope.
2. public Object getAttribute(String name):Returns the attribute for the specified name.
3. public Enumeration getInitParameterNames():Returns the names of the context's initialization
parameters as an Enumeration of String objects.
4. public void removeAttribute(String name):Removes the attribute with the given name from the
servlet context.

Session Tracking in Servlets


 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:

 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.

Using Cookies in Java


 In order to use cookies in java, use a Cookie class that is present in javax.servlet.http package.
 To make a cookie, create an object of Cookie class and pass a name and its value.
 To add cookie in response, use addCookie(Cookie) method of HttpServletResponse interface.
 To fetch the cookie, getCookies() method of Request Interface is used.

Constructor of Cookie class

Cookie() constructs a cookie.


Cookie(String name, String constructs a cookie with a specified name
value) and value.

Methods of Cookie class

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);

//appending the username in the query string


out.print("<a href='./URL_Servlet2?uname="+n+"'>visit</a>");
out.close();

}
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();

//getting value from the query string


String n=request.getParameter("uname");
out.print("Hello "+n);

out.close();

}catch(Exception e){System.out.println(e);}
}
}

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.
 <input type="hidden" name="uname" value="AAABBB">
 It is widely used in comment form of a website. In such case, we store page id or page name in the hidden field
so that each page can be uniquely identified.
 Advantage of Hidden Form Field
1. It will always work whether cookie is disabled or not.
 Disadvantage of Hidden Form Field:
1. It is maintained at server side.
2. Extra form submission is required on each pages.
3. Only textual information can be used.
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: 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();

//Getting the value from the hidden field


String str=request.getParameter("uname");
out.print("Hello "+str);

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.

EX: //File 1: TestUserName.html


<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="./Session_Servlet1" method="get">
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>
</body>
</html>
//File 2: Session_Servlet1.java
publicclass Session_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);

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.

Advantages of JSP over Servlet


 Extension to Servlet : JSP technology is the extension to Servlet technology. We can use all the
features of the Servlet in JSP. In addition to, we can use implicit objects, predefined tags,
expression language and Custom tags in JSP, that makes JSP development easy.
 Easy to maintain: JSP can be easily managed because we can easily separate our business logic
with presentation logic. In Servlet technology, we mix our business logic with the presentation
logic.
 Fast Development: No need to recompile and redeploy. If JSP page is modified, we don't need to
recompile and redeploy the project. The Servlet code needs to be updated and recompiled if we
have to change the look and feel of the application.
 Less code than Servlet: In JSP, we can use many tags such as action tags, JSTL, custom tags, etc. that
reduces the code. Moreover, we can use EL, implicit objects, 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.

The following are the paths followed by a JSP

 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:

<%@ page language="java"contentType="text/html; charset=ISO-8859-1"


pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

Hello World!<br/>
<%
out.println("Your IP address is " + request.getRemoteAddr());
%>
<p>Today's date: <%= (newjava.util.Date()).toLocaleString()%></p>
</body>
</html>

JSP Implicit Objects:

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.

jsp:forward action tag


The jsp:forward action tag is used to forward the request to another resource it may be jsp, html or another
resource.

Syntax of jsp:forward action tag without parameter


<jsp:forward page="relativeURL | <%= expression %>" />

Syntax of jsp:forward action tag with parameter


<jsp:forward page="relativeURL | <%= expression %>">
<jsp:param name="parametername" value="parametervalue | <%=expression%>" />
</jsp:forward>

Example of jsp:forward action tag without parameter


Forwarding the request to the printdate.jsp file.

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>

Example of jsp:forward action tag with parameter


Forwarding the request to the printdate.jsp file with parameter and printdate.jsp file prints the parameter value with
date and time.

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>

jsp:include action tag


The jsp:include action tag is used to include the content of another resource it may be jsp, html or servlet.
The jsp include action tag includes the resource at request time so it is better for dynamic pages because there
might be changes in future.
The jsp:include tag can be used to include static as well as dynamic pages.

Advantage of jsp:include action tag


Code reusability: We can use a page many times such as including header and footer pages in all pages. So it saves
a lot of time.

Difference between jsp include directive and include action

JSP include directive JSP include action


includes resource at translation time. includes resource at request time.
better for static pages. better for dynamic pages.
includes the original content in the generated servlet. calls the include method.

Syntax of jsp:include action tag without parameter


<jsp:include page="relativeURL | <%= expression %>" />

Syntax of jsp:include action tag with parameter


<jsp:include page="relativeURL | <%= expression %>">
<jsp:param name="parametername" value="parametervalue | <%=expression%>" />
</jsp:include>

Example of jsp:include action tag without parameter


In this example, index.jsp file includes the content of the printdate.jsp file.
File: index.jsp
<h2>this is index page</h2>
<jsp:include page="printdate.jsp" />
<h2>end section of index page</h2>

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

The following are the advantages of JavaBean:


o The JavaBean properties and methods can be exposed to another application.
o It provides an easiness to reuse the software components.

Disadvantages of JavaBean

The following are the disadvantages of JavaBean:


o JavaBeans are mutable. So, it can't take advantages of immutable objects.
o Creating the setter and getter method for each property separately may lead to the boilerplate code

jsp:useBean action tag


The jsp:useBean action tag is used to locate or instantiate a bean class. If bean object of the Bean class is
already created, it doesn't create the bean depending on the scope. But if object of bean is not created, it instantiates
the bean.
Syntax of jsp:useBean action tag
<jsp:useBean id= "instanceName" scope= "page | request | session | application"
class= "packageName.className" type= "packageName.className"
beanName="packageName.className | <%= expression >" >
</jsp:useBean>

Attributes and Usage of jsp:useBean action tag

1. id: is used to identify the bean in the specified scope.


2. scope: represents the scope of the bean. It may be page, request, session or application. The default scope is
page.
o page: specifies that you can use this bean within the JSP page. The default scope is page.
o request: specifies that you can use this bean from any JSP page that processes the same request. It
has wider scope than page.
o session: specifies that you can use this bean from any JSP page in the same session whether
processes the same request or not. It has wider scope than request.
o application: specifies that you can use this bean from any JSP page in the same application. It has
wider scope than session.
3. class: instantiates the specified bean class (i.e. creates an object of the bean class) but it must have no-arg
or no constructor and must not be abstract.
4. type: provides the bean a data type if the bean already exists in the scope. It is mainly used with class or
beanName attribute. If you use it without class or beanName, no bean is instantiated.
5. beanName: instantiates the bean using the java.beans.Beans.instantiate() method.

Example of jsp:useBean action tag : invoking the method of the Bean class.

Calculator.java (a simple Bean class)

package com.javatpoint;
public class Calculator{
public int cube(int n){return n*n*n;}
}

index.jsp file

<jsp:useBean id="obj" class="JSPProgram.Calculator"/>


<%
int m=obj.cube(5);
out.print("cube of 5 is "+m);
%>

jsp:setProperty and jsp:getProperty action tags


 The setProperty and getProperty action tags are used for developing web application with Java Bean. In
web devlopment, bean class is mostly used because it is a reusable software component that represents
data.
 The jsp:setProperty action tag sets a property value or values in a bean using the setter method.
 Syntax: jsp:setProperty action tag
<jsp:setProperty name="instanceOfBean" property= "*" |
property="propertyName" param="parameterName" |
property="propertyName" value="{ string | <%= expression %>}"
/>
 EX: jsp:setProperty action tag if you have to set all the values of incoming request in the bean
<jsp:setProperty name="bean" property="*" />
 EX: jsp:setProperty action tag if you have to set value of the incoming specific property
<jsp:setProperty name="bean" property="username" />
 EX: jsp:setProperty action tag if you have to set a specific value in the property
<jsp:setProperty name="bean" property="username" value="Kumar" />

jsp:getProperty action tag


 The jsp:getProperty action tag returns the value of the property.
 Syntax of jsp:getProperty action tag
<jsp:getProperty name="instanceOfBean" property="propertyName" />
 Simple example of jsp:getProperty action tag
<jsp:getProperty name="obj" property="name" />
Example of bean development in JSP
In this example there are 3 pages:
o index.html for input of values
o welocme.jsp file that sets the incoming values to the bean object and prints the one value
o User.java bean class that have setter and getter methods

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;

public void setName(String name){this.name=name;}


public String getName(){return name;}

public void setpassword(String password){this.password=password;}


public String getpassword(){return password;}

public void setemail(String email){this.email=email;}


public String getemail(){return 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-----------------

You might also like