53
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

Which of the options locate the bean equivalent to the following action? (Select three) a request.getAttribute("address"); b request.getParameter("address");

Embed Size (px)

Citation preview

Page 1: Which of the options locate the bean equivalent to the following action? (Select three) a request.getAttribute("address"); b request.getParameter("address");

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

Page 2: Which of the options locate the bean equivalent to the following action? (Select three) a request.getAttribute("address"); b request.getParameter("address");

HttpServletResponse.sendRedirect() works like this:

• HttpServletResponse.sendRedirect() works like this:• if the URL is absolute http://www.google.com , it redirects

to http://www.google.com.• If the URL is not absolute , it redirects relative to the

current URL. If the URL starts with / it redirects relative to the context root, Else it redirects to the current url

• Based on above rules in your case it redirects to http://currenturl/www.google.com.

• Instead modify your code like this • response.sendRedirect("http://www.google.com"); return;

Page 3: Which of the options locate the bean equivalent to the following action? (Select three) a request.getAttribute("address"); b request.getParameter("address");

What is context root

• A name that gets mapped to the document root of a Web application.

Page 4: Which of the options locate the bean equivalent to the following action? (Select three) a request.getAttribute("address"); b request.getParameter("address");

Difference between forward and redirect• forward• Control can be forward to resources available within the server from where the call is made. This

transfer of control is done by the container internally and browser / client is not involved. This is the major difference between forward and sendRedirect. When the forward is done, the original request and response objects are transfered along with additional parameters if needed.

•the difference between the two is that sendRedirect always sends a header back to the client/browser. this header then contains the resource(page/servlet) which u wanted to be redirected. the browser uses this header to make another fresh request. thus sendRedirect has a overhead as to the extra remort trip being incurred. its like any other Http request being generated by ur browser. the advantage is that u can point to any resource(whether on the same domain or some other domain). for eg if sendRedirect was called at www.mydomain.com then it can also be used to redirect a call to a resource on www.theserverside.com.

where as in case of forward() call, the above is not true. resources from the server, where the fwd. call was made, can only be requested for. but the major diff between the two is that forward just routes the request to the new resources which u specify in ur forward call. that means this route is made by the servlet engine at the server level only. no headers r sent to the browser which makes this very eficient. also the request and response objects remain the same both from where the forward call was made and the resource which was called.

Page 5: Which of the options locate the bean equivalent to the following action? (Select three) a request.getAttribute("address"); b request.getParameter("address");

Difference between forward and redirect

• redirect• Control can be redirect to resources to different servers or domains. This

transfer of control task is delegated to the browser by the container. That is, the redirect sends a header back to the browser / client. This header contains the resource url to be redirected by the browser. Then the browser initiates a new request to the given url. Since it is a new request, the old request and response object is lost.

• For example, sendRedirect can transfer control from http://javapapers.com to http://anydomain.com but forward cannot do this.

• ‘session’ is not lost in both forward and redirect.• To feel the difference between forward and sendRedirect visually see the

address bar of your browser,in forward, you will not see the forwarded address (since the browser is not involved)in redirect, you can see the redirected address.

Page 6: Which of the options locate the bean equivalent to the following action? (Select three) a request.getAttribute("address"); b request.getParameter("address");

When can we use forward and when can we use sendRedirect?

Technical scenario: redirect should be used• If you need to transfer control to different domain• To achieve separation of task.For example, database update and data display can be separated by

redirect. Do the PaymentProcess and then redirect to displayPaymentInfo. If the client refreshes the browser only the displayPaymentInfo will be done again and PyamenProcess will not be repeated. But if you use forward in this scenario, both PaymentProcess and displayPaymentInfo will be re-executed sequentially, which may result in incosinstent data.

• For other than the above two scenarios, forward is efficient to use since it is faster than sendRedirect.

Page 7: Which of the options locate the bean equivalent to the following action? (Select three) a request.getAttribute("address"); b request.getParameter("address");

