Вы находитесь на странице: 1из 75

22-11-2019 Java Server Pages

Introduction to Java Server Pages

JavaServer Pages is a technology for developing web pages that include dynamic content.
Unlike a plain HTML page, which contains static content that always remains the same, a
JSP page can change its content based on any number of variable items, including the
identity of the user, the user's browser type, information provided by the user, and
selections made by the user.

A JSP page contains standard markup language elements, such as HTML tags, just like a
regular web page. However, a JSP page also contains special JSP elements that allow the
server to insert dynamic content in the page. JSP elements can be used for a variety of
purposes, such as retrieving information from a database or registering user preferences.
When a user asks for a JSP page, the server executes the JSP elements, merges the results
with the static parts of the page, and sends the dynamically composed page back to the
browser.

JSP defines a number of standard elements that are useful for any web application, such
as accessing JavaBeans components, passing control between pages and sharing
information between requests, pages, and users. Developers can also extend the JSP
syntax by implementing application-specific elements that perform tasks such as
accessing databases and Enterprise JavaBeans, sending email, and generating HTML to
present application-specific data. One such set of commonly needed custom elements is
defined by a specification related to the JSP specification: the JSP Standard Tag Library
(JSTL) specification. The combination of standard elements and custom elements allows for
the creation of powerful web applications.

Why JSP

JavaServer Pages often serve the same purpose as programs implemented using
the Common Gateway Interface (CGI). But JSP offers several advantages in comparison
with the CGI.

Deependra Rastogi, Assistant Professor, SCSE, Galgotia University Page 1


22-11-2019 Java Server Pages

 Performance is significantly better because JSP allows embedding Dynamic Elements


in HTML Pages itself instead of having separate CGI files.
 JSP are always compiled before they are processed by the server unlike CGI/Perl
which requires the server to load an interpreter and the target script each time the
page is requested.
 JavaServer Pages are built on top of the Java Servlets API, so like Servlets; JSP also
has access to all the powerful Enterprise Java APIs, including JDBC, JNDI, EJB,
JAXP, etc.
 JSP pages can be used in combination with servlets that handle the business logic,
the model supported by Java servlet template engines.
Finally, JSP is an integral part of Java EE, a complete platform for enterprise class
applications. This means that JSP can play a part in the simplest applications to the most
complex and demanding.
 Embedding Dynamic Elements in HTML Pages
JSP tackles the problem from the other direction. Instead of embedding HTML in
programming code, JSP lets you embed special active elements into HTML pages.
These elements look similar to HTML elements, but behind the scenes they are
actually componentized Java programs that the server executes when a user requests
the page. Here's a simple JSP page that illustrates this:

<%@page contentType="text/html" pageEncoding="UTF-8"%>


<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Example 1</title>
</head>
<body>
<jsp:useBean id="clock" class="java.util.Date" />
<c:choose>
<c:when test="${clock.hours < 12}">
<h1>Good morning!</h1>
</c:when>
<c:when test="${clock.hours < 18}">
<h1>Good day!</h1>
</c:when>
<c:otherwise>

Deependra Rastogi, Assistant Professor, SCSE, Galgotia University Page 2


22-11-2019 Java Server Pages

<h1>Good evening!</h1>
</c:otherwise>
</c:choose>
Welcome to our site, open 24 hours a day.
</body>
</html>

Output

This page inserts a different message to the user based on the time of day: "Good
morning!" if the local time is before 12 P.M., "Good day!" if between 12 P.M. and 6
P.M., and "Good evening!" otherwise. When a user asks for this page, the JSP
enabled web server executes the logic represented by the highlighted JSP elements
and creates an HTML page that is sent back to the user's browser. For example, if the
current time is 8:53 P.M., the resulting page sent from the server to the browser.

 Compilation
Another benefit that is important to mention is that a JSP page is always compiled
before it's processed by the server. Remember that older technologies such as
CGI/Perl require the server to load an interpreter and the target script each time
the page is requested. JSP gets around this problem by compiling each JSP page into
executable code the first time it's requested (or on demand), and invoking the
resulting code directly on all subsequent requests. When coupled with a persistent
Java virtual machine on a JSP-enabled web server, this allows the server to handle JSP
pages much faster.

 Using the Right Person for Each Task


JSP allows you to separate the markup language code, such as HTML, from the
programming language code used to process user input, access databases, and
perform other application tasks. One way this separation takes place is through the
use of the JSP standard and custom elements; these elements are implemented with
programming code and used the same way as page markup elements in regular web
pages.
Another way to separate is to combine JSP with other J2EE technologies. For
example, Java servlets can handle input processing, Enterprise JavaBeans (EJB) can
take care of the application logic, and JSP pages can provide the user interface.
Deependra Rastogi, Assistant Professor, SCSE, Galgotia University Page 3
22-11-2019 Java Server Pages

This separation means that with JSP, a typical business can divide its efforts among
two groups that excel in their own areas of expertise: a Java web development team
with programmers who implement the application logic as servlets, EJBs and custom
JSP elements, and page authors who craft the specifics of the interface and use the
powerful custom elements without having to do any programming. While the second
half is for programmers who wish to combine JSP with other technologies and create
their own JSP elements.

 Integration with Enterprise Java APIs


Finally, because JavaServer Pages are built on top of the Java Servlets API, JSP has
access to all the powerful Enterprise Java APIs, including:
• JDBC
• Remote Method Invocation (RMI) and OMG CORBA support
• JNDI (Java Naming and Directory Interface)
• Enterprise JavaBeans (EJB)
• JMS (Java Message Service)
• JTA (Java Transaction API)
• JAXP (Java API for XML Processing)
• JAXR (Java API for XML Registries), JAX-RPC (Java API for XML-based RPC), and
SAAJ (SOAP with Attachments API for Java)
• JavaMail
This means that you can easily integrate JavaServer Pages with your existing Java
Enterprise solutions.

Deependra Rastogi, Assistant Professor, SCSE, Galgotia University Page 4


22-11-2019 Java Server Pages

The Problem with Servlet

Java servlet-based applications, processing the request and generating the response are
both handled by a single servlet class. Example shows how a servlet class often looks.

The point is that the servlet contains request processing and business logic (implemented
by methods such as isOrderInfoValid() and saveOrderInfo( )), and also generates the
response HTML code, embedded directly in the servlet code using println( ) calls. A more
structured servlet application isolates different pieces of the processing in various reusable
utility classes and may also use a separate class library for generating the actual HTML
elements in the response. Even so, the pure servlet based approach still has a few
problems:

 Thorough Java programming knowledge is needed to develop and maintain all


aspects of the application, since the processing code and the HTML elements are
lumped together.

 Changing the look and feel of the application, or adding support for a new type of
client (such as a WML client), requires the servlet code to be updated and
recompiled.

Deependra Rastogi, Assistant Professor, SCSE, Galgotia University Page 5


22-11-2019 Java Server Pages

 It's hard to take advantage of web page development tools when designing the
application interface. If such tools are used to develop the web page layout, the
generated HTML must then be manually embedded into the servlet code, a process
which is time consuming, error prone, and extremely boring.

Adding JSP to the puzzle lets you solve these problems by separating the request processing
and business logic code from the presentation. Instead of embedding HTML in the code,
place all static HTML in a JSP page, just as in a regular web page, and add a few JSP
elements to generate the dynamic parts of the page. The request processing can remain the
domain of the servlet, and the business logic can be handled by JavaBeans and EJB
components.

Deependra Rastogi, Assistant Professor, SCSE, Galgotia University Page 6


22-11-2019 Java Server Pages

Servlet vs JSP

SERVLET JSP

A servlet is a server-side program and JSP is an interface on top of Servlets. In another


written purely on Java. way, we can say that JSPs are extension of servlets
to minimize the effort of developers to write User
Interfaces using Java programming.

Servlets run faster than JSP JSP runs slower because it has the transition phase
for converting from JSP page to a Servlet file. Once
it is converted to a Servlet then it will start the
compilation

Executes inside a Web server, such as A JSP program is compiled into a Java servlet
Tomcat before execution. Once it is compiled into a
servlet, it's life cycle will be same as of servlet. But,
JSP has it's own API for the lifecycle.

