0% found this document useful (0 votes)
134 views

JSP and JSTL

JSP (Javascript Server Pages) is a technology that separates the presentation logic from the business logic in a web application by using a tag-based scripting language instead of embedding Java code into an HTML page. Some key points: - JSP runs on the server, processes tags and generates HTML/output to send to the client. Tags allow for dynamic generation of content. - JSP works best when the HTML structure is fixed but values need to be computed dynamically. It is less suitable for applications with variable structures or that output binary data. - JSP pages are translated into Java servlets, with the _jspService() method handling requests instead of doGet()/doPost(). This

Uploaded by

Prashant Singh
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
134 views

JSP and JSTL

JSP (Javascript Server Pages) is a technology that separates the presentation logic from the business logic in a web application by using a tag-based scripting language instead of embedding Java code into an HTML page. Some key points: - JSP runs on the server, processes tags and generates HTML/output to send to the client. Tags allow for dynamic generation of content. - JSP works best when the HTML structure is fixed but values need to be computed dynamically. It is less suitable for applications with variable structures or that output binary data. - JSP pages are translated into Java servlets, with the _jspService() method handling requests instead of doGet()/doPost(). This

Uploaded by

Prashant Singh
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 105

JSP

• Javascript is used to dynamically generate html on the client.


• Jsp runs on the server
• JSP tags are processed on the server and are not a part of the output that is sent to the
client
• Jsp is less good for applications that have a variable structure.
• Jsp is poor for applications that have mostly dynamic data
• JSP is totally unsuitable for applications that output binary data or manipulate http
without generating explicit output. Servlets are clearly superior.
• JSP tags can be placed in the same directory as normal html, pages, images and
stylesheets
• JSP works best when structure of the html page is fixed but the values at various placed
need to be computed dynamically.
• JSP pages can also be accessed through urls of the same form as html pages.
• You are not allowed to use WEB-INF or META-INF as directory names.
• Any java classes called from JSP pages still need to go in the standard locations used by
servlet classes.e.g.
• ../WEB-INF/classes/directoryMatchingPackageName
• You should always use packages for all classes used by either servlets or JSP pages.
JSP LifeCycle
• The JSP page translated into a servlet
• The servlet is complied
• The Servlet is loaded into the server’s memory
• The jspInit() method is called which is used for
initialization
• The _jspService() is called
Note:_jspService() method replaces doGet() method
in servlets that result from jsp pages.
• The jspdestroy() method is called
Basic JSP syntax

• HTML comment – used for commenting html content


• <!-- Blah -->
• JSP Comment – used for commenting JSP content
• <%-- Blah --%>
• JSP Expression
• <%= Java Value %>
• JSP Scriplet
• <% Java Statement; %>
• JSP Declaration
• <%! Field Definition %>
• <%! Method Definition %>
• JSP Directive
• <%@ directive attribute=“value” %>
• where directive = page/include/taglib
Basic JSP syntax
• JSP Action
• <jsp:include file=“..”/>
• <jsp:useBean id=“” class=“” />
• <jsp:invoke />
• JSPExpression Language Element
• ${EL Expression}
• Custom Tag
• Invocation of custom tag
• <%@ taglib uri=“” prefix=“” %>
• Tag example
• <prefix:name>Tag Body</prefix:name>
• Escaped Template
• <\%
• %\>
• Slash is removed and the remaing text is sent to the client.
JSP Comment versus HTML comment

• JSP comment is used for commenting JSP


portion of the code
• <% -- JSP COMMENT --%>
• HTML comment is used for commenting HTML
portion of the code
• <!– HTML COMMENT 
Types of scripting elements

1. Expressions: these are of the form


