Unit7 Jsp Part II
Unit7 Jsp Part II
Dynamic contents means the contents that get changed based on the user inputs or states of
external system or on some runtime conditions. JSP helps in handling such conditions. There are
various ways by which JSP handles the dynamic contents such as use of:
1. Directive elements
2. Java Beans
3. Scripting elements
4. Standard tag libraries
5. Standard and custom actions
6. Expression language.
1. Directive Elements:
Directive elements are used to specify the information about the page.
Syntax:
<%@ directivename attr1=”value1” attr2=”value2” %>
The directive names and attribute names are case sensitive.
Examples of some directives are:
Page
Include
Taglib
Attribute
Tag
Variable
i. Page directive:
This directive can only be used in JSP pages, not tag files. It defines page dependent
attributes, such as scripting language, error page, buffer requirements.
Syntax:
<%@ Page [autoflush=”true/false”] [buffer=”skb/NNkb/None]
[ContentType=”MIMEType”] [errorPage=”page or ContextRelativePath”] [extends=”classname”]
[import=”packagelist”] [info=”info” ][isErrorPage=”true/false”] [isThreadSafe=”true/false”]
[language=”java/language”] [pageEncoding=”encoding”] [session=”true/false”] %>
Example:
<%@ page language=”java” ContentType=”text/html” %>
It includes a static file, merging its content with the including page before the combined
results is converted to JSP page implementation class.
Example:
%>
Example:
This directive can only be used in tag files. It declares the attributes that tag file supports.
Syntax:
Example:
v. Tag directive:
This directive can only be used in tag files.
Syntax:
<%@ tag [body-content=”empty/scriptless/tagdependent”] [description=”desc”] [display-
name=”displayname”] [dynamic-attributes=”attrcolvar”] [import=”packagelist”]
[language=”java/language”] [page-encoding=”encoding”] %>
Example:
<%@ tag body-content=”empty” %>
Scripting.jsp file:
<html>
<body>
<% count++;
out.println(new Date().toString());
%>
</body>
</html>
Web.xml file:
<web-app>
</web-app>
2. Java Beans:
Java beans are reusable components. We can use simple java beans in a JSP. This
helps us in keeping the business logic separate from presentation logic. Beans are used in
the JSP pages as instance of a class. We must specify the scope of the bean in the JSP
page. Here scope of the bean means the range time span of the bean for its existence in
the page.
There are various scopes using which the bean can be used in the JSP page.
i. Page scope: The bean object gets disappeared as soon as the current page gets
discarded. The default scope for a bean in the JSP page is page scope.
ii. Request scope: the bean object remains in the existence as long as the request object is
present.
iii. Session scope: A session can be defined as the specific period of time the user spends
in browsing the site. Then the time spent by the user in starting and quitting the site is
one session.
iv. Application scope: during application scope the bean will gets stored to
ServletContext. Hence particular bean is available to all the servlets in the same web
application.
Getname.html file:
<HTML>
<BODY>
<P><INPUT TYPE=SUBMIT>
</FORM>
</BODY>
</HTML>
Nextpage.jsp file:
<HTML>
<BODY>
You entered<BR>
</BODY>
</HTML>
Savename.jsp file:
<HTML>
<BODY>
<A HREF="NextPage.jsp">Continue</A>
</BODY>
</HTML>
Web.xml file:
<web-app>
</web-app>
Output:
The objects which we access in our JSP page, without any explicit declaration are called as
implicit objects. Implicit objects are exposed by the JSP container and can be seen in the
generated servlet of a JSP page.
Implicit objects are advantageous because, they don’t require the JSP authors to explicitly
declare and initialize a few of the servlet objects, which is a difficult task.
Conditional processing:
Sometimes to built the complex logic we require conditional statements. We can embed
JAVA conditional statements in JSP. This task can be done by scriptlets. The syntax for
scriptlets is:
<% any java code %>
Sample program for conditional processing:
<%@ page language=”java” ContentType=”text/html” %>
<html>
<head><title>Introduction to scriptlet</title></head>
<body>
<h1>
<% out.println(“JSP is very interesting”); %>
</h1>
</body>
</html>
Web.xml file:
<web-app>
</web-app>
Output:
Scripting.jsp file:
<html>
<body>
<% count++;
out.println(new Date().toString());
%>
</body>
</html>
Web.xml file:
<web-app>
</web-app>
Directory structure:
Output:
There are some predefined variables that can be used while defining the expressions. These
variables can be used along with the implicit object.
JSP allow us to use the user defined variables and methods using declaration. The variables
and methods can be used along with scriptlets and expression. The syntax for declaration is as
follows:
return msg;
%>
<html>
<head>
<title>Use of Method</title>
</head>
<body>
<%
<br>
</body>
</html>
Web.xml file:
<web-app>
</web-app>
Output:
While developing any application we may come across several errors. We may get some
syntactical errors during development of JSP pages.
Errors are of two types:
Logical error
Dealing with runtime errors
Catch exceptions
Request processing
Business logic
Presentation logic.
This three partitioned architecture is known as “Model View Controller (MVC) model.
We will make use of bean class in which the methods for getting and setting the counter value
are written. There will be three JSP pages. On the first JSP page we will use the instance of a
bean and increment the counter value, when the counter reaches the value 100 then the control
will be passed to another JSP page using <jsp:forward> action. From their the control will be
passed to third page by using the hyperlink used in second page.
<head>
<strong>User name:</strong>
<input type=”text” name=”username”><br>
<strong>Password:</strong>
<input type=”password” name=”password”>
<input type=”submit” value=”Enter”>
</form>
</body>
</html>
second_page.jsp file:
<%@ page language=”java” %>
<%
String username=request.getParameter(“username”);
String password=request.getParameter(“password”);
session.setAttribute(“username”,username);
session.setAttribute(“password”,password);
%>
<html>
<head>
<title>session object</title>
</head>
<body>
<h3><a href=”third_page.jsp”>click here to view the other session</a>
</h3>
String password=(String)session.getAttribute(“password”);
%>
<html>
<head><title>end of session page</title></head>
<body>
<strong>User Name is:<%= username %></strong>
<br>
<strong>Password is:<%= password %></strong>
</body>
</html>
Output:
The memory usage calculation for session scope is bit complex. Because total number of
objects in session scope, depends upon number of concurrent sessions. Hence to compute
memory usage in current session we must know certain things such as:
Implicit Objects
Jsp implicit objects are used in a JSP page to make the page dynamic.
The dynamic content can be created and accessed by using Java objects with in the scripting
elements.
JSP implicit objects are predefined objects that are accessible to all JSP Pages.
These objects are called implicit objects because you don’t need to instantiate these objects.
The jsp container automatically instantiates these object while writing the script content in the
scriplet and expression tags.
During the translation of a JSP page,the JSP engine initiates Nine most commonly used implicit objects in
the _jspService() method.
Hello, <b><%=request.getParameter("name")%></b><br/><br/>
Your request details are <br/><br/>
<table border="1">
<tr><th>Name</th><th>Value</th></tr>
<tr><td>request method</td>
<td><%= request.getMethod() %></td></tr>
<tr><td>request URI</td>
<td><%= request.getRequestURI() %></td></tr>
<tr><td>request protocol</td>
<td><%= request.getProtocol() %></td></tr>
<tr><td>browser</td>
<td><%= request.getHeader("user-agent") %></td></tr>
</table>
<%if (session.getAttribute("sessionVar")==null) {
session.setAttribute("sessionVar",new Integer(0));
}%>
<table>
<tr><th align=left>Would you like to see use of remaining imlplicit objects?</th></tr>
<tr>
<form name=form1 action="pageContext.jsp" method="post">
<td><input type="radio" name="other" value="Yes">Yes</td>
<td><input type="radio" name="other" value="No" > No</td></tr>
<tr><td><input type="submit" value="Submit"></td></tr>
</body></html>
<BODY>
<%
if("Yes".equals(request.getParameter("other")))
{
pageContext.forward("other");
}
%>
</BODY>
</HTML>
count=Integer.parseInt( sc.getInitParameter("count"));
System.out.println("In jspInit");
}
%>
Count value without using config implicit object: <b> <%=count%></b> <br/>
<%
this.log("log message");
((HttpServlet)page).log("anothermessage");
ServletContext ct = config.getServletContext();
out.println("Value of sessionVar
is:"+" <b>"+session.getAttribute("sessionVar")+"</b><br/>");
</body> </html>
The same business logic can be used many times by the use of custom tag.
The custom tags used in the JSP Page are translated into servlet.
1. Eliminates the need of srciptlet tag The custom tags eliminates the need of scriptlet tag
which is considered bad programming approach in JSP.
2. Separation of business logic from JSP The custom tags separate the the business logic
from the JSP page so that it may be easy to maintain.
3. Reusability The custom tags makes the possibility to reuse the same business logic again
and again.
4. Readability The use of custom tags enhances the readability of the used codes in a JSP
page.The readability increases by encapsulating the use of the Java codes in a JSP page.
5. Maintainability this feature enables the user to reduce the duplicity of codes present in a
JSP page.
There are two ways to use the custom tag. They are given below:
A)First Way
<prefix:tagname attr1=value1....attrn=valuen />
B)Second Way
A tag library is a collection of events that encapsulate some functionality to be used from with in
a JSP Page
A tag library is made available to a JSP page through a taglib directive that identifies the tag
library through a URI.
Syntax:
Elements of TLD
description
display-name
icon
name
path
example
tag-extension
uri
tlib-version
validator
listener
The javax.servlet.jsp.tagext package contains classes and interfaces for JSP custom tag API. The JspTag is the
root interface in the Custom Tag hierarchy.
JspTag interface
The JspTag is the root interface for all the interfaces and classes used in custom tag. It is a marker interface.
Tag interface
The Tag interface is the sub interface of JspTag interface. It provides methods to perform action at the start and
end of the tag.
There are four fields defined in the Tag interface. They are:
IterationTag interface
The IterationTag interface is the sub interface of the Tag interface. It provides an additional method to
reevaluate the body.
public int doAfterBody()throws JspException it is invoked by the JSP page implementation object
after the evaluation of the body. If this method returns EVAL_BODY_INCLUDE, body content will
be reevaluated, if it returns SKIP_BODY, no more body content will be evaluated.
TagSupport class
The TagSupport class implements the IterationTag interface. It acts as the base class for new Tag Handlers. It
provides some additional methods also.
1. Create the Tag handler class and perform action at the start or at the end of the tag.
2. Create the Tag Library Descriptor (TLD) file and define tags
3. Create the JSP file that uses the Custom tag defined in the TLD file
To create the Tag Handler, we are inheriting the TagSupport class and overriding its
method doStartTag().To write data for the jsp, we need to use the JspWriter class.
The PageContext class provides getOut() method that returns the instance of JspWriter class. TagSupport
class provides instance of pageContext bydefault.
// MyTagHandler.java
Tag Library Descriptor (TLD) file contains information of tag and Tag Hander classes. It must be contained
inside the WEB-INF directory.
File: mytags.tld
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE taglib
PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"
"http://java.sun.com/j2ee/dtd/web-jsptaglibrary_1_2.dtd">
<taglib>
<tlib-version>1.0</tlib-version>
<tag>
<name>today</name>
<tag-class>com.cmrcet.customtags.MyTagHandler</tag-class>
</tag>
</taglib>
Let's use the tag in our jsp file. Here, we are specifying the path of tld file directly. But it is recommended to
use the uri name instead of full path of tld file.
It uses taglib directive to use the tags defined in the tld file.
//Index.jsp
Directory Structure:
Execution of the methods implemented within tag handler classes is triggered by these events
along the tag handler life cycle. The sequence of method invocation within the tag handler life
cycle is as follows:
NOTE
At this point in the life cycle, the writer in the pageContext() is returned to the
parent JspWriter.
Next, the doEndTag() method is invoked. This method is commonly used to perform post–body
tag processing, close server-side resources, or to write output to the surrounding scope using
the pageContext.getOut() method.
The doEndTag() method returns one of two different values depending on the nature of your
page:
To conclude the tag handler life cycle, the release() method is invoked just before the tag
handler instance is made available for garbage collection.