sReceives HTTP requests from users and Easier to write than servlets as it is similar to
provides HTTP responses HTML.

We can not build any custom tags One of the key advantage is we can build custom
tags using JSP API (there is a separate package
available for writing the custom tags) which can be
available as the re-usable components with lot of
flexibility

Servlet has the life cycle methods init(), JSP has the life cycle methods of jspInit(),
service() and destroy() _jspService() and jspDestroy()

Written in Java, with a few additional JSPs can make use of the Javabeans inside the web
APIs specific to this kind of processing. pages
Since it is written in Java, it follows all the
Object Oriented programming
techniques.

In MVC architecture Servlet acts as In MVC architecture JSP acts as view.


controller.

Servlet advantages include: JSP Provides an extensive infrastructure for:


1. Performance : get loaded upon first 1. Tracking sessions.

Deependra Rastogi, Assistant Professor, SCSE, Galgotia University Page 7


22-11-2019 Java Server Pages

SERVLET JSP

request and remains in memory 2. Managing cookies.


idenfinately. 3. Reading and sending HTML headers.
2. Simplicity : Run inside controlled 4. Parsing and decoding HTML form data.
server environment. No specific client 5. JSP is Efficient: Every request for a JSP is
software is needed:web broser is enough handled by a simple Java thread
3. Session Management : overcomes 6. JSP is Scalable: Easy integration with other
HTTP's stateless nature backend services
4. Java Technology : network 7. Seperation of roles: Developers, Content
access,Database connectivity, j2ee Authors/Graphic Designers/Web Masters
integration

JSP Life Cycle


JSP Life Cycle is defined as translation of JSP Page into servlet as a JSP Page needs to be
converted into servlet first in order to process the service requests. The Life Cycle starts
with the creation of JSP and ends with the disintegration of that.

When client makes a request to Server, it first goes to container. Then container checks
whether the servlet class is older than jsp page( To ensure that the JSP file got modified). If
this is the case then container does the translation again (converts JSP to Servlet) otherwise
it skips the translation phase (i.e. if JSP webpage is not modified then it doesn’t do the
translation to improve the performance as this phase takes time and to repeat this step
every time is not time feasible).

The steps in the life cycle of jsp page are:

1. Translation
2. Compilation
3. Loading
4. Instantiation
5. Initialization
6. RequestProcessing
7. Destruction

Deependra Rastogi, Assistant Professor, SCSE, Galgotia University Page 8


22-11-2019 Java Server Pages

Deependra Rastogi, Assistant Professor, SCSE, Galgotia University Page 9


22-11-2019 Java Server Pages

Let us have more detailed summary on the above points:

1. Translation of the JSP Page:

A Java servlet file is generated from a JSP source file. This is the first step of JSP life cycle. In
translation phase, container validates the syntactic correctness of JSP page and tag files.

 The JSP container interprets the standard directives and actions, and the custom
actions referencing tag libraries used in this JSP page.
 In the above pictorial description, demo.jsp is translated to demo_jsp.java in the first
step
 Let's take an example of "demo.jsp" as shown below:

demo.jsp

1. <html>
2. <head>
3. <title>Demo JSP</title>
4. </head>
5. <%
6. int demvar=0;%>
7. <body>
8. Count is:
9. <% Out.println(demovar++); %>
10. <body>
11. </html>

Code Explanation for Demo.jsp

Code Line 1: html start tag


Code Line 2: Head tag
Code Line 3 - 4: Title Tag i.e. Demo JSP and closing head tag
Code Line 5,6: Scriptlet tag wherein initializing the variable demo
Code Line 7 - 8: In body tag, a text to be printed in the output (Count is: )
Code Line 9: Scriplet tag where trying to print the variable demovar with incremented value
Code Line 10-11: Body and HTML tags closed

Deependra Rastogi, Assistant Professor, SCSE, Galgotia University Page 10


22-11-2019 Java Server Pages

Demo JSP Page is converted into demo_jsp servlet in the below code.

Code explanation for Demo_jsp.java


Code Line 1: Servlet class demo_jsp is extending parent class HttpServlet
Code Line 2,3: Overriding the service method of jsp i.e. _jspservice which has
HttpServletRequest and HttpServletResponse objects as its parameters
Code Line 4: Opening method
Code Line 5: Calling the method getWriter() of response object to get PrintWriterobject
(prints formatted representation of objects to text output stream)
Code Line 6: Calling setContentType method of response object to set the content type
Code Line 7: Using write () method of PrintWriter object trying to parse html
Code Line 8: Initializing demovar variable to 0
Code Line 9: Calling write() method of PrintWriter object to parse the text
Code Line 10: Calling print() method of PrintWriter object to increment the variable
demovar from 0+1=1.Hence, the output will be 1
Code Line 11: Using write() method of PrintWriter object trying to parse html
Output:

Here you can see that in the screenshot theOutput is 1 because demvar is initialized to 0
and then incremented to 0+1=1

In the above example,

Deependra Rastogi, Assistant Professor, SCSE, Galgotia University Page 11


22-11-2019 Java Server Pages

 demo.jsp, is a JSP where one variable is initialized and incremented. This JSP is
converted to the servlet (demo_jsp.class ) wherein the JSP engine loads the JSP Page
and converts to servlet content.
 When the conversion happens all template text is converted to println() statements
and all JSP elements are converted to Java code.

This is how a simple JSP page is translated into a servlet class.

2. Compilation of the JSP Page

 The generated java servlet file is compiled into java servlet class
 The translation of java source page to its implementation class can happen at any
time between the deployment of JSP page into the container and processing of the
JSP page.
 In the above pictorial description demo_jsp.java is compiled to a class file
demo_jsp.class

3. Classloading

Servlet class that has been loaded from JSP source is now loaded into the container

4. Instantiation

 In this step the object i.e. the instance of the class is generated.
 The container manages one or more instances of this class in the response to
requests and other events. Typically, a JSP container is built using a servlet container.
A JSP container is an extension of servlet container as both the container support JSP
and servlet.
 A JSP Page interface which is provided by container provides init() and destroy ()
methods.
 There is an interface HttpJSPPage which serves HTTP requests, and it also contains
the service method.

5. Initialization

public void jspInit()


{
//initializing the code
}

Deependra Rastogi, Assistant Professor, SCSE, Galgotia University Page 12


22-11-2019 Java Server Pages

 _jspinit() method will initiate the servlet instance which was generated from JSP and
will be invoked by the container in this phase.
 Once the instance gets created, init method will be invoked immediately after that
 It is only called once during a JSP life cycle, the method for initialization is declared as
shown above

6. Request processing

void _jspservice(HttpServletRequest request HttpServletResponse response)


{
//handling all request and responses
}

 _jspservice() method is invoked by the container for all the requests raised by the JSP
page during its life cycle
 For this phase, it has to go through all the above phases and then only service
method can be invoked.
 It passes request and response objects
 This method cannot be overridden
 The method is shown above: It is responsible for generating of all HTTP methods
i.eGET, POST, etc.

7. Destroy

public void _jspdestroy()


{
//all clean up code
}

 _jspdestroy() method is also invoked by the container


 This method is called when container decides it no longer needs the servlet instance
to service requests.
 When the call to destroy method is made then, the servlet is ready for a garbage
collection
 This is the end of the life cycle.
 We can override jspdestroy() method when we perform any cleanup such as
releasing database connections or closing open files.

Deependra Rastogi, Assistant Professor, SCSE, Galgotia University Page 13


22-11-2019 Java Server Pages

The Anatomy of a JSP Page


A JSP page is simply a regular web page with JSP elements for generating the parts that differ for each
request, as shown in figure

Everything in the page that isn't a JSP element is called template text. Template text can be
any text: HTML, WML, XML, or even plain text. It can be used with any markup language.
Template text is always passed straight through to the browser.
When a JSP page request is processed, the template text and dynamic content generated
by the JSP elements are merged, and the result is sent as the response to the browser.

Deependra Rastogi, Assistant Professor, SCSE, Galgotia University Page 14