<%= Java Expression %>
These are evaluated and inserted into the servlet’s output.
JSP expressions contain java value which do not end in a semi colon
2. Scriplets: these are of the form
<% Java Code %>
These are inserted into the servlets _jspService method.
These contain java statements which are terminated by semi colon
3. Declarations: these are of the form
<%! Field/Method Declaration %>
These are inserted into the body of the servlet class outside any existing
methods.
JSP Servlet Correspondence
• Sample HTML and JSP expression
• <HTML>
• <HEAD><TITLE>JSP into Servlet Conversion</TITLE></HEAD>
• <BODY>
• <H1>A Random Number</H1>
• <%= Math.random() %>
• <% baz(); %>
• </BODY>
• <HTML>
____________________________________________________________________________________
• Output in a servlet after being converted from JSP
• public void _jspService(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
• response.setContentType(“text/html”);
• HttpSession session = request.getSession();
• JspWriter out = response.getWriter();
• out.println(“<H1>A Random Number</H1>”);
• out.println(<%= Math.random() %>);
• baz();
• }
____________________________________________________________________________________
• Regular html becomes print statements with double quotes around the text
• JSP expressions become print statements with no double quotes.
• JSP scriplets don’t get placed inside println statements.
How to get the value from one JSP page to another
• <HTML>
• <HEAD><TITLE>JSP into Servlet Conversion</TITLE></HEAD>
• <BODY>
• <UL>
<LI><B>param1</B>: <%= request.getParameter(“param1”) %>
<LI><B>param2</B>: <%= request.getParameter(“param2”) %>
<LI><B>param3</B>: <%= request.getParameter(“param3”) %>
• </UL>
• </BODY>
• <HTML>
Using scriplets to make parts of JSP page conditional
• <HTML>
• <HEAD>Conditional JSP using scriplets</TITLE></HEAD>
• <LINK rel=“stylesheet” href=“JSP-Styles.css” type=“text/css”>
• <BODY>
• <UL>
<% if(Math.random() < 0.5){ %>
<H1>Have a nice day</H1>
<% }else{%>
<H1>Have a lousy day</H1>
<%} %>
</UL>
• </BODY>
• <HTML>
Using Declarations
• A JSP declaration lets you define methods or fields that get inserted
into the main body of the servlet class outside the _jspService()
method that is called by service to process the request.
• In practice declarations almost always contain field or method
definitions.
• Do not use declarations to override the standard life cycle methods
such as service(), doGet(), init() etc
• Use JSP declarations to override jspInit() or jspDestroy() not init() or
destroy() for initialization and cleanup in JSP pages.
• Using declarations to define instance variable fields gives you a
place to store data that is persistent between requests.
• It does not matter whether the code from the declaration goes at
the top or bottom of the servlet.
• Declarations end with a semi-colon.
Declaration example
• <HTML>
• <HEAD>Conditional JSP using scriplets</TITLE></HEAD>
• <LINK rel=“stylesheet” href=“JSP-Styles.css”
type=“text/css”>
• <BODY>
• <H1>JSP Declaration</H1>
• <%! private int accesscount = 0; %>
• <H2>Accesses to page since server reboot:
• <%= ++accessCount %></H2>
• </BODY>
• <HTML>
Predefined variables or implicit objects
• You are supplied with eight automatically defined local
variables in _jspService() method
• These variables are not accessible in declarations.
• These variables are present by default in _jspService()
method
• If you need a separate method to have access to one of
these variables, pass the variable along as a prarmeter.
NOTE: _jspService() replaces doGet() method in servlets that
result from JSP pages.

1. out – the writer used to send response to the client.


2. application – the ServletContext, this data structure is
shared by all servlets and JSP pages.
Implicit object - request
• request – variable of the type
HttpServletRequest. It gives you access to
request parameters, the request type, and the
incoming HTTP headers (e.g. cookies).
Implicit object - response

• response – variable is the


HttpServletResponse associated with the
response to the client.
• used for setting httpstatus code and response
header.
Implicit object - out

• This variable is the writer used to send output to the


client
• JspWriter out = getJspContext().getOut();
• The out is not a standard PrintWriter but a standard
verson of writer called JspWriter.
• The out variable is used almost exclusively in scriplets
since JSP expressions are automatically placed in
output stream i.e. out.println(jspExpression), and
thus rarely need to refer to out explicitly
Implicit object session

• session – the HttpSession associated with the