What is the pageContext implicit object?

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

Page 8: Which of the options locate the bean equivalent to the following action? (Select three) a request.getAttribute("address"); b request.getParameter("address");

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• The _jspService() is called

Page 9: Which of the options locate the bean equivalent to the following action? (Select three) a request.getAttribute("address"); b request.getParameter("address");

What is the pageContext implicit object?

• 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 {... }}

Page 10: Which of the options locate the bean equivalent to the following action? (Select three) a request.getAttribute("address"); b request.getParameter("address");

What is the pageContext implicit object?

• 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 datapageContext.setAttribute("attr1", "value0"); // PAGE_SCOPE is the defaultpageContext.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) %>

Page 11: Which of the options locate the bean equivalent to the following action? (Select three) a request.getAttribute("address"); b request.getParameter("address");

What is the pageContext implicit object?

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

Page 12: Which of the options locate the bean equivalent to the following action? (Select three) a request.getAttribute("address"); b request.getParameter("address");

What is the pageContext implicit object?

• 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

Page 13: Which of the options locate the bean equivalent to the following action? (Select three) a request.getAttribute("address"); b request.getParameter("address");

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

Page 14: Which of the options locate the bean equivalent to the following action? (Select three) a request.getAttribute("address"); b request.getParameter("address");

Difference between ServletConfig and ServletContext

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

Page 15: Which of the options locate the bean equivalent to the following action? (Select three) a request.getAttribute("address"); b request.getParameter("address");

Difference between ServletConfig and 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

Page 16: Which of the options locate the bean equivalent to the following action? (Select three) a request.getAttribute("address"); b request.getParameter("address");

Page implicit object

• The JSP implicit page object is an instance of the java.lang.Object class. It represents the current JSP page.

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

• 3. The page object works like “this” key word in java.• 4. 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.

Page 17: Which of the options locate the bean equivalent to the following action? (Select three) a request.getAttribute("address"); b request.getParameter("address");

Request based sharing

• 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

Page 18: Which of the options locate the bean equivalent to the following action? (Select three) a request.getAttribute("address"); b request.getParameter("address");

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 libraryNOTE: 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.

Page 19: Which of the options locate the bean equivalent to the following action? (Select three) a request.getAttribute("address"); b request.getParameter("address");

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

Page 20: Which of the options locate the bean equivalent to the following action? (Select three) a request.getAttribute("address"); b request.getParameter("address");

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>”);• }

Page 21: Which of the options locate the bean equivalent to the following action? (Select three) a request.getAttribute("address"); b request.getParameter("address");

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 tagB] 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 classD] 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 allowed2]scriptless, - can have JSP content but no scriptlets3]tagdependent – can have any type of content as its body4]JSP - provided for backward compatibility with the classic custom tag model.

Page 22: Which of the options locate the bean equivalent to the following action? (Select three) a request.getAttribute("address"); b request.getParameter("address");

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>

Page 23: Which of the options locate the bean equivalent to the following action? (Select three) a request.getAttribute("address"); b request.getParameter("address");

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 fileNote: This tag is placed in the JSP file where you want to obtain the

output.

Page 24: Which of the options locate the bean equivalent to the following action? (Select three) a request.getAttribute("address"); b request.getParameter("address");

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>

Page 25: Which of the options locate the bean equivalent to the following action? (Select three) a request.getAttribute("address"); b request.getParameter("address");

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

Page 26: Which of the options locate the bean equivalent to the following action? (Select three) a request.getAttribute("address"); b request.getParameter("address");

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>”);

• }

Page 27: Which of the options locate the bean equivalent to the following action? (Select three) a request.getAttribute("address"); b request.getParameter("address");

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

Page 28: Which of the options locate the bean equivalent to the following action? (Select three) a request.getAttribute("address"); b request.getParameter("address");

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 thereof2] 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