22-11-2019 Java Server Pages

JSP Elements

JSP Declaration

 A declaration tag is a piece of Java code for declaring variables, methods and classes.
If we declare a variable or method inside declaration tag it means that the
declaration is made inside the servlet class but outside the service method.
 We can declare a static member, an instance variable (can declare a number or
string) and methods inside the declaration tag.

Syntax of declaration tag:


<%! Dec var %>

Here Dec var is the method or a variable inside the declaration tag.

Example:
In this example, we are going to use the declaration tags
1. <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
2. pageEncoding="ISO-8859-1"%>
3. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
4. <html>
5. <head>
6. <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
7. <title>Declaration Tag</title>
8. </head>
9. <body>
10. <%! int count =10; %>
11. <% out.println("The Number is " +count); %>
12. </body>
13. </html>

Explanation the code:


Code Line 10: Here we are using declaration tag for initializing a variable count to 10.
When you execute the above code you get the following output:

Deependra Rastogi, Assistant Professor, SCSE, Galgotia University Page 15


22-11-2019 Java Server Pages

JSP Scriptlet

 Scriptlet tag allows to write Java code into JSP file.


 JSP container moves statements in _jspservice() method while generating servlet
from jsp.
 For each request of the client, service method of the JSP gets invoked hence the code
inside the Scriptlet executes for every request.
 A Scriptlet contains java code that is executed every time JSP is invoked.

Syntax of Scriptlet tag:

<% java code %>

Here <%%> tags are scriplets tag and within it, we can place java code.

Example:

In this example, we are taking Scriptlet tags which enclose java code.

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


2. pageEncoding="ISO-8859-1"%>
4. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
5. <html>
6. <head>
7. <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
8. <title>Scriplet</title>
9. </head>
10. <body>
11. <% int num1=10;
12. int num2=40;
13. int num3 = num1+num2;
14. out.println("Scriplet Number is " +num3);
15. %>
16. </body>
17. </html>

Explanation of the code:

Code Line 10-14: In the Scriptlet tags where we are taking two variables num1 and num2 .
Third variable num3 is taken which adds up as num1 and num2.The output is num3.

Deependra Rastogi, Assistant Professor, SCSE, Galgotia University Page 16


22-11-2019 Java Server Pages

When you execute the code, you get the following output:

JSP Expression

 Expression tag evaluates the expression placed in it.


 It accesses the data stored in stored application.
 It allows create expressions like arithmetic and logical.
 It produces scriptless JSP page.

Syntax:

<%= expression %>

Here the expression is the arithmetic or logical expression.

Example:

In this example, we are using expression tag

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


2. pageEncoding="ISO-8859-1"%>
3. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
4. <html>
5. <head>
6. <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
7. <title>Expression</title>
8. </head>
9. <body>
10. <% out.println("The expression number is "); %>
11. <% int num1=10; int num2=10; int num3 = 20; %>
12. <%= num1*num2+num3 %>
13. </body>
14. </html>

Deependra Rastogi, Assistant Professor, SCSE, Galgotia University Page 17


22-11-2019 Java Server Pages

Explanation of the code:

Code Line 12: Here we are using expression tags where we are using an expression by
multiplying two numbers i.e. num1 and num 2 and then adding the third number i.e. num3.

When you execute the above code, you get the following output:

JSP Comments
Comments are the one when JSP container wants to ignore certain texts and statements.
When we want to hide certain content, then we can add that to the comments section.

Syntax:

<% -- JSP Comments %>

This tags are used to comment in JSP and ignored by the JSP container.
<!—comment -->

This is HTML comment which is ignored by browser

Example:
In this example, we are using JSP comments

Example:

In this example, we are using expression tag

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


2. pageEncoding="ISO-8859-1"%>
3. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
4. <html>
5. <head>
Deependra Rastogi, Assistant Professor, SCSE, Galgotia University Page 18
22-11-2019 Java Server Pages

6. <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">


7. <title>Comments</title>
8. </head>
9. <body>
10. <%-- Comments section --%>
11. <% out.println("This is comments example"); %>
12.
13. </body>
14. </html>

Explanation of the code:

Code Line 10: Here we are adding JSP comments to the code to explain what code has. It is
been ignored by the JSP container

When you execute the above code you get the following output:

JSP Directives: Page, Include & Taglib

JSP directives are the messages to JSP container. They provide global information about an
entire JSP page.

JSP directives are used to give special instruction to a container for translation of JSP to
servlet code. In JSP life cycle phase, JSP has to be converted to a servlet which is the
translation phase. They give instructions to the container on how to handle certain aspects
of JSP processing. Directives can have many attributes by comma separated as key-value
pairs.

In JSP, directive is described in <%@ %> tags.

Syntax of Directive:

<%@ directive attribute="" %>

There are three types of directives:


Deependra Rastogi, Assistant Professor, SCSE, Galgotia University Page 19
22-11-2019 Java Server Pages

1. Page directive
2. Include directive
3. Taglib directive

JSP Page directive

Syntax of Page directive:

<%@ page…%>

 It provides attributes that get applied to entire JSP page.


 It defines page dependent attributes, such as scripting language, error page, and
buffering requirements.
 It is used to provide instructions to a container that pertains to current JSP page.

Following are its list of attributes associated with page directive:

1. Language
2. Extends
3. Import
4. contentType
5. info
6. session
7. isThreadSafe
8. autoflush
9. buffer
10.IsErrorPage
11.pageEncoding
12.errorPage
13.isELIgonored

More details about each attribute

1. language: It defines the programming language (underlying language) being used in the
page.

Syntax of language:

<%@ page language="value" %>

Here value is the programming language (underlying language)

Deependra Rastogi, Assistant Professor, SCSE, Galgotia University Page 20


22-11-2019 Java Server Pages

Example:

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


pageEncoding="ISO-8859-1"%>

Explanation of code: In the above example, attribute language value is Java which is the
underlying language in this case. Hence, the code in expression tags would be compiled
using java compiler.

2. Extends: This attribute is used to extend (inherit) the class like JAVA does

Syntax of extends:

<%@ page extends="value" %>

Here the value represents class from which it has to be inherited.

Example:

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


pageEncoding="ISO-8859-1"%>

<%@ page extends="demotest.DemoClass" %>

Explanation of the code: In the above code JSP is extending DemoClass which is within
demotest package, and it will extend all class features.

3. Import: This attribute is most used attribute in page directive attributes.It is used to tell
the container to import other java classes, interfaces, enums, etc. while generating
servlet code.It is similar to import statements in java classes, interfaces.

Syntax of import:

<%@ page import="value" %>

Here value indicates the classes which have to be imported.

Example:

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


import="java.util.Date" pageEncoding="ISO-8859-1"%>

Deependra Rastogi, Assistant Professor, SCSE, Galgotia University Page 21


22-11-2019 Java Server Pages

Explanation of the code:

In the above code, we are importing Date class from java.util package (all utility classes),
and it can use all methods of the following class.

4. contentType:

 It defines the character encoding scheme i.e. it is used to set the content type and
the character set of the response
 The default type of contentType is "text/html; charset=ISO-8859-1".

Syntax of the contentType:

<%@ page contentType="value" %>

Example:

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


pageEncoding="ISO-8859-1"%>

Explanation of the code:

In the above code, the content type is set as text/html, it sets character encoding for JSP
and for generated response page.

5. info

 It defines a string which can be accessed by getServletInfo() method.


 This attribute is used to set the servlet description.

Syntax of info:

<%@ page info="value" %>

Here, the value represents the servlet information.

Example:

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


info="Guru Directive JSP" pageEncoding="ISO-8859-1"%>

Explanation of the code:

Deependra Rastogi, Assistant Professor, SCSE, Galgotia University Page 22


22-11-2019 Java Server Pages

In the above code, string "Guru Directive JSP" can be retrieved by the servlet interface using
getServletInfo()

6. Session

 JSP page creates session by default.


 Sometimes we don't need a session to be created in JSP, and hence, we can set this
attribute to false in that case.The default value of the session attribute is true, and
the session is created.

When it is set to false, then we can indicate the compiler to not create the session by
default.