request.
• sessions are created automatically in JSP so this
variable is bound even if there is no incoming
session reference.
• The one exception is the use of session attribute of
page directive to disable automatic session
tracking.
• In that case attempts to reference the session
varible causes errors at the time JSP is converted
into servlet.
Implicit object - application
• This variable is the ServletContext as obtained by getServletContext().
• In the servlet code 
• ServletContext application = getSerlvetContext();
application.setAttribute(“userName”, userName);
application.getAttribute(“userName”);
• data stored in servlet context is shared by all servlets and JSP pages in the application.
• data stored in instance variable declared through declaration is available only to the same servlet that stored
the data.
• ServletContext is also used for initializing initParameters
• Stirng paramName = getSerlvetContext().getInitParameter("paramName");
• note:
• * Context init parameter is for whole web app!!
• * Context init only need to be defined in one DeploymentDescriptor and can be used anywhere in web app!!
• * In a distributed environment, one Servletcontext per JVM

• <context-param>

  <param-name> paramName </param-name>

  <param-value> paramValue </param-value>

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

  <param-name> paramName </param-name>

  <param-value> paramValue </param-value>

</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);
%>

<%-- Show the values --%>


<%= pageContext.getAttribute("attr1") %>
<%= pageContext.getAttribute("attr2", PageContext.PAGE_SCOPE) %>
<%= pageContext.getAttribute("attr3", PageContext.REQUEST_SCOPE) %>
<%= pageContext.getAttribute("attr4", PageContext.SESSION_SCOPE) %>
<%= pageContext.getAttribute("attr5", PageContext.APPLICATION_SCOPE) %>
implicit object - pageContext

• 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 ();

• void forward (String relativeURL)


• Forwards the request to another resource.
• Same as ServletRequest.getRequestDispatcher ().forward ();

• For example, to forward a request to another resource from a servlet, we have to write the
following to lines:

• RequestDispatcher rd = request.getRequestDispatcher ("other.jsp");


• rd.forward (request, response);

• In a JSP page, we can do that in just one line by using the pageContext variable:
• pageContext.forward ("other.jsp");
implicit object - pageContext

• The pageContext object has a type of javax.servlet.jsp.PageContext and according


