You are on page 1of 105

JSP

Prepared by A.kiran Kumar


Asst Professor
Introduction to JSP: The Anatomy of a JSP Page, JSP Processing, Declarations,
Directives, Expressions, Code Snippets, implicit objects, Using Beans in JSP Pages, Using
Cookies and session for session tracking, connecting to database in JSP.
JSP
• Java Server Pages (JSP) is a server side technology for developing dynamic web
applications.
• A JSP page consists of HTML tags and JSP tags.
• JSP is an API.
• JSP is a Specification.
• JSP is an extension to Servlet because it provides more functionality than servlet such
as JSP elements, expression language, JSTL, Custom tags etc.
• JSP contains Html code and java code. JSP adds Java code inside HTML using JSP
tags.
• Using JSP, one can easily separate Presentation and Business logic in the web
application
• The JSP pages are executed by JSP engine or JSP Container.

• JSP program must be saved with the .jsp extension.


Limitations(problems)of servlet:

• Servlets are excellent in request handling but poor in presentation.


• Code generation tools cannot be used effectively and hence development time
increases and hence cost-effectiveness is lost.
• Parallel development is not possible.
• If we do any changes in a servlet, then we need to do the Re-deployment process
• A Servlet is tightly coupled.

• Servlets do not offer any implicit object.

• If we develop any web application with servlets, then it is mandatory for the web
application developer to configure web.xml file.
Imp points about JSP
• A JSP is a text file with any name but with extension .jsp
• A JSP on its own cannot process a client request.It will be translated in to a servlet
by JSP engine.That container-generated servlet serves the client request.
• Developing a JSP is nothing but another style of developing a servlet.Instead of we
writing a servlet,we instruct the container to write servlet for us

NOTE:

• Every JSP page is converted in to a .java file


• The JSP translator or JSP engine converts .jsp file in to .java file(servlet)
• The .java file is converted in to .class file by JSP engine for this it uses java compiler
Features of JSP or Advantages
1. Extension to Servlet: JSP is an Extension to Servlet, it has all the features of servlet and
it have also implicit objects, predefined tags, expression language, and Custom tags in
JSP
2.Powerful: These are internally Servlet, which means consists of byte code, so that all
java features are applicable in case of JSP like robust, dynamic, secure, and platform
independent.
3. Portable: JSP tags will process and execute by the server-side web container So that
these are browser-independent and j2ee server independent.
4. Flexible: Allows to define custom tags, the developer can fill conferrable to use any
kind, of framework-based markup tags in JSP.
5. Easy to maintain: JSP is easy to learn, easy to understand, and easy to develop.
6. Less code than Servlet: In JSP, we can use a lot of tags such as action tags, jstl,
custom tags, etc. which reduces the code.
7. Fast Development: No need to recompile and redeploy
If the JSP page is modified, we don’t need to recompile and redeploy the project.
8. High Performance and Scalability.
It has high performance and scalability compared to other dynamic web development
tools.
9. platform-independent: JSP is built on Java technology, so it is platform-independent.
10. Loosely coupled: JSP is loosely coupled, and it is good at presenting output.
11.Implicit Objects: One of the advantages of JSP over Servlets is Implicit Objects.
In the end a JSP becomes a Servlet
JSP is an extension of servlets and every JSP page first gets converted into servlet by JSP
container before processing the client’s request.
JSP pages are converted into Servlet by the Web Container. The Container translates a
JSP page into servlet class source(.java) file and then compiles into a Java Servlet class.
Why JSP is preffered over servlets?
•JSP provides an easier way to code dynamic web pages.
•JSP does not require additional files like, java class files, web.xml etc
•Java server pages (JSP)are always compiled before its processed by the server as it reduces the
effort of the server to create process.
•Any change in the JSP code is handled by Web Container(Application server like tomcat),
and doesn't require re-compilation.
•JSP pages can be directly accessed, and web.xml mapping is not required like in
servlets.
The Lifecycle of a JSP Page
What is JSP LifeCycle?
• JSP Life Cycle is defined as the translation of JSP Page into a servlet as a JSP Page
needs to be converted into a servlet first in order to process the service requests.
• Jsp engine /jsp container controls the life cycle of jsp.
The JSP pages follow these phases:
•Translation of JSP Page
•Compilation of JSP Page
•Classloading (the classloader loads class file)
•Instantiation (Object of the Generated Servlet is created).
•Initialization ( the container invokes jspInit() method).
•Request processing ( the container invokes _jspService() method).
•Destroy ( the container invokes jspDestroy() method).
1. Translation of JSP page to Servlet: The process of translating the JSP page (.jsp file) into the
corresponding Servlet(.java file) is called the translation phase.
2. Compilation of JSP page: In this compilation phase, the Translated .java file of the servlet is
compiled into the Java servlet .class file.
3. Classloading: The Servlet class which has been loaded from the JSP source is now loaded into
the container.
4. Instantiation: Here an instance of the Servlet class is generated.
5. Initialization:

jspInit: The jspInit() is used to initialize the servlet instance.

6. Request processing:

jspService(): The _jspService() method is called for each and every request by the JSP container in
the jsp life cycle.

7. Destroy:

jspDestroy(): The jspDestroy() method is to destroy the instance of the servlet .


Do I need to follow the directory structure to run a simple JSP?
No, there is no need of directory structure if you don't have class files or TLD files. For
example, put JSP files in a folder directly and deploy that folder. It will be running fine.
However, if you are using Bean class, Servlet or TLD file, the directory structure is required.
The Directory structure of JSP
The directory structure of JSP page is same as Servlet. We contain the JSP page outside
the WEB-INF folder or in any directory.
For writing JSP code we need to write our code inside Scriptlet Tag:
Syntax:
<%
// JSP code goes here…
%>
Ex : todemonstrate JSP Ex to print Hello Word, we can write the code as mentioned below:
<html>
<head>
<title>JSP Test Page</title>
</head>
<body>
<%
out.println("<h1>Hello World!</h1>");
%>
</body>
</html>
JSP Processing
Explain about JSP Processing
JSP pages can be processed using JSP Container only. Following are the steps that need
to be followed while processing the request for JSP page:
Steps:
1. Client makes a request for the required JSP page to the server. The server must have a
JSP container so that JSP requests can be processed. For instance: let the client makes a
request for xyz.jsp page.
2. On receiving this request the JSP container searches and then reads the desired JSP
page.
3 .The JSP container loads the JSP file and translates the JSP to Servlet. This is done by
converting all the template text into println() statements and JSP elements to Java code.
This process is called translation.
For instance: xyz.jsp is converted to xyzservlet.java
4. The JSP engine compiles the Servlet to an executable .class file. It is forwarded to the
Servlet engine. This process is called the compilation/request processing phase
5. The .class file is executed by the servlet engine, which generates the output as an HTML
file. The servlet engine further passes the output as an HTTP response to the webserver.

6.At last, the webserver forwards the HTML file as a response to the client’s browser.
Explain about Anatomy of JSP PAGE

• JSP page is a simple web page that contains the JSP Elements and Template text
• The template text can be scripting code such as HTML, XML or simple plain text
• The template text is always passed directly to the browser
• The JSP elements can be action tags , custom tags, JSTL library elements
• The JSP elements are responsible for generating dynamic web pages
• When the JSP request gets processed template text and JSP Elements are merged
together and sent to the browser as a response.
MVC in JSP
What is MVC?
MVC stands for Model View and Controller. It is a design pattern that separates the
business logic, presentation logic and data.
Controller acts as an interface between View and Model.
•It receives the requests from the view layer and processes the requests and does the
necessary validation for the request.
•This requests is further sent to model layer for data processing, and once the request is
processed, it sends back to the controller with required information and displayed
accordingly by the view.
Ex: Servlet
Model represents the state of the application i.e. data. It can also have business logic.
The model connects with the database as well and stores the data into a database which
is connected to it.
Ex:Java Bean
View represents the presentaion i.e. UI(User Interface).
Ex: html,jsp
Advantages of MVC Architecture
The advantages of MVC are:
•Easy to maintain
•Easy to extend
•Easy to test
•Navigation control is centralized
Expression Language
Expression Language (EL) in JSP
Expression language (EL) has been introduced in JSP 2.0.
The Expression Language (EL) simplifies the process of accessing data
from bean properties and from implicit objects to produce scriptless JSP Pages.
EL includes arithmetic, relational and logical operators too.
There are many implicit objects, operators, and reserve words in EL.
The syntax for Expression Language (EL)
${ expression }
whatever is present inside braces gets evaluated at runtime and being sent to the output
stream.
JSP EL Implicit Objects

pageContext It represents the PageContext object.

pageScope It is used to access the value of any variable


which is set in the Page scope
requestScope It is used to access the value of any variable
which is set in the Request scope.
sessionScope It is used to access the value of any variable
which is set in the Session scope
applicationScope It is used to access the value of any variable
which is set in the Application scope
param Map a request parameter name to a single
paramValues Map
valuea request parameter name to
corresponding array of string values.

header Map containing header names and single string


values.
headerValues Map containing header names to corresponding
array of string values.