Syntax of session:

<%@ page session="true/false"%>

Here in this case session attribute can be set to true or false

Example:

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


session="false"%>

Explanation of code:

In the above example, session attribute is set to "false" hence we are indicating that we
don't want to create any session in this JSP

7. isThreadSafe:

 It defines the threading model for the generated servlet.


 It indicates the level of thread safety implemented in the page.
 Its default value is true so simultaneous
 We can use this attribute to implement SingleThreadModel interface in generated
servlet.
 If we set it to false, then it will implement SingleThreadModel and can access any
shared objects and can yield inconsistency.

Syntax of isThreadSafe:

<% @ page isThreadSafe="true/false" %>

Deependra Rastogi, Assistant Professor, SCSE, Galgotia University Page 23


22-11-2019 Java Server Pages

Here true or false represents if synchronization is there then set as true and set it as false.

Example:

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


isThreadSafe="true"%>

Explanation of the code:

In the above code, isThreadSafe is set to "true" hence synchronization will be done, and
multiple threads can be used.

8. AutoFlush:

This attribute specifies that the buffered output should be flushed automatically or not and
default value of that attribute is true.

If the value is set to false the buffer will not be flushed automatically and if its full, we will
get an exception.

When the buffer is none then the false is illegitimate, and there is no buffering, so it will be
flushed automatically.

Syntax of autoFlush:

<% @ page autoFlush="true/false" %>

Here true/false represents whether buffering has to be done or not

Example:

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


autoFlush="false"%>

Explanation of the code:

In the above code, the autoflush is set to false and hence buffering won't be done and it has
manually flush the output.

9. Buffer:

 Using this attribute the output response object may be buffered.


 We can define the size of buffering to be done using this attribute and default size
is 8KB.
Deependra Rastogi, Assistant Professor, SCSE, Galgotia University Page 24
22-11-2019 Java Server Pages

 It directs the servlet to write the buffer before writing to the response object.

Syntax of buffer:

<%@ page buffer="value" %>

Here the value represents the size of the buffer which has to be defined. If there is no
buffer, then we can write as none, and if we don't mention any value then the default is
8KB

Example:

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


buffer="16KB"%>

Explanation of the code:

In the above code, buffer size is mentioned as 16KB wherein the buffer would be of that
size

10. isErrorPage:

 It indicates that JSP Page that has an errorPage will be checked in another JSP page
 Any JSP file declared with "isErrorPage" attribute is then capable to receive
exceptions from other JSP pages which have error pages.
 Exceptions are available to these pages only.
 The default value is false.

Syntax of isErrorPage:

<%@ page isErrorPage="true/false"%>

Example:

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


isErrorPage="true"%>

Explanation of the code:

In the above code, isErrorPage is set as true. Hence, it will check any other JSPs has
errorPage (described in the next attribute) attribute set and it can handle exceptions.

11.PageEncoding:

Deependra Rastogi, Assistant Professor, SCSE, Galgotia University Page 25


22-11-2019 Java Server Pages

The "pageEncoding" attribute defines the character encoding for JSP page.

The default is specified as "ISO-8859-1" if any other is not specified.

Syntax of pageEncoding:

<%@ page pageEncoding="vaue" %>

Here value specifies the charset value for JSP

Example:

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


isErrorPage="true"%>

Explanation of the code:

In the above code "pageEncoding" has been set to default charset ISO-8859-1

12.errorPage:

This attribute is used to set the error page for the JSP page if JSP throws an exception and
then it redirects to the exception page.

Syntax of errorPage:

<%@ page errorPage="value" %>

Here value represents the error JSP page value

Example:

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


errorPage="errorHandler.jsp"%>

Explanation of the code:

In the above code, to handle exceptions we have errroHandler.jsp

13.isELIgnored:

 IsELIgnored is a flag attribute where we have to decide whether to ignore EL tags or


not.

Deependra Rastogi, Assistant Professor, SCSE, Galgotia University Page 26


22-11-2019 Java Server Pages

 Its datatype is java enum, and the default value is false hence EL is enabled by
default.

Syntax of isELIgnored:

<%@ page isELIgnored="true/false" %>

Here, true/false represents the value of EL whether it should be ignored or not.

Example:

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


isELIgnored="true"%>

Explanation of the code:

In the above code, isELIgnored is true and hence Expression Language (EL) is ignored here.

In the below example we are using four attributes(code line 1-2)

Example with four attributes

Example:

In this example, we are using expression tag

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


2. pageEncoding="ISO-8859-1"%>
3. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
4. <html>
5. <head>
6. <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
7. <title>Directive JSP1</title>
8. </head>
9. <body>
10. <a>Date is:</a>
11. <%= new java.util.Date() %>
12. </body>
13. </html>

Deependra Rastogi, Assistant Professor, SCSE, Galgotia University Page 27


22-11-2019 Java Server Pages

Explanation of the code:

Code Line 1-2: Here we have defined four attributes i.e.

 Language: It is set as Java as programming language


 contentType: set as text/html to tell the compiler that html has to be format
 pageEncoding: default charset is set in this attribute
 isELIgnored: Expression Tag is false hence it is not ignored

Code Line 3: Here we have used import attribute, and it is importing "Date class" which is
from Java util package, and we are trying to display current date in the code.

When you execute the above code, you will get the following output

JSP Include directive

 JSP "include directive" is used to include one file to the another file
 This included file can be HTML, JSP, text files, etc.
 It is also useful in creating templates with the user views and break the pages into
header & footer and sidebar actions.
 It includes file during translation phase

Syntax of include directive:

<%@ include….%>

Deependra Rastogi, Assistant Professor, SCSE, Galgotia University Page 28


22-11-2019 Java Server Pages

Example:

Directive_jsp2.jsp (Main file)

Directive_header_jsp3.jsp (which is included in the main file)

Deependra Rastogi, Assistant Professor, SCSE, Galgotia University Page 29


22-11-2019 Java Server Pages

Explanation of the code:

Directive_jsp2.jsp:

Code Line 3: In this code, we use include tags where we are including the file
directive_header_jsp3.jsp into the main file(_jsp2.jsp)and gets the output of both main file
and included file.

Directive_header_jsp3.jsp:

Code Line 11-12: We have taken a variable count initialized to 1 and then incremented it.
This will give the output in the main file as shown below.

When you execute the above code you get the following output:

JSP Taglib Directive

 JSP taglib directive is used to define the tag library with "taglib" as the prefix, which
we can use in JSP.
 JSP taglib directive is used in the JSP pages using the JSP standard tag libraries
 It uses a set of custom tags, identifies the location of the library and provides means
of identifying custom tags in JSP page.

Syntax of taglib directive:

<%@ taglib uri="uri" prefix="value"%>

Here "uri" attribute is a unique identifier in tag library descriptor and "prefix" attribute is a
tag name.

Deependra Rastogi, Assistant Professor, SCSE, Galgotia University Page 30


22-11-2019 Java Server Pages

Example:

Explanation of the code:

Code Line 3: Here "taglib" is defined with attributes uri and prefix.

Code Line 9: "gurutag" is the custom tag defined and it can be used anywhere

Deependra Rastogi, Assistant Professor, SCSE, Galgotia University Page 31


22-11-2019 Java Server Pages

JSP Standard Action Tags: include, useBean, forward, param

JSP actions use the construct in XML syntax to control the behavior of the servlet engine.

We can dynamically insert a file, reuse the beans components, forward user to another
page, etc. through JSP Actions like include and forward.

Unlike directives, actions are re-evaluated each time the page is accessed.

Syntax:

<jsp:action_name attribute="value" />

How many standard Action Tags are available in JSP?

There are 11 types of Standard Action Tags as following:

 jsp:useBean
 jsp:include
 jsp:setProperty
 jsp:getProperty
 jsp:forward
 jsp:plugin
 jsp:attribute
 jsp:body
 jsp:text
 jsp:param
 jsp:attribute
 jsp:output

1. jsp:useBean:

 This action name is used when we want to use beans in the JSP page.
 With this tag, we can easily invoke a bean.

Syntax of jsp: UseBean:

<jsp:useBean id="" class="" />

