0% found this document useful (0 votes)
135 views53 pages

Introduction To JSP - Updated

The document provides an introduction to Java Server Pages (JSP) technology. Key points include: - JSP pages are used to create dynamic web applications and are easier to maintain than servlets. They allow embedding Java code within HTML using JSP tags. - JSP pages are converted into servlets by the web container, which translates the JSP into a servlet class file that can then be compiled and executed. - Benefits of JSP over servlets include providing an easier way to code dynamic web pages without needing additional files like Java class files or web.xml mappings. JSP also enables easy separation of presentation and business logic.

Uploaded by

Rohit Kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
135 views53 pages

Introduction To JSP - Updated

The document provides an introduction to Java Server Pages (JSP) technology. Key points include: - JSP pages are used to create dynamic web applications and are easier to maintain than servlets. They allow embedding Java code within HTML using JSP tags. - JSP pages are converted into servlets by the web container, which translates the JSP into a servlet class file that can then be compiled and executed. - Benefits of JSP over servlets include providing an easier way to code dynamic web pages without needing additional files like Java class files or web.xml mappings. JSP also enables easy separation of presentation and business logic.

Uploaded by

Rohit Kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 53

Introduction to JSP

 JSP technology is used to create dynamic web applications.


 JSP pages are easier to maintain then a Servlet.
 JSP pages are opposite of Servlets as a servlet adds HTML code
inside Java code, while JSP adds Java code inside HTML using JSP
tags.
 Everything a Servlet can do, a JSP page can also do it.
 JSP enables us to write HTML pages containing tags, inside which
we can include powerful Java programs.
 Using JSP, one can easily separate Presentation and Business
logic as a web designer can design and update JSP pages creating
the presentation layer and java developer can write server side
complex computational code without concerning the web design.
And both the layers can easily interact over HTTP requests.

In the end a JSP becomes a Servlet


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

By:- Anuja Jain assistant professor, VSIT, VIPS


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

Advantage of JSP

 Easy to maintain and code.


 High Performance and Scalability.
 JSP is built on Java technology, so it is platform independent.

By:- Anuja Jain assistant professor, VSIT, VIPS


By:- Anuja Jain assistant professor, VSIT, VIPS
By:- Anuja Jain assistant professor, VSIT, VIPS
JSP Directives :-
1. Page
2. Include
3. Taglib

By:- Anuja Jain assistant professor, VSIT, VIPS


EXPRESSIONS:-

By:- Anuja Jain assistant professor, VSIT, VIPS


By:- Anuja Jain assistant professor, VSIT, VIPS
By:- Anuja Jain assistant professor, VSIT, VIPS
Lifecycle of JSP
A JSP page is converted into Servlet in order to service requests. The translation of a JSP page to
a Servlet is called Lifecycle of JSP. JSP Lifecycle is exactly same as the Servlet Lifecycle, with one
additional first step, which is, translation of JSP code to Servlet code. Following are the JSP
Lifecycle steps:

1. Translation of JSP to Servlet code.

2. Compilation of Servlet to bytecode.

3. Loading Servlet class.

4. Creating servlet instance.

5. Initialization by calling jspInit() method

6. Request Processing by calling _jspService() method

7. Destroying by calling jspDestroy() method

By:- Anuja Jain assistant professor, VSIT, VIPS


 Web Container translates JSP code into a servlet class source(.java) file, then compiles
that into a java servlet class.
 In the third step, the servlet class bytecode is loaded using classloader.
 The Container then creates an instance of that servlet class.
 The initialized servlet can now service request.
 For each request the Web Container call the _jspService() method.
 When the Container removes the servlet instance from service, it calls
the jspDestroy() method to perform any required clean up.

By:- Anuja Jain assistant professor, VSIT, VIPS


What happens to a JSP when it is translated into Servlet
Let's see what really happens to JSP code when it is translated into Servlet. The code written
inside <% %> is JSP code.
<html>
<head>
<title>My First JSP Page</title>
</head>
<%
int count = 0;
%>
<body>
Page Count is:
<% out.println(++count); %>
</body>
</html>

The above JSP page(hello.jsp) becomes this Servlet,


public class hello_jsp extends HttpServlet
{
public void _jspService(HttpServletRequest request, HttpServletResponse response)
throws IOException,ServletException
{
PrintWriter out = response.getWriter();
response.setContenType("text/html");
out.write("<html><body>");
int count=0;
out.write("Page count is:");
out.print(++count);
out.write("</body></html>");

}
}