cookie Map containing cookie names and single string


values.
EL param example :index.html
<html>
<body>
<form method="POST" action="welcome.jsp">
Name <input type="text" name="user" >
<input type="submit" value="Submit">
</form>
</body>
</html>
welcome.jsp
html>
<body>
<h1>Welcome ${param.name}</h1> output: welcome cherry
</body>
</html>
EL cookie example
index.jsp
<h1>EL Cookie</h1>
<%
Cookie ck=new Cookie("name",“cherry");
response.addCookie(ck);
%>
<a href="process.jsp">click</a>
process.jsp
Hello, ${cookie.name.value}

Output: Hello cherry


EL sessionScope example
index.jsp
<h3> welcome to EL session scope </h3>
<%
session.setAttribute("user",“cherry");
%>
<a href="process.jsp">visit</a>
process.jsp
Value is ${ sessionScope.user }

Output: welcome to EL session scope


value is cherry
Code Snippets
JSP code snippets:
A code snippet in jsp is a programming term that depicts a small blocks of source code
that is
Reusable.
It can be incorporated in to large programming modules. An editor program adds the code
snippets to the file. It does not require any compiler support. They can be processed
statically.
Ex:
<h1> heading </h1>
<%! Private string randomHeading()
{
return (“<h2>”+math.random()+ “</h2>”);
}
%>
<%=randomHeading()%>
Custom tags in JSP
Custom tags are user-defined tags. They eliminate the possibility of a scriptlet tag and
separate the business logic from the JSP page.
The same business logic can be used many times by the use of a custom tag.
Advantages of Custom Tags
1.Eliminates the need of a scriptlet tag The custom tags eliminate the need of a scriptlet
tag which is considered bad programming approach in JSP.
2.Separation of business logic from JSP The custom tags separate the business logic
from the JSP page so that it may be easy to maintain.
3.Re-usability : custom tags make the possibility to reuse the same business logic again
and again.
Syntax to use custom tag
There are two ways to use the custom tag
<prefix:tagname attr1=value1....attrn=valuen />
<prefix:tagname attr1=value1....attrn=valuen >
body code
</prefix:tagname>
JSP ELEMENTS
Directive Elements
Scripting Elements
Action Elements
Directive elements

The JSP directives are messages that tell the web container how to translate a JSP page
into the corresponding servlet.
• The directive elements are used to do page-related operations during page translation
time.
• Using directive elements we can import some packages and used them to specify
attributes of the page.

Syntax of directive element :

<% @ directive attribute="value" %>


JSP supports 3 types of directive elements, they are;.
• Page directive
• Include directive
• Taglib directive
1. Page Directive
• This directive is used to provide information about the page. It provides attributes of
page.
Some of the attributes are
•import,contentType, extends, info, buffer, language,errorPage and isErrorPage.

Syntax of JSP page directive :<%@ page attribute=“value” %>


1. import: The import attribute is used to import a class, interface, or all the members of a
package. It is similar to import keyword in the java class
Ex: importex.jsp
<html>
<body>
<%@ page import="java.util.Date" %>
Today is: <%= new Date() %>
</body>
2) contentType
The contentType attribute defines the MIME(Multipurpose Internet Mail Extension) type
of the HTTP response.
The default value is "text/
Ex: contentex.jsp
<html>
<body>
<%@ page contentType=“text/html” %>
Today is: <%= new java.util.Date() %>
</body>
</html> output:Today is: Fri Nov 11 20:12:00 IST 2022
3)extends
The extends attribute defines the parent class that will be inherited by the generated
servlet.It is rarely used.
4)info:
This attribute simply sets the information of the JSP page which is retrieved later by using
the getServletInfo() method of the Servlet interface.
Example of info attribute :info.jsp
<html>
<body>
<%@ page info="composed by Cherry" %>
Today is: <%= new java.util.Date() %>
</body>
</html>
The web container will create a method getServletInfo() in the resulting servlet.
For example:
public String getServletInfo()
{
return "composed by Cherry";
}
6) language : The language attribute specifies the scripting language used in the JSP page.

• The default value is "java".


7.buffer: The buffer attribute sets the buffer size in kilobytes to handle output generated by
the JSP page. The default size of the buffer is 8Kb.
Ex: bufferex.jsp
<html>
<body>
<%@ page buffer="16kb" %>
Today is: <%= new java.util.Date() %>
</body>
</html>
9.isErrorPage:
The isErrorPage attribute is used to declare that the current page is the error page.
8) errorPage: The errorPage attribute is used to define the error page, if if exception
occurs in the current page, it will be redirected to the error page.
Example of errorPage attribute
index.jsp
<html>
<body>
<%@ page errorPage="myerrorpage.jsp" %>
<%= 100/0 %>
</body>
</html>
9.isErrorPage
The isErrorPage attribute is used to declare that the current page is the error page.
Example of isErrorPage attribute
//myerrorpage.jsp
<html>
<body>
<%@ page isErrorPage="true" %>
Sorry an exception occured!<br/>
The exception is: <%= exception %>
</body>
</html>
2. Include directive