Here it specifies the identifier for this bean and class is full path of the bean class

Example:

Deependra Rastogi, Assistant Professor, SCSE, Galgotia University Page 32


22-11-2019 Java Server Pages

Explanation of the code:

Code Line 10: In the above code we use "bean id" and "class path" of the bean.

2. jsp:include

 It also used to insert a jsp file into another file, just like include directive.
 It is added during request processing phase

Syntax of jsp:include

<jsp:include page="page URL" flush="true/false">

Example:

Action_jsp2 (Code Line 10) we are including a date.jsp file

Deependra Rastogi, Assistant Professor, SCSE, Galgotia University Page 33


22-11-2019 Java Server Pages

Date.jsp

Explanation of the code:

Action_jsp2.jsp

Code Line 10: In the first file we are including the date.jsp file in action_jsp2.jsp

Date.jsp:

Code Line 11: We are printing today's date in code line 11 in date.jsp

When you execute the code following is the output.

3. jsp:setProperty

 This property is used to set the property of the bean.


 We need to define a bean before setting the property

Syntax:

Deependra Rastogi, Assistant Professor, SCSE, Galgotia University Page 34


22-11-2019 Java Server Pages

<jsp:setproperty name="" property="" >

Here, the name defines the bean whose property is set and property which we want to set.
Also, we can set value and param attribute.
Here value is not mandatory, and it defines the value which is assigned to the property.
Here param is the name of the request parameter using which value can be fetched.
The example of setproperty will be demonstrated below with getproperty

4. jsp:getProperty

 This property is used to get the property of the bean.


 It converts into a string and finally inserts into the output.

Syntax:

<jsp:getAttribute name="" property="" >

Here, the name of the bean from which the property has to be retrieved and bean should
be defined. The property attribute is the name of the bean property to be retrieved.

Example of setProperty and getProperty:

TestBean.java:

Deependra Rastogi, Assistant Professor, SCSE, Galgotia University Page 35


22-11-2019 Java Server Pages

Explanation of the code:

TestBean.java:

Code Line 5: TheTestBean is implementing the serializable class. It is a bean class with
getters setters in the code.

Code Line 7: Here we are taking private string variable msg as "null"

Code Line 9-14: Here we are using getters and setters of variable "msg".

Action_jsp3.jsp

Code Line 10: Here we are using "useBean" tag, where it specifies the bean i.e TestBean
which has to be used in this jsp class

Code Line 11: Here we are setting the value for the property msg for bean TestBean as
"GuruTutorial."

CodeLine12: Here using getProperty, we are getting the value of property msg for bean
TestBean i.e GuruTutorial which is there in the output

When you execute the above code you get the following output:

Deependra Rastogi, Assistant Professor, SCSE, Galgotia University Page 36


22-11-2019 Java Server Pages

5. jsp:forward:
It is used to forward the request to another jsp or any static page.
Here the request can be forwarded with no parameters or with parameters.

Syntax:

<jsp:forward page="value">

Here value represents where the request has to be forwarded.

Example:

Deependra Rastogi, Assistant Professor, SCSE, Galgotia University Page 37


22-11-2019 Java Server Pages

Explanation of the code

Action_jsp41.jsp

Code Line 10: Here we are using forward JSP Action to forward the request to the page
mentioned in the attribute, i.e., jsp_action_42.jsp

Jsp_action_42.jsp

Code Line 10: Once we call action_jsp41.jsp, the request gets forwarded to this page, and
we get the output as "This is after forward page."

When we execute the above code, we get the following output

6. jsp:plugin

 It is used to introduce Java components into jsp, i.e., the java components can be
either an applet or bean.
 It detects the browser and adds <object> or <embed> tags into the file

Deependra Rastogi, Assistant Professor, SCSE, Galgotia University Page 38


22-11-2019 Java Server Pages

Syntax:

<jsp:plugin type="applet/bean" code="objectcode" codebase="objectcodebase">

 Here the type specifies either an object or a bean


 Code specifies class name of applet or bean
 Code base contains the base URL that contains files of classes

7. jsp:param

 This is child object of the plugin object described above


 It must contain one or more actions to provide additional parameters.

Syntax:

<jsp:params>
<jsp:param name="val" value="val"/ >
</jsp:params>

Example of plugin and param

Deependra Rastogi, Assistant Professor, SCSE, Galgotia University Page 39


22-11-2019 Java Server Pages

8. jsp:body

 This tag is used to define the XML dynamically i.e., the elements can generate during
request time than compilation time.
 It actually defines the XML, which is generated dynamically element body.

Syntax:

<jsp:body></jsp:body>

9. jsp:attribute

 This tag is used to define the XML dynamically i.e. the elements can be generated
during request time than compilation time
 It actually defines the attribute of XML which will be generated dynamically.

Syntax:
Deependra Rastogi, Assistant Professor, SCSE, Galgotia University Page 40
22-11-2019 Java Server Pages

<jsp:attribute></jsp:attribute>

Here we write attribute tag of XML.

Example of body and attribute:

10.jsp:text

 It is used to template text in JSP pages.


 Its body does not contain any other elements, and it contains only text and EL
expressions.

Syntax:

<jsp:text>template text</jsp:text>

Here template text refers to only template text (which can be any generic text which needs
to be printed on jsp ) or any EL expression.

Example:

Deependra Rastogi, Assistant Professor, SCSE, Galgotia University Page 41


22-11-2019 Java Server Pages

Deependra Rastogi, Assistant Professor, SCSE, Galgotia University Page 42


22-11-2019 Java Server Pages

JSP Implicit Objects

What is JSP Implicit object?

 JSP implicit objects are created during the translation phase of JSP to the servlet.
 These objects can be directly used in scriplets that goes in the service method.
 They are created by the container automatically, and they can be accessed using
objects.

How many Implicit Objects are available in JSP?

There are 9 types of implicit objects available in the container:

1. out
2. request
3. response
4. config
5. application
6. session
7. pageContext
8. page
9. exception

1. out

 Out is one of the implicit objects to write the data to the buffer and send output to
the client in response
 Out object allows us to access the servlet's output stream
 Out is object of javax.servlet.jsp.jspWriter class
 While working with servlet, we need printwriter object

Example:

Deependra Rastogi, Assistant Professor, SCSE, Galgotia University Page 43


22-11-2019 Java Server Pages

2. Request

 The request object is an instance of java.servlet.http.HttpServletRequest and it is one


of the argument of service method
 It will be created by container for every request.
 It will be used to request the information like parameter, header information , server
name, etc.
 It uses getParameter() to access the request parameter.

Example:

Deependra Rastogi, Assistant Professor, SCSE, Galgotia University Page 44


22-11-2019 Java Server Pages

Guru.jsp (where the action is taken)

Deependra Rastogi, Assistant Professor, SCSE, Galgotia University Page 45


22-11-2019 Java Server Pages

3. Response

 "Response" is an instance of class which implements HttpServletResponse interface


 Container generates this object and passes to _jspservice() method as parameter
 "Response object" will be created by the container for each request.
 It represents the response that can be given to the client
 The response implicit object is used to content type, add cookie and redirect to
response page

Example:

Deependra Rastogi, Assistant Professor, SCSE, Galgotia University Page 46


22-11-2019 Java Server Pages

4. Application

 Application object (code line 10) is an instance of javax.servlet.ServletContext and it


is used to get the context information and attributes in JSP.
 Application object is created by container one per application, when the application
gets deployed.
 Servletcontext object contains a set of methods which are used to interact with the
servlet container.We can find information about the servlet container

Example:

5. Session

 The session is holding "httpsession" object(code line 10).


 Session object is used to get, set and remove attributes to session scope and also used
to get session information

Deependra Rastogi, Assistant Professor, SCSE, Galgotia University Page 47


22-11-2019 Java Server Pages

Deependra Rastogi, Assistant Professor, SCSE, Galgotia University Page 48


22-11-2019 Java Server Pages

6. pageContext:

 This object is of the type of pagecontext.


 It is used to get, set and remove the attributes from a particular scope

Scopes are of 4 types:

 Page
 Request
 Session
 Application