This is just to explain, what happens internally. As a JSP developer, you do not have to worry
about how a JSP page is converted to a Servlet, as it is done automatically by the web
container.

By:- Anuja Jain assistant professor, VSIT, VIPS


JSP Architecture
• Java Server Pages are part of a 3-tier architecture. A
server(generally referred to as application or web server)
supports the Java Server Pages. This server will act as a
mediator between the client browser and a database.
• JSPs are built on top of SUN Microsystems' servlet
technology. JSPs are essential an HTML page with special
JSP tags embedded.

JSP Architecture Flow


 The user goes to a JSP page and makes the request
via internet in user’s web browser.
 The JSP request is sent to the Web Server.

Web server accepts the requested .jsp file and passes the JSP
file to the JSP Servlet Engine for further processing.

By:- Anuja Jain assistant professor, VSIT, VIPS


JSP Workflow

• Inside the JSP container is a special servlet called the page


compiler. The servlet container is configured to forward to this
page compiler all HTTP requests with URLs

that match the .jsp file extension.

• This page compiler turns a servlet container into a JSP container.


When a .jsp page is first called, the page compiler parses and
compiles the .jsp page into a servlet class.

• If the compilation is successful, the jsp servlet class is loaded into


memory. On subsequent calls, the servlet class for that .jsp page
is already in memory; however, it could have been updated.
Therefore, the page compiler servlet will always compare the
By:- Anuja Jain assistant professor, VSIT, VIPS
timestamp of the jsp servlet with the jsp page. If the .jsp page is
more current, recompilation is necessary.
• With this process, once deployed, JSP pages only go through the
time-consuming compilation process once.
• To save the user from the unpleasant situation of a compiling JSP
page , a mechanism in JSP allows the .jsp pages to be pre-
compiled before any user request for them is received.
Alternatively, you can also deploy your JSP application as a web
archive file in the form of a compiled servlet.

By:- Anuja Jain assistant professor, VSIT, VIPS


JSP Scripting Element
JSP Scripting element are written inside <% %> tags. These code inside <% %> tags are processed
by the JSP engine during translation of the JSP page. Any other text in the JSP page is
considered as HTML code or plain text.
Example:
<html>
<head>
<title>My First JSP Page</title>
</head>
<%
int count = 0;
%>
<body>

By:- Anuja Jain assistant professor, VSIT, VIPS


Page Count is <% out.println(++count); %>
</body>
</html>

Just to experiment, try removing the <% %> scriplet tag from the above code and run it as JSP.
You will see that everything is printed as it is on the browser, because without the scriplet tag,
everything is considered plain HTML code.

There are five different types of scripting elements


Scripting Element Example

Comment <%-- comment --%>

Directive <%@ directive %>

Declaration <%! declarations %>

Scriptlet <% scriplets %>

Expression <%= expression %>

By:- Anuja Jain assistant professor, VSIT, VIPS


JSP Comment
JSP Comment is used when you are creating a JSP page and want to put in comments about
what you are doing. JSP comments are only seen in the JSP page. These comments are not
included in servlet source code during translation phase, nor they appear in the HTTP response.
Syntax of JSP comment is as follows :
<%-- JSP comment --%>

Simple Example of JSP Comment


<html>
<head>
<title>My First JSP Page</title>
</head>
<%
int count = 0;
%>
<body>
<%-- Code to show page count --%>
Page Count is <% out.println(++count); %>
</body>
</html>

NOTE : Adding comments in your code is considered to be a good practice in Programming


world

JSP Scriptlet Tag


Scriptlet Tag allows you to write java code inside JSP page. Scriptlet tag implements
the _jspService method functionality by writing script/java code. Syntax of Scriptlet Tag is as
follows :
<% JAVA CODE %>

By:- Anuja Jain assistant professor, VSIT, VIPS


JSP: Example of Scriptlet
In this example, we will show number of page visit.
<html>
<head>
<title>My First JSP Page</title>
</head>
<%
int count = 0;
%>
<body>
Page Count is <% out.println(++count); %>
</body>
</html>

We have been using the above example since last few lessons and in this scriptlet tags are used.
Everything written inside the scriptlet tag is compiled as java code. Like in the above example,
we initialize count variable of type int with a value of 0. And then we print it while
using ++ operator to perform addition on it.
JSP makes it so easy to perform calculations, database interactions etc directly from inside the
HTML code. Just write your java code inside the scriptlet tags.