• The include directive is used to include the contents of any resource it may be jsp file,
html file or text file.

• The include directive is used to provide the name of the file that can be included in the
JSP.

Ex: iam including login.html in include.jsp

Syntax

<%@ include file="resourceName"%>


Advantage of Include directive
• Code Reusability
Ex:To illustrate Include directive In this Ex we are including hai .html in include.jsp

include.jsp

<html>

<body>

<h1> Include JSP </h1>

<%@ include file=“hai.html" %>

</body> </html>

hai.html

<html>
<body> hai h r u</body> output:Include JSP
hai h r u output:
</html>
3. taglib directive:

• The JSP taglib directive is used to define a tag library that defines many tags. We use
the TLD (Tag Library Descriptor) file to define the tags.
• The directive taglib is used to specify the custom tags.
Syntax:

<@ taglib uri="uriofthetaglibrary" prefix="prefixoftaglibrary" %>


Ex:
html>
<body>
<%@ taglib uri="http://www.nareshit.com/tags" prefix="mytag" %>
<mytag:currentDate/>
</body>
</html>
Scripting ELEMENTS
• The scripting elements provide the ability to insert java code inside the JSP.
• There are three types of Scripting elements
1. Scriptlet
2. Declarations
3. Expression
1.Scriptlet:
• In JSP, java code can be written inside the JSP page using the scriptlet tag.
• A scriptlet tag is used to execute java source code in JSP.
Syntax:
<%....
….. java code
%>
Ex1: To illustrate Scriplet tag
<html>
<body>
<% out.print("welcome to jsp"); %> output: welcome to jsp
</body>
</html>
Ex2:Example of JSP scriptlet tag that prints the user name
<html> (index.html )
<body>
<form action="welcome.jsp">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
</body>
</html>
welcome.jsp
<html>
<body>
<%
String name=request.getParameter("uname");
out.print("welcome "+name);
%>
</form>
</body>
</html> output: welcome cherry
2. Declaration:
• The JSP declaration tag is used to declare instance variables and methods.
• The code written inside the JSP declaration tag is placed outside the service() method of the
auto-generated servlet.
Syntax:
< %!
declare the instance variables and methods ;
%>
Ex: To illustrate Declaration : decex.jsp
<html>
<body>
<%! int x=10; %>
<%= "the value is:"+x %> output: the value: is 10
</body>
</html>
3. Expression:
• JSP Expression tag is used to print java expressions on the browsers.

• The code placed within the JSP expression tag is written to the output stream of the
response. So you need not write out. print() to write data. It is mainly used to print the
values of variables or methods.
Syntax:
<%= statement %>
Ex To illustrate Expression tag: Welcome.jsp
<html>
<body>
<%= "welcome to jsp" %> output: welcome to jsp
</body>
</html>
Action Elements or 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.
Using JSP actions
•a file can be inserted into another page dynamically,
•a bean component can be reused,
•a user can be forwarded from one page to another page.
syntax:
• <jsp:action_name attribute = "attribute_value" />
JSP Action Tags or Action Elements
• jsp:forward: is used for forwarding the request and response to other resources.
• jsp:include: is used for including another resource.
• jsp:param: is used for setting the parameter for (forward or include) value.
• jsp:useBean: is used for creating or locating bean objects.
• jsp:setProperty: is used for setting the value of property in the bean object.
• jsp:getProperty: is used for printing the value of the property of the bean.
• jsp:element: is used for defining XML elements dynamically.
• jsp:plugin: is used for embedding other components (applets).
• jsp: fallback can be used to print the message if the plugin is working.
1. 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 forward action tag without the parameter
<jsp:forward page=“Relative URL " />

Syntax: forward action tag with a parameter


<jsp:forward page=“relative URL>">
<jsp:param name="paparametername value=“parameter value/>
</jsp:forward>
Ex: To illustrate forward action with out parameter
index.jsp
<html>
<body>
<h2>this is Forward index page</h2>
<jsp:forward page="printdate.jsp" />
</body>
</html>

Output: Today is:Fri Oct 28 20:58:00 IST 2022


Ex: To illustrate forward action with parameter
In this example, we are 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=“cherry" />
</jsp:forward>
</body>
</html>
2: jsp:include

