Slide 11 Dev JSP
Slide 11 Dev JSP
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.
Syntax:
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>
Output:
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:
3. Scripting elements:
Scripting allows us to embed java code in a JSP page and scripting elements
(scriptlets, declaration and expressions) allows us to do scripting. Scripting elements are
executed at request processing time and are used for a variety of purposes including
manipulation of objects, perform calculation on runtime variables values, etc.
4. Standard tag libraries:
JSTL stands for JSP standard tag libraries. This tag library is useful for performing
some common task such as condition execution, loop execution, data processing and so
on. JSTL allows the programmer to embed the logic in JSP page without using java code.
The tag library makes use of some standard set of tags. To install JSTL in tomcat just
copy the jstl.jar and standard.jar files in the lib folder of WEB-INF directory to your
tomcat. Some tags are : <c:out>, <c:set>, <c:if>, <c:choose> etc.
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:
<h1>
<% out.println(“JSP is very interesting”); %>
</h1>
</body>
</html>
Web.xml file:
<web-app>
</web-app>
Output:
Displaying Values Using An Expression To Set An Attribute:
The JSP expressions are used to insert java values directly into the output. The syntax of
using expression is as follows:
<%= Expression code %>
This expression gets evaluated at runtime and then the result will get displayed on the web
browser. Thus tags <%= and %> is used.
Sample program for using an expression:
Scripting.jsp file:
<html>
<body>
<% count++;
out.println(new Date().toString());
%>
<%= count %>
</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:
Error Handling & Debugging:
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:
</body>
</html>
Error will be:
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>
<title>registration form</title>
</head>
<body>
<form method=”post” action=”second_page.jsp”>
<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>
</body>
third_page.jsp file:
<%@ page language=”java” % >
<% String username=(String)session.getAttribute(“username”);
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:
Sharing data between JSP pages using application data:
Data need to be shared between different components types like servlets, filters. JSP pages
when they need by any application. This is used by servlets while creating java beans and
passing them to JSP pages that are responsible for displaying those beans.
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>
</form>
</table>
</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/>");
out.println("Server name and version using config implicit
object:"+" <b>"+ct.getServerInfo()+"</b><br/>");
out.println("Value of context parameter param1 get using application implicit object:"
+" <b>"+application.getInitParameter("param1")+"</b><br/>");
out.println("Count value retrieved using config implicit object:"
+" <b>"+config.getInitParameter("count")+"</b>");
%>
</body> </html>
Custom Tags in JSP
Custom tags are user-defined tags. They eliminates the possibility of scriptlet tag and separates
the business logic from the JSP page.
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
JSP Custom Tag API
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.
Fields of Tag interface
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
package com.cmrcet.customtags;
import java.util.Calendar;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;
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>
<jsp-version>1.2</jsp-version>
<short-name>simple</short-name>
<uri>http://tomcat.apache.org/example-taglib</uri>
<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:
Output:
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:
Once a JSP tag is encountered, the methods setPageContext() and setParent() are
invoked to set up an environment context for the tag handler. These methods don't have
to be implemented if you're using the tag support abstract classes
(TagSupport and BodyTagSupport) for development (as opposed to the tag interfaces).
Next, the setter methods for tag attributes are invoked. Tag handlers must define setters
and getters for all attributes.
Next, the doStartTag() method is invoked. This method is commonly used to initialize
any resources for execution of your tag logic. This method should return one of three
different values depending on the nature of your tag body, assuming that a tag body is
implemented:
o Tag.SKIP_BODY should be returned if you're implementing a simple (empty body)
tag. On return of this value, the doEndTag() method is invoked.
o Returning Tag.EVAL_BODY_INCLUDE causes evaluation and inclusion of tag body
contents. Only classes implementing the Tag interface or extending
the TagSupport class may return this value. On return of this value,
the doEndTag() method is invoked.
o Tag.EVAL_BODY_TAG causes evaluation of the tag body, followed by invocation of
the doInitBody() method. Only classes implementing the BodyTag Interface or
extending the BodyTagSupport class may return this value.
If EVAL_BODY_TAG is returned, the setBodyContent()method is invoked. This method
creates a reference to the BodyContent (a JspWriter) buffer, which may be used by
the doAfterBody() method for processing later in the life cycle. The BodyContentbuffer
contains all output from the tag, including any body content, if any. (At this point, the
client does not have access to any output derived from the tag). If the tag is writing output
to the JSP page, that output must be written to the parent-scoped JspWriter (via
the getEnclosingWriter() method) before the end of the doEndTag() method. You
don't have to implement the setBodyContent() method if you're implementing
the BodyTagSupport class. This class has the convenience of
thegetBodyContent() method, which provides a reference to BodyContent.
If EVAL_BODY_TAG is returned, the doInitBody() method is invoked. This method is
invoked immediately prior to the body tag being evaluated for the first time. This method
is commonly used to prepare scripting variables or place content into
theBodyContent JspWriter. As discussed earlier, content placed into the BodyContent is
buffered and isn't available to the JSP page at this point.
If EVAL_BODY_TAG is returned, the doAfterBody method is invoked. This method is
invoked immediately after the tag body is evaluated and added to the BodyContent. This
method is commonly used to process work based on the results of the body tag
evaluation. To access the evaluated body, use the getBodyContent() method if you
extended the BodyTagSupport class, or use the setBodyContent() method if you
implemented the BodyTag interface (you should have stored a BodyContent instance).
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.