JSP and JSTL
JSP and JSTL
• <context-param>
</context-param>
Implicit object - config
• This variable is the ServletConfig object for this page
• In principle you can use it to read initialization parameters
• <init-param>
</init-param>
• In the servlet code
• getSerlvetConfig().getInitParameter("paramName");
• note:
• * Servlet Init Parameter Can't be used until the Servlet is initialized!!
• * Config parameter is read only once!!
• * Init Parameter is only for Servlet!! Each Servlet has it's own parameter
• In practise initialization parameters are read from jspInit not from _jspService()
• You can call getServletConfig.getInitParameter(“paramName”) in jspInit method.
Implicit object - pageContext
• the pageContext variable stores the value of PageContext object associated with the current
page.
• A pageContext implicit object is used for storing and retrieving page-related information and
sharing objects within the same translation unit and same request. Also used as a
convenience class that maintains a table of all the other implicit objects.
• pageContext is of the type PageContext and has a single point of access to many of the page
attributes.
• It has methods which can be used to populate other implicit objects
• pageContext .getRequest(),
• pageContext .getResponse,
• pageContext .getOut,
• pageContext .getSession()
• It provides convenience methods to get and set attributes in different scopes
• pageContext.setAttribute(attribute,value,scope)
• pageContext.getAttribute(attribute,scope);
• To include the output of another resource
• pageContext.forward ("other.jsp");
• pageContext.include ("other.jsp");
implicit object - pageContext
• It stores referece to the implicit objects. The following example shows how PageContext is used to
populate other implicit objects. public void _jspService (HttpServletRequest request,
HttpServletResponse response)
throws java.io.IOException, ServletException {
...
try {
...
application = pageContext.getServletContext ();
config = pageContext.getServletConfig ();
session = pageContext.getSession ();
out = pageContext.getOut ();
...
} catch (Throwable t) {
...
} finally {
...
}
}
implicit object - pageContext
• Provides convenience methods to get and set attributes in different scopes. This
example uses attributes to save and retrieve data in each of the four scopes: <%
// Save data
pageContext.setAttribute("attr1", "value0"); // PAGE_SCOPE is the default
pageContext.setAttribute("attr2", "value1", PageContext.PAGE_SCOPE);
pageContext.setAttribute("attr3", "value2", PageContext.REQUEST_SCOPE);
pageContext.setAttribute("attr4", "value3", PageContext.SESSION_SCOPE);
pageContext.setAttribute("attr5", "value4", PageContext.APPLICATION_SCOPE);
%>
• Provides convenience methods for transferring requests to other resources in your application:
• PageContext
• void include (String relativeURL)
• Includes the output of another resource in the output of the current page.
• Same as ServletRequest.getRequestDispatcher ().include ();
• For example, to forward a request to another resource from a servlet, we have to write the
following to lines:
• In a JSP page, we can do that in just one line by using the pageContext variable:
• pageContext.forward ("other.jsp");
implicit object - pageContext
• ServletConfig
• <init-param>
</init-param>
• In the servlet code
• getSerlvetConfig().getInitParameter("paramName");
• note:
• * Servlet Init Parameter Can't be used until the Servlet is initialized!!
• * Config parameter is read only once!!
• * Init Parameter is only for Servlet!! Each Servlet has it's own parameter
Difference between ServletConfig and ServletContext
• ServletContext
• <context-param>
</context-param>
• In the servlet code
• getSerlvetContext().getInitParameter("paramName");
• note:
• * Context init parameter is for whole web app!!
• * Context init only need to be defined in one DD and can be used
anywhere in web app!!
• * In a distributed environment, one Servletcontext per JVM
implicit object - page
• The JSP implicit page object is an instance of the java.lang.Object class. It represents the current JSP
page.
• That is, it serves as a reference to the java servlet object that implements the JSP page on which it is
accessed. It is not recommended to us this because it consumes large memory.
• The page object works like “this” key word in java.
• In the generated servlet, the variable is declared as follows
• Object page = this;
• Parent reference can be used to hold child class object but, by using that reference we are allow to
call only the methods available in the parent class.
• <jsp:include page=“/fragments/StandardHeading.jsp”>
<jsp:param name=“bgColor” value=“YELLOW”>
</jsp:include>
this element is used to add or replace the parameters of
the included page
Note: these parameter do not apply to the main page
Note: if the main page receives a request parameter
through the url which is also specified in the included
page the value from jsp:param takes precedence only in
the included page.
forwarding requests with jsp:forward
• <jsp:forward page=“/examples/page1.jsp” />
• you can use jsp:forward to obtain the out completely
from the page defined by the page attribute.
• To use jsp:forward the main page must not have any
output. This construct is used only to direct the output to
the auxillary page.
• jsp:forward action is used to permanently transfer
processing from one jsp to another on the local server.
• Any content generated by the original page is discarded
and processing begins anew at the second JSP.
• browser is not notified of the forwarding and displays the
original url.
jsp:plugin -
• the jsp:plugin element is used to insert applets into the JSP pages. These
applets use the java plugin.
• No matter what approach you use for servlets, the applet.class files must
go in the web-accessible directories and not in WEB-INF/classes. The
browser, not the server uses them.
• The jsp:plugin element does not add any Java capability to the browser.
It merely simplifies the creation of cumbersome OBJECT and EMBED tags
needed by java 2 plug in.
• You could replace
<APPLET CODE=“MyApplet.class” width=475 height=350>
</APPLET>
• with
<jsp:plugin type=“applet” code=“MyApplet.class” width=“475 “
height=“350”>
</jsp:plugin>
jsp:fallback
• the jsp:fallback element provides alternate text to browsers that
do not support OBJECT or EMBED e.g.
• replace
• <APPLET CODE=“Myapplet.class” WIDTH=“475” HEIGHT=“350”>
<B>Error: this sample requires java</B>
</APPLET>
with
<jsp:plugin type=“applet” code=“MyApplet.class” width=“475 “
height=“350”>
<jsp:fallback>
<B>Error: this sample requires Java.</B>
</jsp:fallback>
</jsp:plugin>
What are java beans
• beans are simple java classes that are written in standard format. These
classes follow the following rules:
• A bean class must have a zero argument constructor. You can satisfy this
requirement either by defining such a constructor or by omitting all
constructors.
• A bean class should have no public instance variables (fields). A class
should use public accessor methods instead of allowing direct access to
instance variables.
• Persistent values should be accessed through methods called getXxx and
setXxx. If a class stores the current number of passengers, you might
have methods named getNumPassengers (which takes no argument and
returns int)and setNumPassengers(which takes an argument of the type
same as the return type of get and has void return type). In such a case
your bean class is said to have a property numPassengers.
• With boolean values you are permitted to use a method called isXxx()
instead of getXxx().
Building Beans – jsp:useBean
• <jsp:useBean id=“beanName” class=“package.class” />
• Note: you must use fully classified class name for the class attribute of
jsp:useBean
• Note: the bean class definition should be placed in the same directory where
servlets can be installed (/WEB-INF/classes/subdirectoryMatchingPackageName,
not in the directory which contains the JSP file.
• place your jar file in WEB-INF/lib
• you use the type attribute along with the class attribute when you want the
variable being declared to have a type that is a superclass of the actual bean
type or is an interface that the bean implements.
• use the type attribute without the class attribute when the bean already exists
and you want to access an existing object without creating a new object.
• If you supply the scope attribute the jsp:useBean element can either build a new
bean or access a preexisting one. the scope attribute associates the bean with
more than the current page.
• jsp:useBean lets you load a bean to be used in the JSP page.
Accessing bean properties – jsp:getProperty
• <jsp:getProperty name=“beanName”
property=“propertyName” />
• with jsp:useBean, the bean name is given by id
attribte. With jsp:getProperty and
jsp:setProperty the bean name is given by the
name attribute.
Sample Code
• <jsp:useBean id=“stringBean”
class=“coreservlets.StringBean” />
• <LI>Initial value: <jsp:getProperty
name=“stringBean” property=“message” />
• <jsp:setProperty name=“stringBean”
property=“message” value=“best string bean” />
• <LI> Value after setting property: <jsp:getProperty
name=“stringBean” property=“message” />
Setting bean property – jsp:setProperty
• <jsp:setProperty name=“beanName”
property=“propertyName”
value=“propertyValue” />
• this element is used to set the bean properties
as below
• <% book1.setTitle(“Core Servlets and JSP”);
%>
Associating all bean properties with request parameters
• this can be done using the below syntax
• <jsp:usebean id=“entry”
class=“coreservlets.SaleEntry” />
• <jsp:setProperty name=“entry” property=“*” />
• this saves you the bother of performaing conversions for
many built-in types.
• no action is taken when input parameter is missing
• Automatic type conversion does not guard against illegal
values as effectively as does manual type conversion.
• Bean property names and request parameters are case
sensitive.
Sharing beans
• using the scope attribute with jsp:useBean makes the system look for existing bean with the specified name
in the designated location. Only when the system fails to find a preexisting bean does it create a new one.
• <jsp:useBean … scope=“page” />
• <jsp:useBean … scope=“request” />
Note: two JSP pages or a JSP page and a servlet will share request objects when you use jsp:include;
jsp:forward or include or forward methods of the RequestDispatcher
• <jsp:useBean … scope=“session” />
• bean is stored in HttpSession object associated with the current request and can be retrieved with:
session.getAttribute(“XYZ”);
• <jsp:useBean … scope=“application” />
• The ServletContext is shared by all servlets and JSP pages in the web application. Values in the serlvet context
can be retrieved as follows:
• getServletContext().getAttribute(“XYZ”);
• application. getAttribute(“XYZ”);
• If you want to set property only if a new bean is created and not if an existing bean is used use the below
element:
• <jsp:useBean id=“counter” class=“coreservlets.AccessCountBean” scope=“application”>
• <jsp:setProperty name=“counter” property=“firstPage” value=“SharedCounts1.jsp” />
• </jsp:useBean>
• Do not use the same bean name for beans stored in different scopes. For every bean use a unique value of id
in jsp:useBean.
Using scope=“page”
• if no scope attribute is specified then scope=“page” since page is the
default scope.
• scope=“page” implies no sharing
• <jsp:useBean id=“pageBean” class=“coreservlets.BakedBean” />
• <jsp:setProperty name=“pageBean” property=“*” />
• <H2>Bean Level:
• <jsp:getProperty name=“pageBean” property=“level” />
• a second page shares the request object of the first page if the
second page is invoked with jsp:include, jsp:forward or the include
or forward methods of the RequestDispatcher
Note: in order to get the shared request object in the second page
you have to again use the syntax jsp:useBean and jsp:getProperty
using scope=“session” and scope=“application”
• <jsp:useBean id=“sessionBean”
class=“coreservlets.BakedBean” />
• <jsp:setProperty name=“sessionBean”
property=“*” />
• <jsp:getProperty name=“sessionBean”
property=“level”
• Note: for ServletContext replace scope=“session”
with scope=“application”
• Note: also change the id=“applicationBean”
Which of the options locate the bean equivalent to the following action?
(Select three)
<jsp:useBean id="address" class="AddressBean" scope="request“ />
a request.getAttribute("address");
b request.getParameter("address");
c getServletContext().getRequestAttribute("address");
d pageContext.getAttribute("address",PageContext.REQUEST_SCOPE);
e pageContext.getRequest().getAttribute("address");
f pageContext.getRequestAttribute("address");
g pageContext.getRequestParameter("address");
Answers: a, d, and e
The Model View Controller (MVC) Architecture
• In this approach the original request is handled by a servlet.
• The servlet invokes the business logic and data access code and
creates beans to represent the result(That’s the model). the bean
is the model.M -MODEL is the component model can be a java
bean, enterprise java bean or a CORBA component object in short
any business model.
• The servlet decides which JSP page is appropriate to present
those particular results and forwards the request there(the JSP
page is the view). The user's perspective whatever he sees VIEW
of the MODEL can be a simple HTML page, can be a DHTML page,
ASP page or JSP page.
• The servlet decides which business logic code applies and which
JSP page presents the results(the servlet is the controller).
Implementing MVC with RequestDispatcher
• Define beans to represent data
• Use a servlet to handle requests
• Populate the beans?
• Store the bean in request session or
ServletContest
• Forward the request to JSP page
• Extract the data from the bean.
Storing the results in request,session, application scope
• Request based data sharing
Servlet
RequestBean value = new RequestBean;
value.setName(“my_name”)
request.setAttribute(“key”,value);
RequestDispatcher dispatcher = request.getRequestDispatcher(“/WEB-INF/SomePage.jsp”
dispatcher.forward(request,response);
JSP page
<jsp:useBean id=“key” type=“somepackage.RequestBean” scope=“request” />
<jsp:getProperty name=“key” property=“someProperty”
• Use the following element for forwarding requests from JSP page
• <jsp:forward page=“relative url” />
• The page attribute is allowed to contain JSP expressions so that the
destination can be computed at run time.
• <% String destination;
• if(Math.random() >0.5){
destination=“/examples/page1.jsp”;
}else{
destination=“/examples/page2.jsp”
} %>
<jsp:forward page=“<%= destination %>” />
• For forwaridng requests form JSP page use RequestDispatcher.forward()
Combining servlet output with one or more JSP pages
• Use RequestDispatcher.include(request,response);
to include the combine the output of servlet with one or
more JSP pages.
RequestDispatcher dispatcher =
request.getRequestDispatcher(“/WEB_INF/header.jsp”
);
dispatcher.include(request,response);
• the serlvet still relies on Jsp pages to produce the
output, but the servlet invokes different JSP pages to
produce different sections of the page.
JSP 2.0 Expression Language
• The JSP expression language cannot be used in servers that support only JSP 1.2 or earlier
• JSP2.0 expression language lets you simplify the presentation layer by replacing java scripting elements or
Jsp:useBean and jsp:getProperty elements with short and readable entries of the form ${expression}
• Deactivating the Expression Language in Entire Web Application
• The EL is automatically deactivated in web applications whose deployment descriptor referes to servlet
specification version 2.3 or earlier.
• The web.xml file which is compatible with JSP 2.0 stipulates that the EL should be activated by default
• Deactivating the Expression Language for all pages in the legacy directory.
• <web-app>
• <jsp-property-group>
• <url-pattern>/legacy/*.jsp</url-pattern>
• <el-ignored>true</el-ignored>
• </jsp-property-group>
• </web-app>
• Deactivating the Expression Language in Individual JSP pages
• <%@ page isEnabled=“false” %>
• Deactivating Individual Expression Language Statements:
• You can replace $ with $ so ${blah} will display ${blah}
• Note: this technique will only work when you are outputting html to a web browser
Accessing scoped variables
• Objects stored in pageContext, request, session, application
scopes are known as scoped variables.
• the servlet needs to use the setAttribute() to store the data in
one of the standard locations
• Expression language has a quick and easy way to access them by
simply using its name used in scope in the expression language
element.
• ${name}
• The above expression searches the PageContext,
HttpServletRequest, HttpSession, ServletContext (in that order)
for an attribute named name.
• The searching stops as soon as the attribute is found i.e. the value
returned is the first attribute found when searching the scopes in
defined order.
Accessing bean properties
• You can access the bean properties using the powerful dot notation.
• To return the firstName property of the scoped variable (say a bean
stored in scope) named customer use
• ${customer.firstName}
• //i.e. customer.getFirstName()
• the EL lets you nest properties arbitrarily. If the NameBean class has an
address property that returned an address object with zipcode
property,n you would access the zipcode with the following form:
• ${customer.address.zipcode}
• the EL lets you replace the dot notation with array notation e.g. replace
• ${name.property}
• with
• ${name[“property”]}
Accessing collections in scope variables
• If attributeName is a scoped variable referring to an array, and entryName is the
index, you can access an entry in the array with the following element:
• ${attributeName[entryName]}
• e.g. ${customerName[0]}
• If supplierName is a scoped variable referring to an ArrayList, and entryName is
the index, you can access the elements of ArrayList with the following element:
• ${supplierName[entryName]}
• e.g. ${supplierName[0]} will output the first element of the Arraylist.
• If stateCapitals is a scoped variable referring to a HashMap interface, whose key
are stateNames and whose values are cityNames, you can access the elements of
HashMap using:
• String cityName = ${stateCapitals[stateName]}
• or
• String cityName= ${stateCapitals.Maryland}
• Note:array notation lets you choose the key at request time whereas the dot
notation requires you to know the key in advaqnce.
Referencing Implicit Objects
• The pageContext object gives you access to the pageContext JSP object.
• Through the pageContext object, you can access the request object. For example, to access the incoming query string for a
request, you can use the expression:
• ${pageContext.request.queryString}
• To output the current session id use the below syntax:
• ${pageContext.session.id}
• To access a request parameter named username:
• ${param.custID}
• Note:The param and paramValues objects give you access to the parameter values normally available through the
request.getParameter and request.getParameterValues methods.
• To to access a header parameter named user-agent:
• ${header.Accept}
Note: The header and headerValues objects give you access to the header values normally available through the
request.getHeader and request.getHeaders methods.
• To output the value of cookie named userCookie
• ${cookie[“userCookie”].value}
• To out the value of initParam named defaultColor
• ${initParam.defaultColor}
• To output the name element stored in request scope
• ${requestScope.Name}
• Functions in JSP EL :
• JSP EL allows you to use functions in expressions as well. These functions must be defined in custom tag libraries. A function
usage has the following syntax:
• ${ns:func(param1, param2, ...)}
• Where ns is the namespace of the function, func is the name of the function and param1 is the first parameter value. For
example, the function fn:length, which is part of the JSTL library can be used as follows to get the the length of a string.
• ${fn:length("Get my length")}
JSP EL Implicit Objects:
• <taglib>
• <taglib-version></taglib-version>
• <short-name></short-name>
• <tag>
• <description>Example Tag</description>
• <name>example</name>
• <tag-class>somepackage.ExampleTag</tag-class>
• <body-content>empty</body-content>
• </tag>
• </taglib>
The JSP File
• This file has the taglib directive which is of the following form:
• <%@ taglib uri=“/WEB-INF/tlds/example.tld” prefix=“test”
A] uri – gives the location of tld file relative to the applications root
directory.
B] prefix – specifies a prefix that is used in front of any tag name defined
in the tld of this taglib declaration.
• The tag created will be of the following form:
• <test:example>
• <test:example></test:example>
Note: the name of the tag is example and is referenced in the tld file
Note: This tag is placed in the JSP file where you want to obtain the
output.
The JSP File
• <!DOCTYPE HTML PUBLIC>
• <HTML>
• <HEAD>
• <TITLE>Example JSP Page</TITLE>
• </HEAD>
• <BODY>
• <%@ taglib uri=“/WEB-INF/tlds/example.tld” prefix=“test”>
• <test:example/>
• <test:example></test:example>
• </BODY>
• </HTML>
Assigning Attributes to Tags
• package somepackage;
• import javax.servlet.jsp.*;
• import javax.servlet.jsp.tagext.*;
• import java.io.*;
• public class ExampleTag extends SimpleTagSupport{
• public void doTag() throws JspException, IOException{
• JspWriter out = getJspContext.getOut();
• out.print(“<b>Before Printing TagBody</b>”);
• getJSPBody.invoke(null);
• out.print(“<b>After Printing TagBody</b>”);
• }
How to get HttpServletRequest instance from PageContext and invokeing tag
body conditionally
• package somepackage;
• import javax.servlet.jsp.*;
• import javax.servlet.jsp.tagext.*;
• import java.io.*;
• public class ExampleTag extends SimpleTagSupport{
• public void doTag() throws JspException, IOException{
• PageContext context = (PageContext)getJspContext();
• HttpServletRequest request = (HttpServletRequest)context.getRequest();
• if(request.getParameter(“debug”) != null){
• getJSPBody.invoke(null);
• }
• }
• }
Creating Tag Files
• JSP based way to create custom tags using tag files.
• We do not create any tld files in this method
• These tag files run only on JSP 2.0
• There are two stepsto creating a JSP-based custom tag:
1] Create a JSP based tag file.
This file has a .tag extension and is placed inside the WEB-INF/tags or a
subdirectory thereof
2] Create a JSP page that uses the tag file.
The JSP page point to the directory where the tag file resides using the tagdir
attribute of the taglib directive. i.e. uri attribute is replaced by tagdir attribute.
The name of the tag file(minus the .tag extension) becomes the name of the
custom tag therefore no tld connecting the implementation of the tag with its
name is needed
Creating .tag file
• Name of the file: simplePrime2.tag
• <%= coreservlets.Primes.nextPrime
(coreservlets.Primes.random(50)) %>
Creating the JSP file using .tag file
• <!DOCTYPE HTML PUBLIC>
• <HTML
• <HEAD>
• <TITLE>Some 50 digit primes</TITLE>
• </HEAD>
• <BODY>
• <H1>Some 50 digit primes</H1>
• <%@ taglib tagdir=“/WEB-INF/tags” prefix=“csajsp” %>
• <UL>
<LI><csajsp:simplePrime2 />
<LI><csajsp:simplePrime2 />
<LI><csajsp:simplePrime2 />
<LI><csajsp:simplePrime2 />
</UL>
</BODY>
</HTML>
Using attributes with JSP based custom tags
• To use attributes with JSP based custom tags each attribute must be declared inside the .tag
file
• This declaration is accomplished by the attribute directive.ie. This directive is used in the tag
file
• You can use the attributes of the attribute tag like
1] name – name of the attribute
2] required – true/false
prime2.tag file
____________________________________________________________________
<%@ attribute name=“length” required=“false” %>
<%
int len = 50;
try{
len = Integer.parseInt(length);
} catch (NumberFormatException nfe){}
%>
<% coreservlets.Primes.nextPrimes(coreservlets.Primes.random(len)) %>
prime2.jsp
• <HTML>
• <HEAD>
• <TITLE>Some N digit Primes</TITLE>
• <HEAD>
• <BODY>
• <H1>Some N-Digit Primes</H1>
• <%@ taglib tagdir=“/WEB-INF/tags” prefix=“csajsp” %>
• <UL>
<LI><csajsp:prime2 length = “20” />
<LI><csajsp:prime2 length = “40” />
<LI><csajsp:prime2 length = “80” />
<LI>Default (50-digit) <csajsp:prime2 />
</UL>
</BODY>
</HTML>
Outputting the tag body in .tag file using
<jsp:doBody />
Heading2.tag
<%@ attribute name=“align” required=“true” %>
<%@ attribute name=“bgColor” required=“true” %>
<%@ attribute name=“border” required=“true” %>
<%@ attribute name=“fgColor” required=“false” %>
<%@ attribute name=“font” required=“false” %>
<%@ attribute name=“size” required=“false” %>
<TABLE ALIGN=“${align}” BGCOLOR= =“${bgColor}” > <TR><TH>
<SPAN STYLE=“color: “$(fgcolor)” font-family: “$(fgcolor)” font-size=“${size}”>
<jsp:doBody />
</SPAN>
</TABLE><BR CLEAR=“ALL”><BR>
heading2.jsp
• <HTML>
• <HEAD>
• <TITLE>Headings</TITLE>
• <HEAD>
• <BODY>
• <H1>Some N-Digit Primes</H1>
• <%@ taglib tagdir=“/WEB-INF/tags” prefix=“csajsp” %>
• <csajsp:heading2 align=“left” bgcolor=“cyan” border=“10” fgcolor=“black” font=“arial black” size=“78” />
First Heading
<csajsp:heading2 align=“right” bgcolor=“RED” border=“1” fgcolor=“yellow” font=“Times New Roman”
size=“50” />
Second Heading
• <csajsp:heading2 align=“center” bgcolor=“#c0c0c0” border=“20” fgcolor=“blue” font=“arial narrow”
size=“100” />
Third Heading
</csajsp : heading2>
</BODY>
</HTML>
Advanced Features – buffering the output of the tag body
• The below code snippet shows how to buffer the output of the tag body in StringWriter object.
Later this output is modified using ServletUtilities.filter() method which is then sent to client.
• StringWriter myWriter = new StringWriter();
• getJspBody().invoke(myWriter);
HtmlFilterTag.java
package coreservlets.tags;
import javax.servlets.jsp.*;
import javax.servlet.jsp.tagest.*;
import java.io.*;
import coreservlets.ServletUtilities;
public class HtmlFilterTag extends SimpleTagSupport{
public void doTag() throws JspException, IOException{
StringWriter myWriter = new StringWriter();
getJspBody().invoke(myWriter);
String output = ServletUtilities.filter(stringWriter.toString());
JspWriter out = getJspContext().getOut();
out.print(output);
}
}
Advanced Features – Assigning Dynamic Values to Tag Attributes
• While using this tag we use an attribute whose value can be accessed in the tag body using JSP EL
• <mytags:for beanKeyValue=“arrayValue” iterateOver=“${someArray}”>
• Value is ${arrayValue}
• </mytags:for>
• Note: the above array is generally set in request or session attribute in a servlet and is thus available to the forwarding
JSP using EL ${array_name_used _to_set_the_attribute} e.g.
• request.SetAttribute(“servers”,servers);
• <csajsp:forEach items=“${servers}” var=“server”>
<LI>${server}
• </csajsp:forEach>
Advanced Features– Creating Expression Language Functions
• Through this feature we are able to call a java method inside the body of the tag using EL
without using scripting.
• The java method (say someMethod())is defined in a utility class say SomeClass.java
• public class SomeClass{
public static String someMethod(HttpServletRequest request){…}
}
• Inside the tld file the fully qualifies class name anf the method gets mapped to some name that
will be used inside the JSP page to invoke the method
• <function>
<name>run</name
<function-class>somepackage.SomeClass</function-class>
<function-signature>java.lang.String someMethod(javax.servlet.HttpServletRequest)</function-
signature>
</function>
• Declare the tag library inside the JSP page as below
<%@ taglib prefix=“myfunc” uri=“taglib_location” %>
• Invoke the method using the tag. The method alias is placed immediately after the tag prefix:
• ${csajsp:run(pageContext.request)}
Advanced Features – Handling Nested Custom Tags
• The tag body of a custom tag can also contain other custom tags
• If the inner tag and other tag don’t depend on each other the inner tag can appear without the presence of outer tag.
• The simple tag api provides two methods that let an inner tag get hold of the outer tag
1. getParent()
2. findAncestorWithClass()
A] getParent
• The getParent() method is called on the instance of inner tag.
• It returns an object of type JSPTag which can be cast to the type of outer tag’s handler class
• If this method is called on the outmost tag in hierarchy it returns null.
B] findAncestorWithClass(JspTag fromTag, Class toBeMatchedClass)
• this method starts searching the hierarchy of tags from a given tag instance, fromTag, looking at its parent tag up until it finds a tag
instance that matches the type of toBeMatchedClass.
• If the search takes all the way to the top of the hierarchy with no results it returns null.
• If this method find the right instance of the tag class it returns it as a JspTag instance
• With this method you know the parent type in advance so if tis method returns anything but null you are guaranteed that you can
successfully cast down te instane it returns using the class type that was provided in the second argument. With getParent() you need to
anticipate a ClassCastException
• How to get at the inner tag from the outer tag – you can store some information in the outer tag that te inner tag can later review and act
on.
public class OuterTag extends SimpleTagSupport{
public void setSomeValue(SomeClass arg){….}
}
public class InnerTag extends SimpleTagSupport{
public int doTag() throws JSPException, IOException{
Outer Tag parent = (OuterTag)findAncestorWithClass(this,Outer.class);
if(parent == null) {
throw new JspTagException(“nestingError”);
}
SomeClass value= parent.getSomeValue();
DoSomethingWithValue(value);
}}
JSP Standard Tag Library (JSTL)
• JSTL provides many useful tag libraries and has been universally accepted by the Java community
• The most common JSTL library is the core library. It contains the following tags:
1. out
2. if
3. forEach
4. forTokens
5. choose
6. when
7. otherwise
8. set
9. remove
10.import
11.url
12.param
13.redirect
14.catch
Installation of JSTL
• Copy standard.jar and jstl.jar into the WEB-INF/lib directory of your
application.
• Jstl.jar contains only the interfaces that the jstl specification requires
• Standard.jar contains the actual implementations along with the tld
files.
• Import the library into your JSP page with the taglib directive as
below:
<%@ taglib prefix=“c” uri=http://java.sun.com/jsp/jstl/core %>
Note: it’s a known convention that the JSTL core library is assigned
“c” as the prefix and you should stick to it.
• It is also very useful to download the JSTL tag library documentation.
c:out tag
• <c:out value=“…” default=“…” escapeXml=“…”/>
• This tag is very similar to JSP scripting expression <%= expression %>
and ${expression} where the value of expression is output.
• The value attribute is evaluated and the resulting expression is
output.
• However the c:out tag lets the JSP developer specify a default value
to output if the resulting expression inside the value tag evaluates to
null.
• The attribute escapeXml=“true” allows the tag to automaticallty
escapse any xml characters like <,>,”,’
• <c:out value=“<c:out> tag” />
• <c:out value=“${account}” default=“none” />
c:forEach
• c:forEach provides basic iteration accepting many different collection types e.g.
<c:forEach items=“${list}” var=“item” >
<LI>${item}</LI>
</c:forEach>
where list is of the type java.util.List
Note: the var attribute allows the developer to specify a key with which to refer to
the current element through iteration.
• c:forEach can also function as a counter-based for loop specifying a begin, end, and
a step index
<c:forEach var=“i” begin=“1” end=“10” step=“2” >
<LI>i = ${i}</LI>
</c:forEach>
c:forTokens
• this tag is designed to iterate over a String of
tokens separated by delimiters
• the delimiter is specified through its required
delims attribute
<c:forTokens var=“item” items=“<Once)Upon,
a(Time%There…>” delims=“<),(%>” >
<LI>${item}</LI>
</c:forTokens>
c:if
• This tag evaluates the body if the condition supplied to
the test attribute is true e.g.
<c:forEach var=“i” begin=“1” end=“10” step=“2” >
<LI>
i = ${i}
<c:if test=${i < 3} >
(greater than 3)
</c:if>
</LI>
</c:forEach>
c:choose
• c:choose tag is a conditional tag that establishes a context for mutually exclusive operations marked by c:when
and c:otherwise tags
• These tags work in the same way as java switch-case-default statements
• The c:choose tag itself does not have any attributes, its sole purpose is to provide the context to other two tags.
• c:when tag has a test attribute that allows the JSP developer to specify a condition, which if evaluated to true
would signal the container to evaluate the body of c:when tag
• If a particular c:when tag evaluates to true no other c:when tag below it are evaluated and the processing jumps
to line after the closing c:choose tag
• If the optional c:otherwise tag is specified and no c:when tag evaluates to true, the body of the c:otherwise tag is
evaluated.
• <c:forEach var=“i” begin=“1” end=“10” >
• <LI>
• i=${i}
• <c:choose>
<c:when test=“${i < 3}” >(less than 3)</c:when>
<c:when test=“${i < 5}” >(less than 5)</c:when>
<c:when test=“${i == 5}” >(it is 5! so exciting)</c:when>
<c:otherwise>(greater than 5)</c:otherwise>
• <c:choose>
• </LI>
• </c:forEach>
c:set
• c:set attribute is used either for setting a scoped attribute or updating and creating bean
properties and map values.
• <c:set var=“attributeName” value=“someValue” />
• <c:set target=“map” property=“elementKey” value=“elementValue” />
• <c:set target=“bean” property=“name”>John Dow</c:set>
Note: the last c:set tag does not specify the value attibute. Its value comes from the body of
c:set tag
• the c:set tag provides two attributes var and target of which at least one is required. However
these attributes are not allowed to appear at the same time.
• the var attribute is used to specify the name of the attribute to set. This attribute is set in the
scope specified by the optional scope attribute.
• If the scope attribute is not specified it defaults to page scope.
• the target attribute must be an expression that evaluates to some object. If the object
implements the map interface, the property attribute of the c:set tag is treated as a key with
which to create a new map entry with the value specified.
• if the target evaluated to JavaBean the value of the c:set tag is passed to the property of the
target JavaBean specified by the property attribute.
• When the value of c:set tag evaluates to null, the effect is no different than invoking
someScopeReference.setAttribute(null) where someScopeReference is not of
request,session,application which essentially removes the attribute from that scope.
c:remove
• the c:remove attribute specifies the name of the attribute to
remove using the required var attribute and the scope to
remove it from using the optional scope attribute.
• If the scope is not specified, the c:remove attribute will
remove the attribute from all scopes
• <c:set var=“authors” value=“Marty Hall, Larry Brown, Yaakov
Chaikin” scope=“request” />
• <c:set var=“authors” />Authors</c:set>
• <H2 align=“center”> ${pageScope.authors}:$
{requestScope.authors}</H2>
• <c:remove var=“authors” />
• <H2 align=“center”> ${pageScope.authors}:$
{requestScope.authors}</H2>
c:import tag
• <c:import tag can include the content pointed to by the required attribute “url” even if the
content resides on a different webserver.
• The imported content has to be a snippet of HTML that fits into the structure of the existing
HTML page. The links inside the imported content have to be absolute.
• The behaviour of c:import tag is to output the included content into the included page at
the pace where c:import tag appears
• However if the optional var and the likewise optional scope attributes are specified, the
included content can be saved as a scoped attribute instead.
• If the var attribute is specified the c:import tag does not output the included content but
caches it into a scoped var attribute. If the c:import tag does not specify a the included
content is output into the place where the c:import tag appears
• If the scope attribute is omitted it defaults to page scope.
• If the imported attribute contains relative links it will not work.
• <c:import url=http://www.google.co.in var=“outputBufferVar” />
• <td>${outputBufferVar}
• <c:import url=http://www.google.co.in />
c:url and c:param
• If the cookies are disables the container will not append the sessionID to the url that are
sent back to the client inside your JSP pages.
• Every url within your page needs to be encoded if its to retain the sessionid info
• The c:url encodes the url specified in its required value attribute appending the
sessionID if the client is not using cookies and leaves the url as it was if the client
browser is able to accept a session cookie.
• Just like the c:import tag the c:url tag is able to hold off on outputting the URL string if
the optional var attribute is present. In such a case the resulting URL gets stored in in a
optional “scope” attribute
• If omitted it defaults to page scope.
• <c:url value=“myurl?fullName=${fullNameParam} “ />
• We use the c:url tag in conjunction with c:param tag to encode a value with a space in it
• <c:url value=“/out.jsp“ var=“inputUrl” >
• <c:param name=“name” value=“John Dow” />
• </c:url>
c:redirect