Example:

Deependra Rastogi, Assistant Professor, SCSE, Galgotia University Page 49


22-11-2019 Java Server Pages

7. Exception

 Exception is the implicit object of the throwable class.


 It is used for exception handling in JSP.
 The exception object can be only used in error pages.

Example:

Deependra Rastogi, Assistant Professor, SCSE, Galgotia University Page 50


22-11-2019 Java Server Pages

JSP - Cookies Handling


Cookies are text files stored on the client computer and they are kept for various
information tracking purposes. JSP transparently supports HTTP cookies using underlying
servlet technology.
There are three steps involved in identifying and returning users −
 Server script sends a set of cookies to the browser. For example, name, age, or
identification number, etc.
 Browser stores this information on the local machine for future use.
 When the next time the browser sends any request to the web server then it sends
those cookies information to the server and server uses that information to identify
the user or may be for some other purpose as well.
Along with the name and value, the cookie may contain

 An expiration date, after which the client is no long expected to retain the cookie. If
no date is specified, the cookie expires as soon as the browser session ends.
 A domain name, such as servername.com, which restricts the subset of URLs for
which the cookie is valid. If unspecified, the cookie is returned with all requests to
the originating Web server.
 A path name that further restricts the URL subset.
 A secure attribute, which, if present, indicates the cookie should only be returned if
the connection uses a secure channel, such as SSL.

First, the Web browser requests a page from the Web server. No cookies are involved at
this point. When the server responds with the requested document, it sends a Set-Cookie
header assigning the value fr to a cookie named language. The cookie is set to expire in one
year. The browser reads this header, extracts the cookie information, and stores the
name/value pair in its cookie cache, along with the Web server’s domain and default path.
Later, when the user visits the page again, the browser recognizes it previously received a
cookie from this server and the cookie hasn’t yet expired, and, therefore, sends the cookie
back to the server.

One advantage of cookies over other persistence schemes is they can retain their values
after the browser session is over, even after the client computer is rebooted. This makes
cookies well suited for maintaining users’ preferences, such as language. The application
shown in the following enables the user to select the desired language by clicking a
hyperlink. The selection causes two cookies to be sent to the client: one for language and
one for country. The next time the user visits the site, the browser automatically sends the
cookies back to the server and the user’s preferred language is used in the page.
Deependra Rastogi, Assistant Professor, SCSE, Galgotia University Page 51
22-11-2019 Java Server Pages

Cookies Methods

Following table lists out the useful methods associated with the Cookie object which you
can use while manipulating cookies in JSP −
S.No. Method & Description

public void setDomain(String pattern)


1 This method sets the domain to which the cookie applies; for example,
tutorialspoint.com.

public String getDomain()


2 This method gets the domain to which the cookie applies; for example,
tutorialspoint.com.

public void setMaxAge(int expiry)


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

Deependra Rastogi, Assistant Professor, SCSE, Galgotia University Page 52


22-11-2019 Java Server Pages

public int getMaxAge()


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

public String getName()


5 This method returns the name of the cookie. The name cannot be changed after
the creation.

public void setValue(String newValue)


6
This method sets the value associated with the cookie.

public String getValue()


7
This method gets the value associated with the cookie.

public void setPath(String uri)


This method sets the path to which this cookie applies. If you don't specify a path,
8
the cookie is returned for all URLs in the same directory as the current page as well
as all subdirectories.

public String getPath()


9
This method gets the path to which this cookie applies.

public void setSecure(boolean flag)


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

public void setComment(String purpose)


11 This method specifies a comment that describes a cookie's purpose. The comment
is useful if the browser presents the cookie to the user.

public String getComment()


12 This method returns the comment describing the purpose of this cookie, or null if
the cookie has no comment.

Setting Cookies with JSP

Setting cookies with JSP involves three steps −

Step 1: Creating a Cookie object


You call the Cookie constructor with a cookie name and a cookie value, both of which are
strings.
Cookie cookie = new Cookie("key","value");
Deependra Rastogi, Assistant Professor, SCSE, Galgotia University Page 53
22-11-2019 Java Server Pages

Keep in mind, neither the name nor the value should contain white space or any of the
following characters −

[]()=,"/?@:;

Step 2: Setting the maximum age


You use setMaxAge to specify how long (in seconds) the cookie should be valid. The
following code will set up a cookie for 24 hours.

cookie.setMaxAge(60*60*24);

Step 3: Sending the Cookie into the HTTP response headers


You use response.addCookie to add cookies in the HTTP response header as follows

response.addCookie(cookie);

Example

main.jsp

<%
// Create cookies for first and last names.
Cookie firstName = new Cookie("first_name", request.getParameter("first_name"));
Cookie lastName = new Cookie("last_name", request.getParameter("last_name"));

// Set expiry date after 24 Hrs for both the cookies.


firstName.setMaxAge(60*60*24);
lastName.setMaxAge(60*60*24);

// Add both the cookies in the response header.


response.addCookie( firstName );
response.addCookie( lastName );
%>

<html>
<head>
<title>Setting Cookies</title>
</head>

<body>
<center>
Deependra Rastogi, Assistant Professor, SCSE, Galgotia University Page 54
22-11-2019 Java Server Pages

<h1>Setting Cookies</h1>
</center>
<ul>
<li><p><b>First Name:</b>
<%= request.getParameter("first_name")%>
</p></li>
<li><p><b>Last Name:</b>
<%= request.getParameter("last_name")%>
</p></li>
</ul>

</body>
</html>

cookie_main.jsp

<html>
<body>

<form action = "main.jsp" method = "GET">


First Name: <input type = "text" name = "first_name">
<br />
Last Name: <input type = "text" name = "last_name" />
<input type = "submit" value = "Submit" />
</form>

</body>
</html>

Reading Cookies with JSP

To read cookies, you need to create an array of javax.servlet.http.Cookie 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.

Example

<html>
<head>
<title>Reading Cookies</title>
</head>
Deependra Rastogi, Assistant Professor, SCSE, Galgotia University Page 55
22-11-2019 Java Server Pages

<body>
<center>
<h1>Reading Cookies</h1>
</center>
<%
Cookie cookie = null;
Cookie[] cookies = null;

// Get an array of Cookies associated with the this domain


cookies = request.getCookies();

if( cookies != null ) {


out.println("<h2> Found Cookies Name and Value</h2>");

for (int i = 0; i < cookies.length; i++) {


cookie = cookies[i];
out.print("Name : " + cookie.getName( ) + ", ");
out.print("Value: " + cookie.getValue( )+" <br/>");
}
} else {
out.println("<h2>No cookies founds</h2>");
}
%>
</body>

</html>

Delete Cookies with JSP


To delete cookies is very simple. If you want to delete a cookie, then you simply need to
follow these three steps −
 Read an already existing cookie and store it in Cookie object.
 Set cookie age as zero using the setMaxAge() method to delete an existing cookie.
 Add this cookie back into the response header.

Example

<html>
<head>
<title>Reading Cookies</title>
</head>

Deependra Rastogi, Assistant Professor, SCSE, Galgotia University Page 56


22-11-2019 Java Server Pages

<body>
<center>
<h1>Reading Cookies</h1>
</center>
<%
Cookie cookie = null;
Cookie[] cookies = null;

// Get an array of Cookies associated with the this domain


cookies = request.getCookies();

if( cookies != null ) {


out.println("<h2> Found Cookies Name and Value</h2>");

for (int i = 0; i < cookies.length; i++) {


cookie = cookies[i];

if((cookie.getName( )).compareTo("first_name") == 0 ) {
cookie.setMaxAge(0);
response.addCookie(cookie);
out.print("Deleted cookie: " + cookie.getName( ) + "<br/>");
}
out.print("Name : " + cookie.getName( ) + ", ");
out.print("Value: " + cookie.getValue( )+" <br/>");
}
} else {
out.println(
"<h2>No cookies founds</h2>");
}
%>
</body>

</html>

Deependra Rastogi, Assistant Professor, SCSE, Galgotia University Page 57


22-11-2019 Java Server Pages

JSP - Session Tracking