Example of JSP Scriptlet Tag


In this example, we will create a simple JSP page which retrieves the name of the user from the
request parameter. The index.html page will get the username from the user.
index.html
<form method="POST" action="welcome.jsp">
Name <input type="text" name="user" >
<input type="submit" value="Submit">
</form>

In the above HTML file, we have created a form, with an input text field for user to enter
his/her name, and a Submit button to submit the form. On submission an HTTP Post request
( method="POST" ) is made to the welcome.jsp file ( action="welcome.jsp" ), with the form values.

By:- Anuja Jain assistant professor, VSIT, VIPS


welcome.jsp
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Welcome Page</title>
</head>
<%
String user = request.getParameter("user");
%>

<body>
Hello, <% out.println(user); %>
</body>
</html>

As we know that a JSP code is translated to Servlet code, in which _jspService method is
executed which has HttpServletRequest and HttpServletResponse as argument. So in
the welcome.jsp file, request is the HTTP Request and it has all the parameters sent from the
form in index.html page, which we can be easily get using getParameter() with name of
parameter as argument, to get its value.

Mixing scriptlet Tag and HTML


Let's see how we can utilize the power of JSP scripting with HTML to build dynamic webpages
with help of a few examples.
If we want to create a Table in HTML with some dynamic data, for example by reading data
from some MySQL table or file. How to do that? Here we will describe you the technique by
creating a table with numbers 1 to n.

<table border = 1>


<%
for ( int i = 0; i < n; i++ ) {
%>
<tr>
<td>Number</td>

By:- Anuja Jain assistant professor, VSIT, VIPS


<td><%= i+1 %></td>
</tr>
<%
}
%>
</table>

The above piece of code will go inside the <body> tag of the JSP file and will work when you
initialize n with some value.
Also, observer closely we have only included the java code inside the scriptlet tag, and all the
HTML part is outside of it. Similarly we can do plenty of stuff.
Here is one more very simple example :

<%
if ( hello ) {
%>
<p>Hello, world</p>
<%
} else {
%>
<p>Goodbye, world</p>
<%
}
%>

Above code is using if-else condition to evaluate what to show, based on the value of
a booleanvariable named hello.
You can even ask user to enter the value of hello, using HTML Form and evaluate your JSP code
based on that.

By:- Anuja Jain assistant professor, VSIT, VIPS


JSP Declaration Tag
We know that at the end a JSP page is translated into Servlet class. So when we declare a
variable or method in JSP inside Declaration Tag, it means the declaration is made inside the
Servlet class but outside the service(or any other) method. You can declare static member,
instance variable and methods inside Declaration Tag. Syntax of Declaration Tag :
<%! declaration %>

Example of Declaration Tag


<html>
<head>
<title>My First JSP Page</title>
</head>
<%!
int count = 0;
%>
<body>
Page Count is:
<% out.println(++count); %>
</body>
</html>

In the above code, we have used the declaration tag to declare variable count. The above JSP
page becomes this Servlet :
public class hello_jsp extends HttpServlet
{
int count=0;
public void _jspService(HttpServletRequest request, HttpServletResponse response)
throws IOException,ServletException
{
PrintWriter out = response.getWriter();
response.setContenType("text/html");

By:- Anuja Jain assistant professor, VSIT, VIPS


out.write("<html><body>");

out.write("Page count is:");


out.print(++count);
out.write("</body></html>");
}
}

In the above servlet, we can see that variable count is declared outside the _jspservice()method.
If we declare the same variable using scriptlet tag, it will come inside the service method, as
seen in the last lesson.

When to use Declaration tag and not scriptlet tag


If you want to include any method in your JSP file, then you must use the declaration tag,
because during translation phase of JSP, methods and variables inside the declaration tag,
becomes instance methods and instance variables and are also assigned default values.
For example:
<html>
<head>
<title>My First JSP Page</title>
</head>
<%!
int count = 0;
int getCount() {
System.out.println( "In getCount() method" );
return count;
}
%>
<body>
Page Count is:
<% out.println(getCount()); %>
</body>
</html>

Above code will be translated into following servlet :

By:- Anuja Jain assistant professor, VSIT, VIPS


public class hello_jsp extends HttpServlet
{
int count = 0;
int getCount() {
System.out.println( "In getCount() method" );
return count;
}
public void _jspService(HttpServletRequest request, HttpServletResponse response)
throws IOException,ServletException
{
PrintWriter out = response.getWriter();
response.setContenType("text/html");
out.write("<html><body>");

out.write("Page count is:");


out.print(getCount());
out.write("</body></html>");
}
}