to the API documents:
• "A PageContext instance provides access to all the namespaces associated with a
JSP page, provides access to several page attributes, as well as a layer above the
implementation details. Implicit objects are added to the pageContext
automatically" A PageContext instance is obtained by a JSP implementation class
by calling the JspFactory.getPageContext() method, and is released by calling
JspFactory.releasePageContext().
• a single API to manage the various scoped namespaces
• a number of convenience API?s to access various public objects
• a mechanism to obtain the JspWriter for output
• a mechanism to manage session usage by the page
• a mechanism to expose page directive attributes to the scripting environment
• mechanisms to forward or include the current request to other active
components in the application
• a mechanism to handle errorpage exception processing
How to get initialization parameters from
jspInit() method
• you can call
getServletConfig().getInitParameter(“name-of-
init-param-in-jsp") in jspInit method
• Georgy Gobozov Jun 14 '13 at 13:41
Difference between ServletConfig and ServletContext

• ServletConfig
• <init-param>

  <param-name> paramName </param-name>

  <param-value> paramValue </param-value>

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

  <param-name> paramName </param-name>

  <param-value> paramValue </param-value>

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

• Note : page cannot be used to directly call the servlet methods


• ·        page.getServletInfo()
•  Error because page is java.lang.Object type
• ·        ((servlet)page).getServletInfo()
• ·        this.getServletInfo()
• The page Object:
• This object is an actual reference to the instance of the page. It can be thought of as an object that
represents the entire JSP page.
• The page object is really a direct synonym for the this object.
JSP Directive
• In JSP there are three main types of directive: page,
include, taglib
• The page directive lets you control the structure of
the servlet by importing classes, customizing the
servlet superclass, setting the content type etc
• The include directive lets you insert a file into the JSP
page at the time the JSP is translated into servlet. The
include directive is placed at the point you want the
file to be inserted.
• The taglib directive declares the custom tag and gives
the location of tld files and tag prefix.
import attribute of page directive
• <%@ page import=“package.class1,package.class2,…
package.classN” %>
• <%@ page import=“java.util.*” %>
• The import attribute of the package directive lets you
specify the packages that should be imported by the
servlet into which the JSP page gets translated.
• Always put your utility classes in packages while using
your utility classes in JSP.
• Import attribute is the only attribute that is allowed to
appear multiple times within the same document.
contentType and pageEncoding attributes of the page
directive
• <%@ page contentType=“application/vnd.ms-excel” %>
• the contentType attribute sets the
ContentType response header indicating the MIME type of the document being sent to the
client.
Note: If you want to conditionally set the contentype use the normal servlet approach of
response.setContentType() e.g.
<%
String format = request.getParameter(“format”);
if((format != null) && (format.equals(“excel”))){
response.setContentType(“application/vnd.ms-excel”);
}
%>
• The directives are parsed specially; they don’t directly become _jspService() code at the
location at which they appear.
• If you just want to change the charset it is simpler to use the pageEncoding attribute
<%@ page pageEncoding=“Shift_JIS” %>
session attribute of page directive
• <%@ page session=“false” %>
• <%@ page session=“false” %><%-- Default --%>
• A value of true signifies that the predefined variable
session should be bound to existing session, otherwise a
new session should be created and bound to session.
• Using session=“false” does not automatically disable
session tracking. It merely prevents JSP page from
creating a new session for users who don’t have them
already. Hence attempts to access the variable session will
result in errors at the time JSP is converted into servlet.
isELIgnored attribute of the page directive

• <%@ page isELIgnored=“false” %>


• <%@ page isELIgnored=“false” %>
• This attribute controls whether JSP 2.0
Expression Language (EL) is ignored (true) or
evaluated normally(false)
• If web.xml specifies servlets 2.4 default is false
• If web.xml specified servlets 2.3 default is true
buffer , autoflush, info, attribute of the page directive
• <%@ page buffer=“30kb” %>
• <%@ page buffer=“none” %>
• Buffer specifies the document content.
• The above directive means that the document content should be bufferd and not sent to the
client until at least 32 kilobytes are accummulated.
• Turning off the buffer requires the JSP elements that set the header or status codes to appear
at the top of the file before any html content
• <%@ page autoFlush=“true” %><%-- Defualt --%>
• <%@ page autoFlush=“false” %>
• the autoflush attribute controls whether the output buffer should be automatically flushed
when it is full or whether an exception should be raised when buffer overflows
(autoflush=“false”)
• autoflush=“false” is illegal when buffer=“none” is used.
• <%@ page info=“some message” %>
• The info attribute defines a String that can be retrieved from the servlet by means of
getServletInfo() method
errorPage, isErrorPage attribute of the page directive
• <%@ page errorPage=“Relative URL” %>
• The errorPage attribute specifies a JSP page that should
process any exception (i.e. something of the type throwable)
thrown but not caught in the current page.
• There is no try catch in the current page
• The exception thrown will be automatically available in the
designated error page by means of the exception variable.
• <%@ page isErrorPage=“true” %>
• <%@ page isErrorPage=“false” %><%--Default--%>
• the isErrorPage attribute indicates whether or not the current
page can act as the error page for another JSP
• the file specified by the errorPage attribute is placed in the
WEB-INF directory.
extends, language attribute of the page directive

• <%@ page extends=“package.class” %>


• the extends attribute designates the super
class of the servlet that will be generated for
the JSP page.
• <%@ page language=“java” %>
• the language attribute is intended to specify
the scripting language being used.
jsp:include
• <jsp:include page=“/WEB-INF/item1.html” flush=“true”/>
• difference between @ include and jsp:include
• the include directive inserts the source of resue.html at translation time before the main page is translated into
serlvet but action tag jsp:include inserts the response of reuse.html at runtime.
• jsp:include lets you insert any of the following into the JSP output
1. the content of an html page
2. the content of a plain text document
3. the output of a JSP page
4. the output of a serlvet.
Note: the jsp is converted into a servlet and then the output is inserted to the main page which is also converted
into a servlet, hence two servlets result.
Note: that the url mentioned in the path attribute are interpreted relative to the base web application directory.
Note: you can place the included pages in the WEB-INF or a subdirectory thereof
Note: jsp:include also has an optional flush attribute. This specifies whether the output stream of the main page
should be flushed before the inclusion of the page.
• the main advantage of jsp:include is that it saves you from changing the main page when the included page
changes.
• the min disadvantage is that the included JSP page cannot use any JSP constructs that affect the main page as a
whole.
• Do not use HTML documents for your included pages. Use only the html tags appropriate to the place where
included files will be inserted.
include directive :

• <%@ include file=“relative url” %>


• This construct lets you insert JSP code into the main page before
that main page is translated into serlvet.
• The included file is inserted int other main page then the page is
translated into servlet. Here only one servlet result.
• This included the actual content of the file
• It is powerful and the included code can contain JSP constructs
such as field definitions and content type setting that affect the
main page as a whole.
• It is hard to maintain and if you change an included file you have
to update the modification dates of all JSP files that use it.
• You should use the include directive in cases in which the included
file defines fields or methods that the main page uses or when the
included file sets response headers of the main page.
using jsp:param element with jsp:include

• <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”

• session based data sharing:


Serlet
SessionBean value = new Sessionbean;
value.setName(“my_name”);
HttpSession session = request.getSession();
session.setAttribute(“key”,value);
RequestDispatcher dispatcher = request.getRequestDispatcher(“/WEB-INF/SomePage.jsp”
dispatcher.forward(request,response);
JSP page
<jsp:useBean id=“key” type=“somepackage.SessionBean” scope=“session” />
<jsp:getProperty name=“key” property=“someProperty”

• Application based data sharing


Servlet
synchronized(this){
ApplicationBean value = new Applicationbean;
value.setName(“my_name”);
getServletContext.setAttribute(“key”,value);
RequestDispatcher dispatcher = request.getRequestDispatcher(“/WEB-INF/SomePage.jsp”
dispatcher.forward(request,response);
JSP page
<jsp:useBean id=“key” type=“somepackage.ApplicationBean” scope=“application” />
<jsp:getProperty name=“key” property=“someProperty”
Forwarding requests to jsp pages using forward() method of
RequestDispatcher
• using forward() method of the RequestDispatcher
String address (“/WEB-INF/Order.jsp”);
RequestDispatcher dispatcher =
request.getRequestDispatcher(address);
dispatcher.forward(request,response);
• When you use the forward method of the RequestDispatcher, the
client sees the url of the original servlet, not the new url of the
final JSP page
• Pages can be placed in WEB-INF to prevent the user from accessing
them without going through the servlet that sets up the data
• Control is transferred entirely on the server
• Post requests cannot be forwarded to static html pages
Redirecting instead of forwarding using sendRedirect()
method of HttpServletResponse

• Control is transferred by sending the client a 302 status code


and a location response header which contains the url of the
new document.
• the 302 code directs the browser to connect to a new location
• the browser immediately connects to the new url and no
intermediate output is displayed.
• The user sees the address of the destination page and can
bookmark it and access it independently.
• This approach would be useful when redisplaying an
incomplete an independent html form or summarizing the
contents of shopping cart.
Ensuring that the jsp never creates new objects

• To guarantee that the JSP page will not create


new objects you should use:
• <jsp:useBean … type=“package.class” />
• instead of
• <jsp:useBean … type=“package.class” />
• The scope you specify in jsp:useBean should
match the storage location used by servlet.
Storing the input in request scope
• A second page shares 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
Forwarding requests from JSP page

• 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 &#36 so &#36;{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:

• Implicit object Description


• pageScope Scoped variables from page scope
• requestScopeScoped variables from request scope
• sessionScope Scoped variables from session scope
• applicationScopeScoped variables from application scope
• param Request parameters as strings
• paramValues Request parameters as collections of strings
• headerHTTP request headers as strings
• headerValuesHTTP request headers as collections of strings
• initParam Context-initialization parameters
• cookieCookie values
• pageContextThe JSP PageContext object for the current page
Note: You can use these objects in an expression as if they were variables. Here are few
examples which would clear the concept:
${pageContext.request.queryString}
${param["username"]}
${header["user-agent"]}
${pageContext.servletContext.serverInfo}
Evaluating Expressions Conditionally

• ${ test ? expression1 : expression2 }


• if test expression evaluates to true, the above
expression returns the value of expression1,
otherwise it returns the value of expression2
• Remember that the main purpose of the
expression language is to simplify the
presentation logic. Avoid using this technique
for business logic.
Accessing databases with JDBC – using jdbc in general

• specify the classname of the database driver in the Class.forName method.


• Define the connection URL
• Establish the connection
• Create a statement object
• Execute a query or update
• process the results
• close the connection
• Class.forName(“oracle.jdbc.driver.OracleDriver”);
• String oracleURL = “jdbc:oracle:thin:@”+host+”:”+port+”:”dbName;
• Connection conn = DriverManager.getConnection(oracleURL, userName,pasword);
• Statement stmt = conn.createStatement();
• String query=“select * from employees”
• ResultSet rs = stmt.executeQuery(query);
• while(rs.next()){
• }
• conn.close();
Accessing JDBC with prepared statements
• Class.forName(“oracle.jdbc.driver.OracleDriver”);
• String oracleURL = “jdbc:oracle:thin:@”+host+”:”+port+”:”dbName;
• Connection conn = DriverManager.getConnection(oracleURL,
userName,pasword);
• String query=“select * from employees where empid=? and
emp_name=?”;
• PreparedStatement pstmt = conn.prepareStatement(query);
• pstmt.setString(1,x);
• pstmt.setFloat(1,y);
• ResultSet rs = stmt.executeQuery();
• while(rs.next()){
• }
• conn.close();
TAG LIBRARIES
• The Basics
• Creating and using custom tags utilizes SimpleTag api which was
introduced in version 2.4 of servlet specification.
Tag Library Components
• The tld (xml files) files map the xml element names to tag
specification and are placed in WEB-INF/tld
• The tag handler class extends SimpleTagSupport and is placed in
WEB-INF/classes
• The JSP file that uses the tag library
NOTE: The taglib directive is placed in jsp file. It has two attributes.
A] uri attribute giving the location of tld file and
B] prefix attribute which is prefixed to every tag.
The Tag Handler Class
• This class extends SimpleTagSupport which is available in javax.servlet.jsp.tagext
package
• This is a java class that tells the system what to do when it sees the tag.
• This class has a doTag() method. The code that does the actual work of the tag
goes inside this method
• Every tag handler class must have a no-arg constructor or its instantiation will
fail.
• A new instance of the tag handler class is created for every tag occurrence on
the page. This alleviates worries about race conditions and cached values
instance variables in the tag handler class.
• To obtain an instance of JspWriter class you call:
JspWriter out = getJspContext().getOut();
• You place the tag handler class in the same location you place a regular servlet
inside the WEB-INF/classes
The Tag Handler Class
• 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>Hello World</b>”);
• }
The Tag Library Descriptor File