JSP makes use of the servlet provided HttpSession Interface. This interface provides a way
to identify a user across.

 a one page request or


 visit to a website or
 store information about that user
By default, JSPs have session tracking enabled and a new HttpSession object is instantiated
for each new client automatically. Disabling session tracking requires explicitly turning it
off by setting the page directive session attribute to false as follows −
<%@ page session = "false" %>
The JSP engine exposes the HttpSession object to the JSP author through the
implicit session object. Since session object is already provided to the JSP programmer, the
programmer can immediately begin storing and retrieving data from the object without
any initialization or getSession().
Here is a summary of important methods available through the session object −

S.No. Method & Description

public Object getAttribute(String name)


1 This method returns the object bound with the specified name in this session, or
null if no object is bound under the name.

public Enumeration getAttributeNames()


2 This method returns an Enumeration of String objects containing the names of all
the objects bound to this session.

public long getCreationTime()


3 This method returns the time when this session was created, measured in
milliseconds since midnight January 1, 1970 GMT.

public String getId()


4 This method returns a string containing the unique identifier assigned to this
session.

public long getLastAccessedTime()


5 This method returns the last time the client sent a request associated with the this
session, as the number of milliseconds since midnight January 1, 1970 GMT.

Deependra Rastogi, Assistant Professor, SCSE, Galgotia University Page 58


22-11-2019 Java Server Pages

public int getMaxInactiveInterval()


6 This method returns the maximum time interval, in seconds, that the servlet
container will keep this session open between client accesses.

public void invalidate()


7
This method invalidates this session and unbinds any objects bound to it.

public boolean isNew()


8 This method returns true if the client does not yet know about the session or if the
client chooses not to join the session.

public void removeAttribute(String name)


9
This method removes the object bound with the specified name from this session.

public void setAttribute(String name, Object value)


10
This method binds an object to this session, using the name specified.

public void setMaxInactiveInterval(int interval)


11 This method specifies the time, in seconds, between client requests before the
servlet container will invalidate this session.

Deependra Rastogi, Assistant Professor, SCSE, Galgotia University Page 59


22-11-2019 Java Server Pages

Deependra Rastogi, Assistant Professor, SCSE, Galgotia University Page 60


22-11-2019 Java Server Pages

Example
Session Tracking

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


<%
// Get session creation time.
Date createTime = new Date(session.getCreationTime());

// Get last access time of this Webpage.


Date lastAccessTime = new Date(session.getLastAccessedTime());

String title = "Welcome Back to my website";


Integer visitCount = new Integer(0);
String visitCountKey = new String("visitCount");
String userIDKey = new String("userID");
String userID = new String("ABCD");

// Check if this is new comer on your Webpage.


if (session.isNew() ){
title = "Welcome to my website";
session.setAttribute(userIDKey, userID);
session.setAttribute(visitCountKey, visitCount);
}
visitCount = (Integer)session.getAttribute(visitCountKey);
visitCount = visitCount + 1;
userID = (String)session.getAttribute(userIDKey);
session.setAttribute(visitCountKey, visitCount);
%>

<html>
<head>
<title>Session Tracking</title>
</head>

<body>
<center>
<h1>Session Tracking</h1>
</center>

<table border = "1" align = "center">


<tr bgcolor = "#949494">
<th>Session info</th>

Deependra Rastogi, Assistant Professor, SCSE, Galgotia University Page 61


22-11-2019 Java Server Pages

<th>Value</th>
</tr>
<tr>
<td>id</td>
<td><% out.print( session.getId()); %></td>
</tr>
<tr>
<td>Creation Time</td>
<td><% out.print(createTime); %></td>
</tr>
<tr>
<td>Time of Last Access</td>
<td><% out.print(lastAccessTime); %></td>
</tr>
<tr>
<td>User ID</td>
<td><% out.print(userID); %></td>
</tr>
<tr>
<td>Number of visits</td>
<td><% out.print(visitCount); %></td>
</tr>
</table>

</body>
</html>

Deependra Rastogi, Assistant Professor, SCSE, Galgotia University Page 62


22-11-2019 Java Server Pages

Login Example in JSP with Session

Login.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>


<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Example</title>
</head>
<body>
<form method="post" action="login_logic.jsp">
<center>
<table border="1" width="30%" cellpadding="3">
<thead>
<tr>
<th colspan="2">Login Here</th>
</tr>
</thead>
<tbody>
<tr>
<td>User Name</td>
<td><input type="text" name="uname" value="" /></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="pass" value="" /></td>
</tr>
<tr>
<td><input type="submit" value="Login" /></td>
<td><input type="reset" value="Reset" /></td>
</tr>
<tr>
<td colspan="2">Yet Not Registered!! <a href="reg.jsp">Register Here</a></td>
</tr>
</tbody>
</table>
</center>
</form>
</body>
</html>

Deependra Rastogi, Assistant Professor, SCSE, Galgotia University Page 63


22-11-2019 Java Server Pages

login_logic.jsp

<%@ page import ="java.sql.*" %>


<%
String userid = request.getParameter("uname");
String pwd = request.getParameter("pass");