While, anything we add in scriptlet tag, goes inside the _jspservice() method, therefore we
cannot add any function inside the scriptlet tag, as on compilation it will try to create a
function getCount() inside the service method, and in Java, method inside a method is not
allowed.

By:- Anuja Jain assistant professor, VSIT, VIPS


JSP Directive Tag
Directive Tag gives special instruction to Web Container at the time of page translation.
Directive tags are of three types: page, include and taglib.

Directive Description

<%@ page ... %> defines page dependent properties such as language, session, errorPage etc.

<%@ include ... %> defines file to be included.

<%@ taglib ... %> declares tag library used in the page

We'll discuss about include and taglib directive later. You can place page directive anywhere in
the JSP file, but it is good practice to make it as the first statement of the JSP page.The Page
directive defines a number of page dependent properties which communicates with the Web
Container at the time of translation. Basic syntax of using the page directive is <%@ page
attribute="value" %> where attributes can be one of the following :

 import attribute
 language attribute
 extends attribute
 session attribute
 isThreadSafe attribute
 isErrorPage attribute
 errorPage attribute
 contentType attribute
 autoFlush attribute

By:- Anuja Jain assistant professor, VSIT, VIPS


 buffer attribute

Page Directive: import attribute

•The import attribute defines the set of classes and packages that must be imported in servlet
class definition.

•Examples:

<%@ page import = "java.util.Date" %>


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

Page Directive: language attribute


•The language attribute tells the container which language is being used to write the JSP page.

•Examples:

<%@ page language = “java” %>

•The default language is Java and for this reason, there is no need to write this attribute.
•In future, if the designers would like to give support for other language, then language
attribute might come into usage.
•As on today, no other language is supported by JSP.

Page Directive: extends attribute

•The extends attribute specifies a parent class that will be inherited by the generated servlet.

•Examples:

<%@ page extends = “packName.className” %>

By:- Anuja Jain assistant professor, VSIT, VIPS


Page Directive: session attribute
•session attribute defines whether the JSP page is participating in an HTTP session.
 It takes a Boolean value of true or false.
 If set to true, the session is maintained in JSP.
 Is set to false, the session is not maintained.
 Default is true; that is, session is implicitly maintained with every JSP page.
•Example:

<%@ page session = “true” %>


<%Object o1 = session.getAttribute(“uName”)%>

Exception Handling in JSP


•JSP provide 3 different ways to perform exception handling:
 Using isErrorPage and errorPage attribute of page directive.

 Using <error-page> tag in Deployment Descriptor.

 Using simple try...catch block.

Page Directive: isErrorPage attribute


•isErrorPage attribute in page directive officially appoints a JSP page as an error page.
•Examples: Error.jsp

By:- Anuja Jain assistant professor, VSIT, VIPS


Page Directive: errorPage attribute
•errorPage attribute indicates another JSP page that will handle all the run time exceptions
thrown by current JSP page.

•It specifies the URL path of another page to which a request is to be dispatched to handle run
time exceptions thrown by current JSP page.

•Examples: Hello.jsp

Error Page in Deployment Descriptor


Examples:
…………………
<error-page>
<exception-type>java.lang.ArithmeticException</exception-type>
<location>/Error.jsp</location>
</error-page>
…………………
…………………
<error-page>
<error-code>404</error-code>
<location>/Error.jsp</location>
</error-page>
…………………

Page Directive: contentType attribute


•contentType attribute defines the MIME type for the JSP response.
•Examples:

<%@ page contentType = “text/html” %>


Page Directive: info attribute
•Programmer uses info attribute to give some information or description about the JSP page
like: when the project started, Programmers involved, functionality of the page, etc.

•Example:

<%@ page info = “Proj Started on 11.09.17” %>

By:- Anuja Jain assistant professor, VSIT, VIPS


•The information given as string for info attribute can be accessed with getServletInfo()
method.
•The web container will create a method getServletInfo() in the resulting servlet. For example:

public String getServletInfo() {


return "Proj Started on 11.09.17";
}

Page Directive: buffer attribute


•JSP first writes the response data to the buffer and when the buffer is full, the data is sent to
client.
•When the PrintWriter object is closed with out.close(), the unfilled buffer is flushed to the
client.
•Using buffer page directive attribute, the buffer size can be increased or decreased or set to
none (means no buffer is maintained)
•If not set by the Programmer, the default buffer size is 8 KB.
•Syntax: <%@ page buffer = “integer/none” %>
•Example:

<%@ page buffer = “5kb” %>


<%@ page buffer = “none” %> - buffer is not maintained or set to zero. The response data is
immediately written to output stream of client. This kills performance and increases network
traffic.

Page Directive: autoFlush attribute


•autoFlush indicates the container to flush the data or not when the buffer gets filled to be
sent to client.
•It takes Boolean values of true or false.
•The default value is true, indicating flushing is required.
•When set to false, the autoFlush raises exception when the buffer is full.
•Syntax: <%@ page autoFlush = “true/false” %>
<%@ page autoFlush = “true” %> - It is the default value. When the buffer is full, the data is
flushed out to the output stream of the response object to send to client. This is done by the
container implicitly.
<%@ page autoFlush = “false” %> - The container raises exception when the autoFlush is set
to false, when buffer gets filled up.

By:- Anuja Jain assistant professor, VSIT, VIPS


Page Directive: isThreadSafe attribute
•This attribute takes Boolean values of true or false indicating the JSP page can be safe in
multithreaded environment or not. The default value is true.
•When set to true, the same JSP page can honor multiple clients.

When a client requests a JSP file, the container loads the JSP file, translates it to a Servlet,
compiled and then executed. For multiple clients’ requests also, the container creates multiple
objects of the same Servlet and honors. For each Servlet object, a separate service() method is
created. That is, each client will have a separate service() method. For this reason, Servlets and
JSP are implicitly thread safe.

•If the Programmer would like to create only one object for the Servlet/JSP (and not multiple
objects), then declare false.

That is, multiple clients request the same JSP (or Servlet), multiple files of the same JSP are
loaded and executed. This decreases the performance. This type coding is required when the
data is very important and critical like money transfer operations in banks.
•Syntax:

<%@ page isThreadSafe = “true/false” %>

Page Directive: isELIgnored attribute


•The isELIgnored attribute value informs the container whether to evaluate or execute EL
(Expression Language) expression present in the JSP or not.
•It takes Boolean values of true or false.
•The default value is false, indicating that EL expressions are evaluated.
•Example:

<%@ page isELIgnored = “true” %>


•While using EL in JSP, this attribute should be set to false else not executed.

By:- Anuja Jain assistant professor, VSIT, VIPS


Page Directive: isScriptingEnabled attribute
•JSP code contains scriptlets, expressions and declarations.

•isScriptingEnabled takes Boolean values of true or false.

By default, this attribute is set to true and means these elements (non-EL) are recognized by
the container.

When set to false, a translation-time error will be raised if the JSP uses any scriptlets,
expressions (non-EL), or declarations.

JSP Expression Tag


Expression Tag is used to print out java language expression that is put between the tags. An
expression tag can hold any java language expression that can be used as an argument to
the out.print() method. Syntax of Expression Tag
<%= Java Expression %>

When the Container sees this


<%= (2*5) %>

It turns it into this:


out.print((2*5));
Note: Never end an expression with semicolon inside Expression Tag. Like this:
<%= (2*5); %>

Example of Expression Tag


<html>
<head>
<title>My First JSP Page</title>
</head>
<%
int count = 0;
%>
<body>
Page Count is <%= ++count %>

By:- Anuja Jain assistant professor, VSIT, VIPS


</body>
</html>

JSP Include Directive


The include directive tells the Web Container to copy everything in the included file and paste it
into current JSP file. Syntax of include directive is:
<%@ include file="filename.jsp" %>

Example of include directive


welcome.jsp
<html>
<head>
<title>Welcome Page</title>
</head>

<body>
<%@ include file="header.jsp" %>
Welcome, User
</body>
</html>

By:- Anuja Jain assistant professor, VSIT, VIPS


header.jsp

<html>
<body>
<img src="header.jpg" alt="This is Header image" / >
</body>
</html>

The example above is showcasing a very standard practice. Whenever we are building a web
application, with webpages, all of which have the top navbar and bottom footer same. We
make them as separate jsp files and include them using the include directive in all the pages.
Hence whenever we have to update something in the top navbar or footer, we just have to do
it at one place. Handy, isn't it?

One more standard application of include directive is, if you create a separate jsp file, with some
commonly used functions, kind of like a util jsp file. Which can be included in the web pages
wherever you want to use those functions.

By:- Anuja Jain assistant professor, VSIT, VIPS