• The tag library descriptor file is in xml format


• This file identifies the tag handler class to the server and associates it with a particular XML tag
name using the <name> element.
• The tld file must be placed inside the WEB-INF directory or a subdirectory thereof.
• The <tag> element through the following subelements in their required order defines the
custom tag.
A] description – document the purpose of custom tag
B] name – this is a required element and defines the name of the tag as it will be referred to by
the JSP page (actually the tag suffix)
C] tag-class – This a required element and it defines the fully qualifies class name of the
implementing tag handler class
D] body-content – This ia a required element and it tells the container how to treat the content
between the beginning and ending occurrence of the tag. It can have the following values:
1]empty – no content allowed
2]scriptless, - can have JSP content but no scriptlets
3]tagdependent – can have any type of content as its body
4]JSP - provided for backward compatibility with the classic custom tag model.
The Tag Library Descriptor File (example.tld)

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

• The tag will assume the following form


• <prefix:name attribute1=“value1” attribute2=“value2” />
• If you use attribute1 in your tag you need to have setAttribute1(String value1) method in your
tag handler class
• You also need to add the <attribute></attribute> elements to the tld file. This element is of
the following form:
<attribute>
<description>N (prime number length></description>
<name>attribute1</name>
<required>false</required>
</attribute>
• The attribute has the following sub elements:
• 1] name – this is the same as that mentioned in the tag
• 2] required – this can have two values true,false
• 3] rtexprvalue – this indicates whether the attribute can be either a jsp expression like <%=
expression %> or a JSP EL like ${bean.value} which is indicated by true or whether it must be
a fixed String which is indicated by false. The default value is false.
• NOTE: these attributes are passed to the tag handler class or the .tag files as parameters
Include tag body in the output
• <prefix:tagname>scriptless JSP content</prefix:tagname>
Note: the portion “scriptless JSP content” is the tag body
• To output the body content of the tag inside the doTag() method you need to use the below code:
getJSPBody.invoke(null);
Note: it is the output resulting from the execution of tag body’s Jsp content that gets passed to the client, not the JSP
code itself. Given below is sample Tag Handler Class