• The jsp: include action tag is used to include the content of another resource it
may be JSP, HTML, or servlet.

• The jsp: include tag can be used to include static as well as dynamic pages.
Syntax of jsp: include action tag without the parameter
<jsp:include page=“relative URL" />
Syntax of JSP: include action tag with a parameter
<jsp:include page=“relative URL
<jsp:param name="parameter name value="parameter value
</jsp: include>
Advantage
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.
Ex : To illustrate include action without parameter
index.jsp
<h2>this is index page</h2>
<jsp:include page="printdate.jsp" />
<h2>end section of index page</h2>
Printdate.jsp
<% out.print("Today is:"+java.util.Calendar.getInstance().getTime()); %>
3 param action
<jsp: param> tag is used to represent parameter value during jsp forward or include
action this should be the subtag of <jsp: forward> or <jsp: include>.
Syntax
<jsp:param name=“param_name " value=“param_value "/>
Ex : To illustrate param action
index.jsp
<html>
<body>
<h2>this is index page</h2>
<jsp:forward page="printdate.jsp" >
<jsp:param name="name" value=“amazon.com" />
</jsp: forward>
</body>
</html>
printdate.jsp
<html>
<body>
<% out.print("Today is:"+java.util.Calendar.getInstance().getTime()); %>
<%= request.getParameter("name") %>
</body>
</html>

Output:
Today is:Fri Oct 28 21:05:10 IST 2022 amazon.com
Using Beans in JSP Pages
What is java bean?

• A Java Bean is a specialized Java class that is defined according to Java Beans API
Specifications.
• A Java Bean is a plat form independent reusable software component used in
Presentation layer.

Advantages of JavaBean
•It provides an easiness to reuse the software components.
•Java Bean used at client side like development of button, password field screen etc.
•it provides easy maintenance.
A Java Bean is a java class that should follow following conventions or Rules:

1.Java Bean class must be public java class.


2.Java Bean class must have one default constructor.
3.Java Bean class properties must be declared as private.
4.Each Bean property has one public setter method and one public getter method
5. Java Bean class must implement java.io.Serializable interface.
Java bean properties
1. getPropertyName (): we can read data from the bean object.
2. setPropertyName () : we can set the data to the bean object.
How to create bean in JSP
4.jsp:useBean
The jsp:useBean action tag is used to locate or instantiate a bean object.
Syntax:
<jsp:useBean id = "beanName" class = “package.className" scope = "page | request | session |
application"></jsp:useBean>
Example of jsp:useBean action tag
Calculator.java
Package com.nareshit;
public class Calculator
{

public int cube(int n)


{
return n*n*n;
}
}
Attributes of use: bean 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.
1.page: specifies that you can use this bean within the JSP page. The default scope is
page.
2.request: specifies that you can use this bean from any JSP page that processes the
same request.
3.session specifies that you can use this bean from any JSP page in the same
session whether processes the same request or not.
4.application: specifies that you can use this bean from any JSP page in the same
application.
5.class: instantiates the specified bean class (i.e. creates an object of the bean class)
3.type: provides the bean a data type if the bean already exists in the scope. It is mainly
used with class or beanName attribute.
4.Bean name: instantiates the bean using the java.beans.Beans.instantiate() method.
5.jsp:setProperty
The jsp:setProperty action tag sets a value in a bean using the setter method.
Syntax:

<jsp: setProperty name=“instanceOfBean” property=” propertyName”/>

Or

<jsp:setProperty name="userinfo“property="*" />

Ex: <jsp: setProperty name=”bean” property=” firstname”/>


6.jsp:getProperty action tag
The jsp:getProperty action tag get the value of the property.
Syntax
<jsp:getProperty name="instanceOfBean" property="propertyName" />
Ex:
<jsp:getProperty name="obj" property="name" />
Ex To illustrate UseBean,setProperty and getProperty
Details.java
package cmrtc.com;
public class Details
{
public Details()
{
}
private String username;

public String getUsername()


{
return username;
}
public void setUsername(String username)
{
this.username = username;
}
}
index.jsp
<html>
<body>
<form action="userdetails.jsp" method="post">
User Name: <input type="text" name="username"><br>
<input type="submit" value="submit">
</form>
<body>
</html> Output:You have enterted below
details:cherry
userdetails.jsp
<jsp:useBean id="userinfo" class="cmrtc.com.Details">
</jsp:useBean>
<jsp:setProperty property="*" name="userinfo"/>
You have enterted below details:<br>
<jsp:getProperty property="username" name="userinfo"/><br>
JSP Implicit objects
• JSP Implicit Objects are the Java objects that the JSP Container makes available to
developers in each page and developer can call them directly without being explicitly
declared.
• JSP Implicit Objects are also called pre-defined variables.
• One of the advantages of JSP over Servlets is Implicit Objects.
• Implicit objects make JSP coding simple.
• As they are created by JSP container implicitly, they are known as implicit objects.
There are 9 jsp implicit objects.