Similarly, there are many ways in which this directive proves to be quite useful in giving a
structure to your web application code.

JSP - The taglib Directive


The JavaServer Pages API allow you to define custom JSP tags that look like HTML or XML tags
and a tag library is a set of user-defined tags that implement custom behavior.
The taglib directive declares that your JSP page uses a set of custom tags, identifies the
location of the library, and provides means for identifying the custom tags in your JSP page.
The taglib directive follows the syntax given below −
<%@ taglib uri = "uri" prefix = "prefixOfTag" >
Where, the uri attribute value resolves to a location the container understands and
the prefixattribute informs a container what bits of markup are custom actions.
You can write the XML equivalent of the above syntax as follows −
<jsp:directive.taglib uri = "uri" prefix = "prefixOfTag" />
When you use a custom tag, it is typically of the form <prefix:tagname>. The prefix is the same
as the prefix you specify in the taglib directive, and the tagname is the name of a tag
implemented in the tag library.

By:- Anuja Jain assistant professor, VSIT, VIPS


Example
For example, suppose the custlib tag library contains a tag called hello. If you wanted to use
the hello tag with a prefix of mytag, your tag would be <mytag:hello> and it will be used in
your JSP file as follows −
<%@ taglib uri = "http://www.example.com/custlib" prefix = "mytag" %>

<html>
<body>
<mytag:hello/>
</body>
</html>

JSP Standard Tag(Action Element)


 JSP specification provides Standard(Action) tags for use within your JSP
pages.
 These tags are used to remove or eliminate scriptlet code from your JSP
page because scriplet code are technically not recommended nowadays.
 It's considered to be bad practice to put java code directly inside your JSP
page.
 There is only one syntax for the Action element, as it conforms to the XML
standard −

 <jsp:action_name attribute = "value" />

 There are many JSP Standard Action tag which are used to perform some
specific task.

By:- Anuja Jain assistant professor, VSIT, VIPS


 You can dynamically insert a file, reuse JavaBeans components, forward
the user to another page, or generate HTML for the Java plugin.

The following are some JSP Standard Action Tags available:

Action Tag Description

jsp:forward forward the request to a new page


Usage : <jsp:forward page="Relative URL" />

jsp:useBean instantiates a JavaBean


Usage : <jsp:useBean id="beanId" />

jsp:getProperty retrieves a property from a JavaBean instance.


Usage :
<jsp:useBean id="beanId" ... />
...
<jsp:getProperty name="beanId" property="someProperty" .../>
Where, beanName is the name of pre-defined bean whose property we
want to access.

jsp:setProperty store data in property of any JavaBeans instance.


Usage :
<jsp:useBean id="beanId" ... />
...
<jsp:setProperty name="beanId" property="someProperty"
value="some value"/>
Where, beanName is the name of pre-defined bean whose property we

By:- Anuja Jain assistant professor, VSIT, VIPS


want to access.

jsp:include includes the runtime response of a JSP page into the current page.

jsp:plugin Generates client browser-specific construct that makes an OBJECT or


EMBED tag for the Java Applets

jsp:fallback Supplies alternate text if java plugin is unavailable on the client. You can
print a message using this, if the included jsp plugin is not loaded.

jsp:element Defines XML elements dynamically

jsp:attribute defines dynamically defined XML element's attribute

jsp:body Used within standard or custom tags to supply the tag body.

jsp:param Adds parameters to the request object.

jsp:text Used to write template text in JSP pages and documents.


Usage : <jsp:text>Template data</jsp:text>

Common Attributes
There are two attributes that are common to all Action elements: the id attribute
and the scope attribute.

Id attribute
The id attribute uniquely identifies the Action element, and allows the action to
be referenced inside the JSP page. If the Action creates an instance of an object,
the id value can be used to reference it through the implicit object PageContext.

By:- Anuja Jain assistant professor, VSIT, VIPS


Scope attribute
This attribute identifies the lifecycle of the Action element. The id attribute and
the scope attribute are directly related, as the scope attribute determines the
lifespan of the object associated with the id. The scope attribute has four
possible values: (a) page, (b)request, (c)session, and (d) application.

The <jsp:include> Action

 This action lets you insert files into the page being generated.
 The syntax looks like this −
<jsp:include page = "relative URL" flush = "true" />
 Unlike the include directive, which inserts the file at the time the JSP page
is translated into a servlet, this action inserts the file at the time the page is
requested.
 The include action allows you to include either a static or dynamic resource