• 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

• The is no change in tag handler class.


• If we have attribute1 in the tag we will have to provide the setter method
public void setAttribute(String value1){
doSomethingWith(Value1)
• Set the <rtexprvalue>true</rtexprvalue> which means that the attribute can be
either a JSP scripting expression or a JSP EL:
<attribute>
<description></description>
<name>attribute1</name>
<rtexprvalues>true</rtexprvalue>
</attribute>
• Use the expression language to get the value of attribute1 in the taglib directive
<prefix:name attribute1=“${bean:value} attribute2=“<%= bean.getValue() %>” />
Advanced Features – Assigning complex objects as values to Tag Attributes
• <prefix:name attribute1=“${bean:value} attribute2=“<%= bean.getValue() %>” />
• If we wanted to pass a collection of Orders or some other complex structure, we still need to provide setter
for the attribute as before. However the type of argument in the setter would now be complex object type
instead of
String
• public void setAttribute1(SomeComplexObject value1){
doSomethingWith(Value1);
}
• Provide the rtexprvalue element with a value of true
<attribute>
<description></description>
<name>attribute1</name>
<rtexprvalues>true</rtexprvalue>
</attribute>
• The taglib directive remains the same
• <%@ taglib uri=“…” prefix=“…” %>
• The usage of the tag is very much the same as the one we had for dynamic values
<prefix:name attribute1=“${bean:value} attribute2=“<%= bean.getValue() %>” />
Note: In the above tag the expression ${bean.value} must evaluate to either an instance of SuperClass or an
instance of any class that inherits from SuperClass. By SuperClass we are referring to the methods parameters
as below:
public void setAttribute(SuperClass value1){
}
Advanced features – creating looping tag
• Corresponding to the for loop we use a custom tag as a looping structure in JSP
• <prefix:custom-tag>
– some text ${someBean.someValue}
</prefix:custom-tag>
• This tag would create some bean with appropriate values and pass to the JSP content inside the body of the tag.
• The attributes of the tag are only visible to the tag body.
• Use the following code inside the doTag() method to place an object as an attribute of the tagbody scope .ie. the object
is available inside the tag body
getJspContext().setAttribute(key,object)
• You then use JSP EL inside the body of custom tag to access this attibute
• <prefix:custom-tag>
some text ${someBean.someValue}
</prefix:custom-tag>

• 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

• This tag is used or redirecting urls in JSP pages


• If its required attribute “url” specifies an absolute url the
c:redirect tag acts just like the sendRedirectURL
methodof the HttpServletResponse class
• However if the url specified in the url attribute is a
relative url a dynamic forward occurs which is equivalent
to the forward method of the RequestDispatcher class.
• The c:redirect tag can take advantage of the automatic
encoding provided by nesting one or more param tags in
its body in which case the name,value pairs are
appended to the end of the url.
c:catch
• c:catch acts likek the try catch construct in java except that in the case of c:catch
there is no try.
• You can surround the part of the page that may throw an exception with the
c:catch tag and if an exception occurs the page will still render up to the point
where the exception occurs and then continue rendering from the c:catch end tag.
• You can throw the thrown exception in a page scoped attribute specified by the
optional var attribute.
• Avoid using the c:catch tag for anything other than debugging or experimentation.
• Exception handling should be a part of the business logic code not JSP code.
• <c:catch var=“myException” >
<% int x=1/0; %>
• </c:catch>
• <H2>After illegal operation</H2>
• Exception Message: ${myException.message}

You might also like