Page 29: Which of the options locate the bean equivalent to the following action? (Select three) a request.getAttribute("address"); b request.getParameter("address");

Creating .tag file

• Name of the file: simplePrime2.tag• <%= coreservlets.Primes.nextPrime

(coreservlets.Primes.random(50)) %>

Page 30: Which of the options locate the bean equivalent to the following action? (Select three) a request.getAttribute("address"); b request.getParameter("address");

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>

Page 31: Which of the options locate the bean equivalent to the following action? (Select three) a request.getAttribute("address"); b request.getParameter("address");

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 attribute2] required – true/falseprime2.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)) %>

Page 32: Which of the options locate the bean equivalent to the following action? (Select three) a request.getAttribute("address"); b request.getParameter("address");

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>

Page 33: Which of the options locate the bean equivalent to the following action? (Select three) a request.getAttribute("address"); b request.getParameter("address");

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>

Page 34: Which of the options locate the bean equivalent to the following action? (Select three) a request.getAttribute("address"); b request.getParameter("address");

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>

Page 35: Which of the options locate the bean equivalent to the following action? (Select three) a request.getAttribute("address"); b request.getParameter("address");

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.javapackage 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);

}}

Page 36: Which of the options locate the bean equivalent to the following action? (Select three) a request.getAttribute("address"); b request.getParameter("address");

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 methodpublic 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() %>” />

Page 37: Which of the options locate the bean equivalent to the following action? (Select three) a request.getAttribute("address"); b request.getParameter("address");

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){}

Page 38: Which of the options locate the bean equivalent to the following action? (Select three) a request.getAttribute("address"); b request.getParameter("address");

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 bodygetJspContext().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>

Page 39: Which of the options locate the bean equivalent to the following action? (Select three) a request.getAttribute("address"); b request.getParameter("address");

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)}

Page 40: Which of the options locate the bean equivalent to the following action? (Select three) a request.getAttribute("address"); b request.getParameter("address");

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 tag1. 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);

}}

Page 41: Which of the options locate the bean equivalent to the following action? (Select three) a request.getAttribute("address"); b request.getParameter("address");

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. out2. if3. forEach4. forTokens5. choose6. when7. otherwise8. set9. remove10. import11. url12. param13. redirect14. catch

Page 42: Which of the options locate the bean equivalent to the following action? (Select three) a request.getAttribute("address"); b request.getParameter("address");

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.

Page 43: Which of the options locate the bean equivalent to the following action? (Select three) a request.getAttribute("address"); b request.getParameter("address");

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

Page 44: Which of the options locate the bean equivalent to the following action? (Select three) a request.getAttribute("address"); b request.getParameter("address");

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.ListNote: 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>

Page 45: Which of the options locate the bean equivalent to the following action? (Select three) a request.getAttribute("address"); b request.getParameter("address");

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>

Page 46: Which of the options locate the bean equivalent to the following action? (Select three) a request.getAttribute("address"); b request.getParameter("address");

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>

Page 47: Which of the options locate the bean equivalent to the following action? (Select three) a request.getAttribute("address"); b request.getParameter("address");

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>

Page 48: Which of the options locate the bean equivalent to the following action? (Select three) a request.getAttribute("address"); b request.getParameter("address");

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.

Page 49: Which of the options locate the bean equivalent to the following action? (Select three) a request.getAttribute("address"); b request.getParameter("address");

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>

Page 50: Which of the options locate the bean equivalent to the following action? (Select three) a request.getAttribute("address"); b request.getParameter("address");

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

Page 51: Which of the options locate the bean equivalent to the following action? (Select three) a request.getAttribute("address"); b request.getParameter("address");

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>

Page 52: Which of the options locate the bean equivalent to the following action? (Select three) a request.getAttribute("address"); b request.getParameter("address");

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.

Page 53: Which of the options locate the bean equivalent to the following action? (Select three) a request.getAttribute("address"); b request.getParameter("address");

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}