Servlets & JSP
Servlets & JSP
Session is basically a time frame and tracking means
maintaining user data for certain period of time
frame.
HTTP protocol and web servers are stateless.
All requests and responses are independent.
Each request to the web server is treated as a new
request.
Session Tracking is a mechanism used by the
web
container to store session information for a particular
user. It is used to recognize a particular user.
Methods of Session Tracking
1) Cookies
2) Hidden Form Field
3) URL Rewriting
4) HttpSession
Cookies
Cookies are small piece of information sent by web
server in response header and gets stored in browser
side.
A web server assigns a unique session ID to each
web client.
The cookies are used maintain the session. The
client
can disable the cookies.
Hidden Form Field
The hidden form field is used to insert the
information in the webpages and this information is
sent to the server.
These fields are not viewable to the user directly.
For example:
<input type = hidden' name = 'session' value =
'12345' >
URL Rewriting
Append some extra data through URL as request
parameters with every request and response. URL
rewriting is a better way to maintain session’s
management and work for the browsers.
For example:
http://abcserver.com/servlet.html;jsessionid=54321
HttpSession Object
The HttpSession object represents a user session. The
HttpSession interface creates a session between an
HTTP client and HTTP server.
A user session contains information about the user
across multiple HTTP requests.
For example:
HttpSession session = request.getSession( );
Session.setAttribute("username", "password");
Cookies
Cookies are small piece of data on the client
computer that send response from the web server to
client.
They are used to store the client state.
The information which is stored on the client
machine is called cookie.
A Servlet container sends small information to the
web browser. This data is saved by the browser and
later back to the server.
The servlet sends cookies to the browser
using HttpServletResponse.addCookie(javax.servl
et.http.Cookie) method.
Types of Cookies
Two types of cookies presents in Servlets:
1. Non-persistent/session cookie
2. Persistent cookie
Non-persistent/session cookie
Non-persistent cookies do not have an expiry time.
They are valid for a single session only.
The persistent cookies are live till the browser is
open.
They disappear when user closes the browser.
Persistent cookie
Persistent cookies have expiry time parameter. They
are valid for multiple sessions.
They do not disappear when user closes the browser.
They are stored in primary memory of the
computer. They disappear when user logs out or
signs out.
Cookie Class Constructors
Constructor Description
Cookie( ) Constructs the cookie with
default property.
Cookie(String name, Constructs a cookie with
String value) specified name and value.
Cookie Class Methods
Methods Description
public String Returns the name of the
getName( ) cookies.
public String Returns the path of the
getPath( ) server to which the
browser returns the cookie.
public String Returns the value of the
getValue( ) cookie.
public int Returns the maximum age
getMaxAge( ) limit to the cookie,
specified in seconds.
public void Sets the maximum age of
setMaxAge(int the cookies in seconds.
expiry)
public void Allocates a new value to a
setValue(String cookie after the cookie is
newValue) created.
Create a Cookie Object
The constructor of Cookie class creates the cookie
object with corresponding cookie name and
value.
Example
Cookie cookie = new Cookie("username","Surendra");
response.addCookie(cookie);
Reading Cookie Sent from the Browser
The getCookies( ) method is used for getting the cookie.
Example
Cookie[ ] cookies = request.getCookies( ); String
username = null;
for (Cookie cookie : cookies)
{
if("user".equals(cookie.getName( )))
{
username = cookie.getValue();
}
}
Deleting the Cookies
We can remove the cookies from the browser by
setting the cookie expiry time to 0 or -1.
Example
Cookie cookie = new Cookie("user", "");
cookie.setMaxAge(0);
response.addCookie(cookie);
Database Access in Servlets
To access the database in Servlet, load the JDBC
driver and return the Connection object.
The Connection object is used to create
Statement
object.
Before starting with database access through servlet,
make sure that the proper JDBC connection with
database has been setup.
Accessing a Database
Following files are required for accessing the
database:
i. welcome.html
ii. ServletDatabaseDemo.java
iii. web.xml
iv. ojdbc14.jar
OR
RequestDispatcher rd =
request.getRequestDispatcher("index.html");
rd.include(request, response);
Page Redirection
The Page redirection is the process of redirecting the
response to another resource.
It is used to move the document to the new location
for load balancing or simple randomization.
The sendRedirect( ) method is the method of
HttpServletResponse interface.
It is used to redirect response to another resource
(servlet, jsp or HTML file).
For example:
response.sendRedirect("index.html");
Difference between forward( ) method and
sendRedirect( ) method
forward( ) sendRedirect( )
Used to forward the Used to redirect the
resources available resources to different servers
within the server. or domains.
The forward( ) method The sentRedirect( ) method
is executed on the is executed on the client
server side. side.
The forward( ) method It is slower because each
is faster than time a new request is
sendRedirect( ). created, old one is lost.
The transfer of control The transfer of control is
is done by container assigned to the browser and
and client/browser is a new request to the given
not involved. URL is initiated.
Syntax:
<% java code %>
Example : implements JSP scriptlet tag
<html>
<head>
<title>
My First JSP Page
</title>
</head>
<body>
<% out.print("Welcome to JSP world"); %>
</body>
</html>
Output:
Welcome to JSP world
JSP Declaration Tag
JSP declaration tags are used to declare variable
fields and methods.
The declaration tag is placed outside the service
method and inside the Servlet class to make them
class level variable and methods.
Syntax:
<%! Declaration %>
Example : Declaring a method inside Declaration
Tag
<html>
<head>
<title>JSP Declaration Tag</title>
</head>
<body>
<%! int square(int a){
return a * a;
}
%>
<% = "Square of 5 is:
"+square(5) %>
</body>
</html>
Output:
Square of 5 is: 25
JSP Expression Tag
JSP expression tag is used to write the client
response to the output stream.
Expression tag keeps the expression that can be used
as an argument to the output stream method.
Syntax:
<%= Java Expression %>
Example : Displays current date using Expression
tag
<%@page contentType="text/html"
import="java.util.*" %>
<html>
<head>
<title>JSP Expression
Tag</title>
</head>
<body>
<h2>Current Date</h2>
<p>
Today's Date: <%= (new
java.util.Date()).toLocalString() %>
</p>
</body>
</html>
Output
:
Today’s
Date:
03-
Aug-
2016
10:52:2
1
JSP Comments
JSP comment is text or statement that is not
considered by JSP container.
JSP comments are hidden in JSP page source and
ignored by JSP container.
Syntax:
<%-- JSP comment --%>
Example : JSP comment tag
<html>
<head>
<title>JSP Comments</title>
</head>
<body>
<%-- this will hide on JSP page --%>
</body>
</html>
JSP Implicit Object
JSP implicit objects are created by the web container
and available to all JSP pages. They are basically
Java object which also called pre-defined variables.
Object Availability and Uses
request The javax.servlet.http.HttpServletRequ
est object is associated with the request.
response The javax.servlet.http.HttpServletResp
onse object is associated with the
response.
out The javax.servlet.jsp.JspWriter object is
used to send output the client.
session The javax.servlet.http.HttpSession objec
t is associated with the session for the
given client request.
Applicati The javax.servlet.ServletContext object
on is used for the web application.
config The javax.servlet.ServletConfig object is
associated with the Servlet for current
JSP page.
pageCont The javax.servlet.jsp.PageContext objec
ext t encapsulates the environment of a
single request for the current JSP page.
page The page variable is similar to this
reference of Java. It is available
in java.lang.Object class.
exception The Exception object represents
the Throwable object that was thrown by
some other JSP page.
Example : Implementing Request Object
//welcome.html
<html>
<head>
<title>Username & Password</title>
</head>
<body>
<form action="welcome.jsp">
Enter User Name: <input type="text"
name="uname" /> <br>
Enter Password: <input type="text"
name="pass" /> <br>
<input type="submit"
value="Submit"/>
<input type = "submit"
value = "Reset">
</form>
</body>
</html>
//welcome.jsp
<%@ page import = " java.util.* "
%>
<html>
<%
String username =
request.getParameter("uname");
String password =
request.getParameter("pass");
out.print("Welcome: "+username);
%>
</body>
</html>
Example : Implementing session Object
//index.html
<html>
<body>
<form action="session.jsp">
<input type="text" name="uname">
<input type="submit" value="Click
here!"><br/>
</form>
</body>
</html>
//session.jsp
<html>
<head>
<title>Passing Session Variables</title>
</head>
<body>
<%
String name = request.getParameter("uname");
out.print("Welcome "+name);
session.setAttribute("user",name);
<a href="display.jsp">Display Page</a>
%>
</body>
</html>
//display.jsp
<html>
<body>
<%
String
name=(String)session.getAttribute("user");
out.print("Welcome "+name);
%>
</body>
</html>
Example : Implementing config Object
//welcome.html
<form action="welcome.jsp">
<input type="text" name="uname">
<input type="submit" value="Click
here!!"><br/>
</form>
//web.xml
<web-app>
<servlet>
<servlet-name>Welcome</servlet-name>
<jsp-file>/welcome.jsp</jsp-file>
</servlet>
<servlet-mapping>
<servlet-name>Welcome</servlet-name>
<url-pattern>/test</url-pattern>
</servlet-mapping>
</web-app>
//welcome.jsp
<html>
<head>
<title>Config Implicit Object</title>
</head>
<body>
<%
String sname = config.getServletName();
out.print("Servlet Name: "+sname);
%>
</body>
</html>
Form Processing in JSP
Forms are the basic components that help us interact
with web pages.
The form processing became very easy with the help
of JSP. The browser uses the GET
method and POST method for passing the
information to the webserver.
GET Method
The GET method is used to send the encoded user
information appended to the page URL. Each
encoded information is separated by '?' character.
GET is a default method to send information to web
server. We should avoid using GET method to
send sensitive information like as password etc.
For example:
http://www.abcserver.com/hello?key1=value&key2=
value2
GET Method Example
<html>
<head>
<title>Reading data by Using GET
method</title>
</head>
<body>
<h1>GET method</h1>
<ul>
<li><p><b>Name:</b>
<%=
request.getParameter("name")
%>
</p></li>
<li><p><b>City:</b>
<%= request.getParameter("city")%>
</p></li>
<li><p><b>Profession:</b>
<%= request.getParameter("prof")%>
</p></li>
</ul>
</body>
</html>
POST Method
The POST method is used to send large amount of
data on web server. When we want to send any
sensitive data on web page, the POST method should
be used as instead of sending text string in URL, it
sends the encrypted message.
Example: Implementing POST method using Form
//welcome.html
<html>
<head>
<title>Using POST method</title>
</head>
<body>
<h2>Using POST method</h2>
<form action = "welcome.jsp" method = "POST">
Name: <input type = "text" name = "name"/>
City: <input type = "text" name = "city"/>
Job: <input type = "text" name = "job">
<input type = "submit" value = "Submit">
</form>
</body>
</html>
//welcome.jsp
<html>
<head>
<title>JSP page using POST method</title>
</head>
<body>
Name: <%= request.getParameter ("name") %>
City: <%= request.getParameter ("city") %>
Job: <%= request.getParameter ("job") %>
</body>
</html>
Directive Elements
Directives control the processing of the JSP page.
The directive tag instructs the web container at the
time of translating a JSP page into the corresponding
Servlet page.
Attribute Description
import Import list of packages, classes and
interfaces in servlet class
definition.
Example: <%@ page import =
"java.util.Date" %>
extends Used to extend the parent class that
will be generated by Servlet.
Example: <%@ page extends =
"mypackage.DemoClass"%>
language Defines which scripting language
to be used in the page.
Example: <%@ page language
=
"value"%>
session Specifies the JSP page
participating in an HTTP session.
Example: <%@ page session =
"true"%>
buffer Specifies a buffer model to handle
output stream generated by JSP
page.
Example: <%@ page buffer =
"4kb"%>
autoFlush Specifies that buffer should be
flushed automatically. The default
value of autoFlush attribute
is ‘true’.
Example: <%@ page autoFlush =
"false"%>
info Sets the information of the JSP
page which is retrieved later by
using getServletInfo( ) method.
Example: <%@ page info =
"Given by Surendra Maurya"%>
contentType Sets the content of the JSP page.
Example: <%@ page
contentType="text/html"%>
isThreadSafe It is used to define the threading
model for the JSP page which is
generated by Servlet because JSP
and servlet both are thread safe.
Example: <%@ page
isThreadSafe="false"%>
errorPage Define the error page, if any error
generates in current page, it will be
redirected to the error page.
Example: <%@ page
errorPage="erroropage.jsp"%>
isErrorPage Defines whether the current JSP
page is error page or not.
Example: <%@ page
isErrorPage="true" %>
isELIgnored Specifies whether the expression
will be evaluated or not in JSP
page.
Example: <%@ page
isELIngored="true" %>
include directive
The include directive is used to insert a file like a
JSP file, HTML file or text file. It will parse the JSP
elements during the translation phase.
The main advantage of the include directive is
code reusability functionality.
Syntax:
<%@ include file="resourceName" %>
Example
<html>
<head>
<title>Include Directive</title>
</head>
<body>
<%@ include file = "header.jsp">
</body>
</html>
taglib directive
It is used to define a tag library that contains many
custom tags.
JSP technology supports the development of reusable
components called custom actions.
The custom tags can be customized by passing the
attribute from invoking page.
It can be accessed by all the available objects on the
JSP page.
Syntax:
<%@ taglib prefix="prefixOfTag"
uri="uriOfTagLibrary" %>
Example
<html>
<head>
<title>Taglib directive</title>
</head>
<%@ taglib prefix="myTag" uri
="http://www.abcserver.com/java-
technologies.htm" %>
<body>
Welcome, <myTag:userName
/>
</body>
</html>
Exception Handling
Exception is an event that arises during the execution
of the program.
It terminates the program abnormally.
Exception handling is the process of handling the
abnormal termination of the program.
Exception handling in JSP is easier than in Java
technology.
JSP also uses the same exception class object.
Syntax:
<jsp: useBean id="instanceOfBean"
class="package_name.class_name" />
....
....
<jsp:setProperty name="instanceOfBean"
property="property_name" />
The <jsp:getProperty> Action Tag
It is used to return the value of the property.
Syntax:
<jsp:getProperty name="instanceOfBean"
property="propertyName" />
Custom Tags in JSP
Custom tags are user-defined tags.
Custom tags are distributed in a tag library which
defines a set of related custom tags.
They are used to remove the complexity of the
business logic and separate it from the JSP page.
It also provides the code reusability of the custom
tag.
Syntax
1. Create an empty tag:
<prefix:tagname attr1=value1....attrn=valuen />
package com.anyserver.com;
import java.util.Calendar;
import java.io.*;
import
javax.servlet.jsp.JspExceptio
n;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;
public class TagHandlerDemo extends TagSupport
{
public intdoInstantTag() throws JspException
{
JspWriter out=pageContext.getOut();
try
{
out.print("This is custom Tag");
out.print(Calendar.getInstance().getTime());
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Tag Library Descriptor
It is an XML document contained inside the WEB-
INF directory.
It has the information of tag and Tag Handler class.
TDLs are used by the JSP web container to
validate the tags.
<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>2.0</jsp-version>
<short-name>Custom Tag Demo</short-name>
<uri>http://to
mcat.apache.org/example- taglib</uri>
<tag>
<name>WelcomeMsg</name>
<tag-
class>anyserver.com.Details</tag-
class>
<body-content>empty</body-content>
</tag>
</taglib>
Use the Custom tag in the JSP File
The taglib directive in JSP page must specify the path
of the URI (Uniform Resource Identifier) field in
TDL path.