1.out
2.request
3.response
4.config
5.application
6.session
7.pagecontext
8.page
9.exception
1. JSP out implicit object
JSP provides an implicit object named out. It is the object of JspWriter.
out is one the implicit object to write the data to the buffer and send output to the client
in response.

Example of JSP request implicit object


index.jsp
<html>
<body>
<% out.print("Today is:"+java.util.Calendar.getInstance().getTime()); %>
</body>
</html>
Output: Today is:Fri Oct 28 21:05:10 IST 2022
2.JSP request implicit object
• The JSP request is an implicit object of type HttpServletRequest i.e. created for each jsp
request by the web container.
• It can be used to get request information such as parameters, header information,
remote address, server name, server port, content type, character encoding etc.
• It can also be used to set, get and remove attributes from the jsp request scope.
• It uses the getParameter() method to access request parameter.
Example of JSP request implicit object
index.html
<form action="welcome.jsp">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>

Output: welcome cherry


3.JSP response implicit object
• In JSP, response is an implicit object of type HttpServletResponse. The instance of
HttpServletResponse is created by the web container for each jsp request.
• It can be used to add or manipulate response such as redirect response to another
resource, send error etc.
Example of response implicit object
index.html
<form action="welcome.jsp">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
welcome.jsp
<%
response.sendRedirect("http://www.google.com");
%>
4. JSP config implicit object
config is an implicit object of type ServletConfig The config object is created by the web
container to get the initialization parameter from the web.xml for a particular jsp page.
This config object can be used to get configuration information like username,
password, driver name, servlet name, and servlet context for a JSP page from a web.xml
file.
Methods:
getInitParameter() : to get the initialization parameter from web.xml the file.
getServletName(): It returns the name of the servlet which we define in the web.xml file
Example of config implicit object:
index.html
<form action="welcome">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
web.xml
<web-app>
<servlet>
<servlet-name>sonoojaiswal</servlet-name>
<jsp-file>/welcome.jsp</jsp-file>
<init-param>
<param-name>dname</param-name>
<param-value>sun.jdbc.odbc.jdbcOdbcDriver</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>sonoojaiswal</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>
</web-app>
welcome.jsp
<%
out.print("Welcome "+request.getParameter("uname"));
String driver=config.getInitParameter("dname");
out.print("driver name is="+driver);
%>
5.JSP application implicit object
• In JSP, application is an implicit object of type .
• The instance of ServletContext is created only once by the web container when
application or project is deployed on the server.
• This object can be used to get initialization parameter from configuaration file
(web.xml). It can also be used to get, set or remove attribute from the application scope.
• This initialization parameter can be used by all jsp pages.
Example of application implicit object:
index.html
<form action="welcome.jsp">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
web.xml
<web-app>
<servlet>
<servlet-name>sonoojaiswal</servlet-name>
<jsp-file>/welcome.jsp</jsp-file>
</servlet>
<servlet-mapping>
<servlet-name>sonoojaiswal</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>
<context-param>
<param-name>dname</param-name>
<param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>
</context-param>
</web-app>
welcome.jsp
<%
out.print("Welcome "+request.getParameter("uname"));
String driver=application.getInitParameter("dname");
out.print("driver name is="+driver);
%>
6.session implicit object
• In JSP, session is an implicit object of type HttpSession.The Java developer can use
this object to set,get or remove attribute or to get session information.
• JSP makes use sessions to identify a user across more than one page request or visit to
a Web site and to store information about that user.

Example of session implicit object


index.html
<html>
<body>
<form action="welcome.jsp">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
</body>
</html>
welcome.jsp
<html>
<body>
<%
String name=request.getParameter("uname");
out.print("Welcome "+name);
session.setAttribute("user",name);
<a href="second.jsp">second jsp page</a>
%>
</body>
</html>
7.pageContext implicit object
In JSP, pageContext is an implicit object of type PageContext class.
The pageContext object can be used to set, get or remove attribute from one of the
following scopes:
page
request
session
application
In JSP, page scope is the default scope.
Example of pageContext implicit object
index.html
<html>
<body>
<form action="welcome.jsp">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
</body>
</html>
welcome.jsp
<html> <body>
<%
String name=request.getParameter("uname");
out.print("Welcome "+name);
pageContext.setAttribute("user",name,PageContext.SESSION_SCOPE);
<a href="second.jsp">second jsp page</a>
%>
</body> </html>
second.jsp
<html>
<body>
<%
String name=(String)pageContext.getAttribute("user",PageContext.SESSION_SCOPE);
out.print("Hello "+name);
%>
</body> </html>
8.JSP page implicit object:
page is an implicit object of type Object class.