in a JSP file. The results of including static and dynamic resources are quite
different. If the resource is static, its content is inserted into the calling JSP
file. If the resource is dynamic, the request is sent to the included
resource, the included page is executed, and then the result is included in
the response from the calling JSP page.

Example
Let us define the following two files (a)date.jsp and (b) main.jsp as follows −

Following is the content of the date.jsp file −


<p>Today's date: <%= (new java.util.Date()).toLocaleString()%></p>

By:- Anuja Jain assistant professor, VSIT, VIPS


Following is the content of the main.jsp file −
<html>
<head>
<title>The include Action Example</title>
</head>

<body>
<center>
<h2>The include action Example</h2>
<jsp:include page = "date.jsp" flush = "true" />
</center>
</body>
</html>
Let us now keep all these files in the root directory and try to access main.jsp.
You will receive the following output −

The include action Example

Today's date: 12-Sep-2010 14:54:22

Difference b/w include Directive and include Action :-

By:- Anuja Jain assistant professor, VSIT, VIPS


II.jsp:forward

• The jsp:forward action element is used to terminate the execution of the


current JSP page and switch control to another resource. You can forward
control either to a static resource or a dynamic resource.

 <jsp:forward page="relativeURL"/> If you want to pass information


to the included resource, use the second syntax:

 <jsp:forward page="relativeURL"> ( <jsp:param . . . /> )*


</jsp:include> The page attribute represents the URL of the included
resource in the local server.

By:- Anuja Jain assistant professor, VSIT, VIPS


jsp:plugin, jsp:params, jsp:fallback

• The <jsp:plugin> action is used to generate browser-dependent HTML code


(OBJECT or EMBED) that displays and executes a Java Plugin software (Java
applet or a JavaBean component) in the current JSP page.
The <jsp:params> and<jsp:fallback> actions are optional sub elements.

• Briefly, the <jsp:params> element sends parameter names and values to


the applet or Bean, while <jsp:fallback>provides a message for the user in
the event the applet or Bean does not start.

By:- Anuja Jain assistant professor, VSIT, VIPS


JavaBean Components

•Any Java class that follows certain design conventions is a JavaBeans component.
•A Java class with the following features is called a JavaBean:
A no-argument constructor
Properties defined with accessors and mutators (getter and setter method)
Class must not define any public instance variables
The class must implement the java.io.Serializable interface

Example of a JavaBean

By:- Anuja Jain assistant professor, VSIT, VIPS


JSP Action - jsp:useBean

Using a JavaBean in JSP page

JavaBeans can be used in any JSP page using the <jsp:useBean> tag

<jsp:useBean id=“myBeanAttribute” class=“myPack.MyBean”
scope=“request | page | session | application”/>

Once the bean is defined in JSP, we can get it’s properties using jsp:getProperty.
We can use jsp:setProperty to set the property values of a java bean.

JSP Action - jsp:setProperty

•The <jsp:setProperty> action tag sets a property value or values in a


bean using the setter method.

<jsp:setProperty name=“bean” property=“userName”


value=“Sunil”/>

JSP Action - jsp:getProperty

•The <jsp:getProperty> action tag returns the value of the property.

By:- Anuja Jain assistant professor, VSIT, VIPS


Using <jsp:useBean>

•TestBean.java

 TestBean.jsp

Using <jsp:useBean>: Output

By:- Anuja Jain assistant professor, VSIT, VIPS


Got Message …
Hello JSP

Implicit Objects in JSP

 Implicit objects in jsp are the objects that are created by the container
automatically making them available to the developers.
 These objects are created by JSP Engine during translation phase (while
translating JSP to Servlet). They are being created inside jspService()
method so we can directly use them within Scriptlet without initializing and
declaring them.
 A variable that matches one of the implicit objects is evaluated
by ImplicitObjectResolver, which returns the implicit object.
The ImplicitObjectResolver resolves the sessionScope implicit object only.

 JSP provide access to some implicit object which represent some commonly
used objects for servlets that JSP page developers might need to use.
 For example you can retrieve HTML form parameter data by
using request variable, which represent the HttpServletRequest object.

By:- Anuja Jain assistant professor, VSIT, VIPS


• There are a total of nine implicit objects, which are listed as follows:

S.No Object Class

1 application javax.servlet.ServletContext

2 config javax.servlet.ServletCofig

3 exception java.lang.Throwable

4 out javax.servlet.jsp.JspWriter