Class.forName("com.mysql.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/employee","root", "");
Statement st = con.createStatement();
ResultSet rs;
rs = st.executeQuery("select * from user_detail where uname='" + userid + "' and
passwd='" + pwd + "'");

if (rs.next()) {
session.setAttribute("userid", userid);
response.sendRedirect("success.jsp");
} else {
out.println("Invalid password <a href='Login.jsp'>try again</a>");
}
%>

success.jsp

<%
if ((session.getAttribute("userid") == null) || (session.getAttribute("userid") ==
"")) {
%>

You are not logged in<br/>


<a href="Login.jsp">Please Login</a>

<%} else {
%>

Welcome <%=session.getAttribute("userid")%>
<a href='logout.jsp'>Log out</a>

<%
}
%>

Deependra Rastogi, Assistant Professor, SCSE, Galgotia University Page 64


22-11-2019 Java Server Pages

logout.jsp

<%
session.setAttribute("userid", null);
session.invalidate();
response.sendRedirect("Login.jsp");
%>

Deependra Rastogi, Assistant Professor, SCSE, Galgotia University Page 65


22-11-2019 Java Server Pages

Data base action with JSP

Project Folder Specifications

Database

Deependra Rastogi, Assistant Professor, SCSE, Galgotia University Page 66


22-11-2019 Java Server Pages

Create four packages in the src folder.


com.bari.controller: contains the servlets(UserController.java)
com.bari.dao: contains the logic for database operation(UserDao.java)
com.bari.model: contains the POJO (Plain Old Java Object).(User.java)
com.bari.util : contains the class for initiating database connection(Database.java)

User.java

package com.bari.model;
import java.util.Date;

public class User {


String uname, password, email;
Date registeredon;

public String getEmail() {


return email;
}

public void setEmail(String email) {


this.email = email;
}

public String getPassword() {


return password;
}

public void setPassword(String password) {


this.password = password;
}

public Date getRegisteredon() {


return registeredon;
}

public void setRegisteredon(Date registeredon) {


this.registeredon = registeredon;
}

public String getUname() {


return uname;
}

public void setUname(String uname) {


this.uname = uname;
}

Deependra Rastogi, Assistant Professor, SCSE, Galgotia University Page 67


22-11-2019 Java Server Pages

Database.java
package com.bari.util;
import java.sql.Connection;
import java.sql.DriverManager;
public class Database {
public static Connection getConnection() {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection
("jdbc:mysql://localhost:3306/employee",
"root","");
return con;
}
catch(Exception ex) {
System.out.println("Database.getConnection() Error -->" + ex.getMessage());
return null;
}
}

public static void close(Connection con) {


try {
con.close();
}
catch(Exception ex) {
}
}
}

UserDao.java

package com.bari.dao;

import java.sql.*;
import java.util.*;
import com.bari.model.User;
import com.bari.util.Database;

public class UserDao {

private Connection connection;

public UserDao() {
connection = Database.getConnection();
}

public void checkUser(User user) {


try {
PreparedStatement ps = connection.prepareStatement("select uname from users where uname
= ?");

Deependra Rastogi, Assistant Professor, SCSE, Galgotia University Page 68


22-11-2019 Java Server Pages

ps.setString(1, user.getUname());
ResultSet rs = ps.executeQuery();
if (rs.next()) // found
{
updateUser(user);
} else {
addUser(user);
}
} catch (Exception ex) {
System.out.println("Error in check() -->" + ex.getMessage());
}
}
public void addUser(User user) {
try {
PreparedStatement preparedStatement = connection.prepareStatement("insert into
users(uname, password, email, registeredon) values (?, ?, ?, ? )");
// Parameters start with 1
preparedStatement.setString(1, user.getUname());
preparedStatement.setString(2, user.getPassword());
preparedStatement.setString(3, user.getEmail());
preparedStatement.setDate(4, new java.sql.Date(user.getRegisteredon().getTime()));
preparedStatement.executeUpdate();

} catch (SQLException e) {
e.printStackTrace();
}
}

public void deleteUser(String userId) {


try {
PreparedStatement preparedStatement = connection.prepareStatement("delete from users
where uname=?");
// Parameters start with 1
preparedStatement.setString(1, userId);
preparedStatement.executeUpdate();

} catch (SQLException e) {
e.printStackTrace();
}
}

public void updateUser(User user) {


try {
PreparedStatement preparedStatement = connection.prepareStatement("update users set
password=?, email=?, registeredon=?"
+ "where uname=?");
// Parameters start with 1
System.out.println(new java.sql.Date(user.getRegisteredon().getTime()));
preparedStatement.setString(1, user.getPassword());

Deependra Rastogi, Assistant Professor, SCSE, Galgotia University Page 69


22-11-2019 Java Server Pages

preparedStatement.setString(2, user.getEmail());
preparedStatement.setDate(3, new java.sql.Date(user.getRegisteredon().getTime()));
preparedStatement.setString(4, user.getUname());
preparedStatement.executeUpdate();

} catch (SQLException e) {
e.printStackTrace();
}
}

public List<User> getAllUsers() {


List<User> users = new ArrayList<User>();
try {
Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery("select * from users");
while (rs.next()) {
User user = new User();
user.setUname(rs.getString("uname"));
user.setPassword(rs.getString("password"));
user.setEmail(rs.getString("email"));
user.setRegisteredon(rs.getDate("registeredon"));
users.add(user);
}
} catch (SQLException e) {
e.printStackTrace();
}

return users;
}

public User getUserById(String userId) {


User user = new User();
try {
PreparedStatement preparedStatement = connection.prepareStatement("select * from users
where uname=?");
preparedStatement.setString(1, userId);
ResultSet rs = preparedStatement.executeQuery();

if (rs.next()) {
user.setUname(rs.getString("uname"));
user.setPassword(rs.getString("password"));
user.setEmail(rs.getString("email"));
user.setRegisteredon(rs.getDate("registeredon"));
}
} catch (SQLException e) {
e.printStackTrace();
}

return user;

Deependra Rastogi, Assistant Professor, SCSE, Galgotia University Page 70


22-11-2019 Java Server Pages

}
}

UserController.java

package com.bari.controller;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.bari.dao.UserDao;
import com.bari.model.User;

public class UserController extends HttpServlet {


private static final long serialVersionUID = 1L;
private static String INSERT_OR_EDIT = "/user.jsp";
private static String LIST_USER = "/listuser.jsp";
private UserDao dao;

public UserController() {
super();
dao = new UserDao();
}

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws


ServletException, IOException {
String forward="";
String action = request.getParameter("action");

if (action.equalsIgnoreCase("delete")){
String userId = request.getParameter("userId");
dao.deleteUser(userId);
forward = LIST_USER;
request.setAttribute("users", dao.getAllUsers());
} else if (action.equalsIgnoreCase("edit")){
forward = INSERT_OR_EDIT;
String userId = request.getParameter("userId");
User user = dao.getUserById(userId);
request.setAttribute("user", user);
} else if (action.equalsIgnoreCase("listUser")){
forward = LIST_USER;

Deependra Rastogi, Assistant Professor, SCSE, Galgotia University Page 71


22-11-2019 Java Server Pages

request.setAttribute("users", dao.getAllUsers());
} else {
forward = INSERT_OR_EDIT;
}

RequestDispatcher view = request.getRequestDispatcher(forward);


view.forward(request, response);
}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws


ServletException, IOException {
User user = new User();
user.setUname(request.getParameter("uname"));
user.setPassword(request.getParameter("pass"));
try {
Date reg = new SimpleDateFormat("yyyy/MM/dd").parse(request.getParameter("dob"));
System.out.println("rrrrrrrrrrr"+ reg);
user.setRegisteredon(reg);
} catch (ParseException e) {
e.printStackTrace();
}
user.setEmail(request.getParameter("email"));
String userid = request.getParameter("uname");
user.setUname(userid);
dao.checkUser(user);
RequestDispatcher view = request.getRequestDispatcher(LIST_USER);
request.setAttribute("users", dao.getAllUsers());
view.forward(request, response);
}
}

index.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>


<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>CRUD Example</title>
</head>
<body>
<jsp:forward page="/UserController?action=listuser" />
</body>
</html>

user.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>


<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

Deependra Rastogi, Assistant Professor, SCSE, Galgotia University Page 72


22-11-2019 Java Server Pages

<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>


<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Add new user</title>
</head>
<body>
<form method="POST" action='UserController' name="frmAddUser">
<% String action = request.getParameter("action");
System.out.println(action);
%>
<% if (action.equalsIgnoreCase("edit")) {%>
User Name : <input type="text" name="uname"
value="<c:out value="${user.uname}" />" readonly="readonly"/> (You Can't Change
this)<br />
<%} else {%>
User Name : <input type="text" name="uname"
value="<c:out value="${user.uname}" />" /> <br />
<%}%>
Password : <input
type="password" name="pass"
value="<c:out value="${user.password}" />" /> <br />
Email : <input
type="text" name="email"
value="<c:out value="${user.email}" />" /> <br />

<% if (action.equalsIgnoreCase("edit")) {%>


Registration : <input
type="text" name="dob"
value="<fmt:formatDate pattern="yyyy/MM/dd" value="${user.registeredon}" />"
readonly="readonly"/>(You Can't Change this) <br />
<%} else {%>
Registration : <input
type="text" name="dob"
value="<fmt:formatDate pattern="yyyy/MM/dd" value="${user.registeredon}" />"
/>(yyyy/MM/dd) <br />
<%}%>
<input type="submit" value="Submit" />
</form>
</body>
</html>

listuser.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>


<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<!DOCTYPE html>

Deependra Rastogi, Assistant Professor, SCSE, Galgotia University Page 73


22-11-2019 Java Server Pages

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Show All Users</title>
</head>
<body>
<table border=1>
<thead>
<tr>
<th>User Name</th>
<th>Email</th>
<th>Registration Date</th>
<th colspan=2>Action</th>
</tr>
</thead>
<tbody>
<c:forEach items="${users}" var="user">
<tr>
<td><c:out value="${user.uname}" /></td>
<td><c:out value="${user.email}" /></td>
<td><fmt:formatDate pattern="dd MMM,yyyy" value="${user.registeredon}" /></td>
<td><a href="UserController?action=edit&userId=<c:out
value="${user.uname}"/>">Update</a></td>
<td><a href="UserController?action=delete&userId=<c:out
value="${user.uname}"/>">Delete</a></td>
</tr>
</c:forEach>
</tbody>
</table>
<p><a href="UserController?action=insert">Add User</a></p>
</body>
</html>

web.xml

<?xml version="1.0" encoding="UTF-8"?>


<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-
app_3_1.xsd">
<servlet>
<servlet-name>UserController</servlet-name>
<servlet-class>com.bari.controller.UserController</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>UserController</servlet-name>
<url-pattern>/UserController</url-pattern>
</servlet-mapping>
<session-config>

Deependra Rastogi, Assistant Professor, SCSE, Galgotia University Page 74


22-11-2019 Java Server Pages

<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>

Deependra Rastogi, Assistant Professor, SCSE, Galgotia University Page 75

Вам также может понравиться