Page implicit variable hold the currently executes Servlet object for the corresponding
JSP.
Acts as this object for current jsp page
EX:
<%=page.getClass ().getName () %>
<%=page.getServlestInfo ()%>
9.exception implicit object
In JSP, exception is an implicit object of type java.lang.Throwable class.
This object can be used to print the exception. But it can only be used in error pages.
error.jsp
<%@ page isErrorPage="true" %>
<html>
<body>
Sorry following exception occured:<%= exception %>
</body>
</html>
Session tracking
Using cookies and session
Session Handling or Session Management or Session tracing in JSP

Session Handling becomes mandatory when a requested data need to be sustained for
further use. Since http protocol considers every request as a new one, session handling
becomes important.

Following are some of the methods to handle session.

1.Cookies

2.Session

3.URL Rewriting

4.Hidden form fields:


Session Tracking in JSP
• 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
Why use Session Tracking?
To recognize the user It is used to recognize the particular user.

Session Tracking Techniques


There are four techniques used in Session tracking:

Cookies
Hidden Form Field
URL Rewriting
HttpSession
1.JSP Cookies
• Cookies are the text files stored on the client computer/machine for tracking purposes
like login details, file transfer, etc.
• Cookies are mainly used to recognize a user on the web server.
• A cookie can be used to remember the username and password for any site.
• 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.
• A cookie's value can uniquely identify a client, so cookies are commonly used for
session management.
• Size of cookies is 4 kb.
• In JSP cookie is the object of the class javax.servlet.http.Cookie. This class is used to
creates a cookie.
• A JSP can access to the cookies through the request method request.getCookies()
which returns an array of Cookie objects.
Types of Cookies in JSP
There are basically two types of cookies:
1. Persistent cookies: These cookies are also known as permanent cookies. They remain
on the hard drive and persist until the user deletes them or they expire themselves.
2. Session cookies: These cookies are also known as temporary cookies. They get deleted
themselves as soon as the session ends or the browser closes.
Cookie methods:
setDomain(String domain)
•This JSP set cookie is used to set the domain to which the cookie applies
getDomain()
•This JSP get cookie is used to get the domain to which the cookie applies
setMaxAge(int expiry)
•It sets the maximum expiration time to the cookie expires.
intgetMaxAge()
•It returns the maximum age of the cookie in JSP
getName()
•It returns the name of the cookie
setValue(String value)
•Sets the value associated with the cookie
getValue()
•Get the value associated with the cookie
Creating the cookie in JSP
Creating a Cookie object:
You call the Cookie constructor with a cookie name and a cookie value
EX: Cookie cookie = new Cookie("key","value");
Setting the maximum age:
You can use setMaxAge to specify how long (in seconds) the cookie should be valid
Ex: cookie.setMaxAge(60*60*24);
You can use response.addCookie() to add cookies in the HTTP response header as
follows:
EX: response.addCookie(cookie);
Reading Cookies with JSP

To read cookies, you need to create an array of objects by calling


the getCookies( ) method of HttpServletRequest.
Then cycle through the array, and use getName() and getValue() methods to access each
cookie and associated value.
Delete cookies
To delete cookies, set cookie age to zero using setMaxAge() method.
Ex how to create cookie in jsp

Cookie.html

<html>
<body>
<form method = "post" action="cookie1.jsp">
<font>Username<input type = "text" name = "name"></font>
</font><br>
<input type = "submit" name = "submit" value = "submit" >
</form>
</body>
</html>
cookie1.jsp

<%@ page language="java" import="java.util.*"%>


<%
String name=request.getParameter("name");
Cookie cookie = new Cookie ("name",name);
response.addCookie(cookie);
cookie.setMaxAge(50 * 50); //Time is in Minutes
%>
<a href="cookie2.jsp">Continue</a>

Output:

Displaying the value of the Cookie