5 page java.lang.Object

6 PageContext javax.servlet.jsp.PageContext

7 request javax.servlet.ServletRequest

By:- Anuja Jain assistant professor, VSIT, VIPS


8 response javax.servlet.ServletResponse

9 session javax.servlet.http.HttpSession

By:- Anuja Jain assistant professor, VSIT, VIPS


• Application: These objects has an application scope. These objects are
available at the widest context level, that allows to share the same
information between the JSP page's servlet and any Web components with
in the same application.

• Config: These object has a page scope and is an instance of


javax.servlet.ServletConfig class. Config object allows to pass the
initialization data to a JSP page's servlet. Parameters of this objects can be
set in the deployment descriptor (web.xml) inside the element <jsp-file>.
The method getInitParameter() is used to access the initialization
parameters.

• Exception: This object has a page scope and is an instance of


java.lang.Throwable class. This object allows the exception data to be
accessed only by designated JSP "error pages."

• Out: This object allows us to access the servlet's output stream and has a
page scope. Out object is an instance of javax.servlet.jsp.JspWriter class. It
provides the output stream that enable access to the servlet's output
stream.

• Page: This object has a page scope and is an instance of the JSP page's
servlet class that processes the current request. Page object represents the
current page that is used to call the methods defined by the translated
servlet class, The page object represents the generated servlet instance
itself, it is same as the "this" keyword used in a Java file.

Example:- <%= ((Servlet)page).getServletInfo () %>

By:- Anuja Jain assistant professor, VSIT, VIPS


• Pagecontext: PageContext has a page scope. Pagecontext is the context for
the JSP page itself that provides a single API to manage the various scoped
attributes. PageContext object represents the environment for the page
also provides access to several page attributes like including some static or
dynamic resource.

By:- Anuja Jain assistant professor, VSIT, VIPS


By:- Anuja Jain assistant professor, VSIT, VIPS
• Request: Request object has a request scope that is used to access the
HTTP request data, and also provides a context to associate the request-
specific data. Request object implements javax.servlet.ServletRequest
interface. It uses the getParameter() method to access the request
parameter. The container passes this object to the _jspService() method.

• Response: This object has a page scope that allows direct access to the
HTTPServletResponse class object. The response object also defines the
interfaces that deal with creating new HTTP headers. Through this object
the JSP programmer can add new cookies or date stamps, HTTP status
codes etc.

• Session: Session object has a session scope that is an instance of


javax.servlet.http.HttpSession class. Perhaps it is the most commonly used
object to manage the state contexts. The session object is used to track
client session between client requests. This object persist information
across multiple user connection.

By:- Anuja Jain assistant professor, VSIT, VIPS


Load-on-startup tag

By:- Anuja Jain assistant professor, VSIT, VIPS


Design Strategies

• Many dozens of design strategies have been developed for web


applications.

1. Page-centric Design : Requests are made to JSPs, and the JSPs respond to
clients

2. Dispatcher Design: Requests are sent to JSPs or servlets that then forward the
requests to another JSP or servlet

3. View Helper Strategy: The View Helper pattern specifies that you use helpers
to adapt model data to the presentation layer of an application. When developing
helpers for JSP pages, you have two choices. You could use either JavaBeans or
custom tags.

3.1 JavaBeans Helper Strategy- The built-in JSP tags that enable you
to work with JavaBeans are simple and intuitive to use. JavaBeans can do more
than simply retrieve data items from the model. They can also format specific
data items, perform calculations, or generate large blocks of content.

• 3.2 Custom Tag Helper Strategy- For more complex model


adaptations, custom tags have the ability to embed Java code
and perform several iterations over the data while providing
the page designer with a simple tag with which to work.

4. Model Separation Strategy- Sometimes preferable, strategy is to have the


development team build dummy data into its models so that designers can do
their work as if the real model exists, also ensuring that the model they're
working with is always the correct one

• In all cases, the goal is to separate logic from presentation and


to separate as many concerns in the logic as possible

By:- Anuja Jain assistant professor, VSIT, VIPS


Reference

• O’Reilly- Head First Servlets and JSP by Kathy Sierra.

• http://www.studytonight.com

• https://www.javatpoint.com

• https://way2java.com

• https://docs.oracle.com

• “Inside Servlets” by Dustin R. Callaway

• “Enterprise Java Computing: Applications and Architectures” by Govind


Sesadari

By:- Anuja Jain assistant professor, VSIT, VIPS

You might also like