Hello cherry
2. JSP Session
• In JSP, a session is an implicit object of type HttpSession.The Java developer can use
this object to set, get or remove attributes or to get session information.
• JSP makes use of sessions to identify a user across more than one-page of request or
visit to a Web site and to store information about that user.
• The session is available until the session time out until the client log out. The default
session time is 30 minutes and can configure explicit session time in the web.xml file.
Example of session implicit object
index.html
<html>
<body>
<form action="welcome.jsp">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
</body>
</html>
Methods used HttpSession object
1.setAttribute(String, object):To set a attribute name and attribute value pair in the session object
we use
Ex: session.setAttribute(“uid”,”kiran”);
2.getAttribute(String name):We can get attribute value associated with attribute name by using
the following method
Session.getAttribute(“uid”));
3.invalidate():We can delete the session or end a session by using Invalidate();
Ex: session.invalidate ();

4. getLastAccessedTime: The getLastAccessedTime method is mostly used to notice the last


accessed time of a session.

5.isNew(): This method is used to check either the session is new or not. Boolean value (true or
false) is returned by it.

6. removeAttribute(String name): The objects that are stored in the session can be removed
from the session.
Ex to create session in jsp
index.html
<html>
<body>
<h1> Session Demo</h>
<form action="welcome.jsp">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
</body>
</html>
welcome.jsp
<%@ page language="java" contentType="text/html;"%>
<html>
<body>
<%
String name=request.getParameter("uname");
out.print("Welcome "+name);
session.setAttribute("user",name);
%>
<a href="second.jsp">Display the value</a>
</body>
</html>
second.jsp
<%@ page language="java" contentType="text/html;"%>
<html>
<body>
<h1>Display the session value on this page</h1>
<%
String name=(String)session.getAttribute("user");
out.print("Hello "+name);
%>
</body>
</html>
OUTPUT:
Display the session value on this page
Hello cherry
3.URL REWRITING:
• URL rewriting: In URL rewriting we append some extra information on the end of each
URL that identifies the session.
• If your browser does not support cookies, URL rewriting provides you with another
session tracking alternative. URL rewriting is a method in which the requested URL is
modified to include a session ID.
• URL rewriting works only for Hyperlinks.
• In URL rewriting client state and identity information is stored in every request and
response.

We can send parameter name/value pairs using the following format:


url?name1=value1&name2=value2&??
Drawback: we cannot store sensitive information in URL Rewriting why because it is
visible in Client address bar.
4.Hidden form fields:

An invisible text box of the form page is called a hidden box. When a form page is
submitted, the hidden box value goes to web resource program along with the request
parameter value.

• HTML form hidden input elements are called Hidden Form Fields.
• In hidden form fields the html entry will be like this :
• <input type ="hidden" name = "uid" value="kiran">.
• This means that when you submit the form, the specified name and value will be get
included in get or post method.
• In this session ID information would be embedded within the form as a hidden field and
submitted with the Http POST command.
connecting to database in JSP
Accessing DataBase from JSP page( connecting jsp page to Data Base Mysql)
Step1:
Create a data base named students in Mysql using the following command
Mysql> create Database students;
Mysql>use students;
Then create table named students with field’s sname, saddress.
Mysql> create table students (sname char (10), saddress char (10));
Mysql>Table successfuly created.
Mysql>insert into students values(‘cherry’,’Hyd’);
Mysql> inserted values successfully.
same sddress
Cherry Hyd
Step2:For establishing the connectivity between Jsp and Mysql you have to download

mysql-connector-java-5.1.23-bin.jar and set CLASSPATH using the Environment Variables.

Step3:Create the Directory Structure for the JSP web application in a web-app folder in
tomcat 7.And place all the jsp and html files outside the WEB-INF folder inside the
web-app folder
Step4: create the html program to insert username and address
user.html
<html>
<body>
<form name = "login" method="post" action="proc.jsp">
User Name:
<input type="text" name="sname" ></td>
Address:
<input type="test" name="saddress" ></td>
<input type="submit" name="ok" value="Submit"></td>
</form>
</body>
</html>
Step5: create a jsp page to connect to the database and values should be updated in
database
proc.jsp
<%@ page language="java" import="java.sql.*" %>
<%@ page import="java.io.*" %>
<%
Connection conn=null;
ResultSet rs=null;
Statement stmt=null;
Class.forName ("com.mysql.jdbc.Driver").newInstance();
conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/kiran","root","root");
out.write("connected to the mysql");
stmt=conn.createStatement();
String sname=request.getParameter("sname");
String saddress=request.getParameter("saddress");
stmt.executeUpdate("insert into students(sname,saddress)values ('" + sname +"','"+saddress+"')");
conn.close();
out.write("connection success");
%>
Step6:

start the tomcat server and type the URL in some Browser

http:localhost:8085/user.html

Step7:

you will get output on browser

Output:

Connected to mysql

Connection success

Note: Check in database sname and saddress updated in mysql database

You might also like