Head first Servlets and Jsp Chapter 9 Short Notes
April 28, 2011 at 6:53 pm Leave a comment
Note: Feel free to copy the post, modify and comment
Customer Tags are powerful
Coverages:
1. Syntax and semantics of taglib directive
2. Custom tag libs for a design goal
3. JSTL - Core tags, conditional tags, iterator tags & url-related tags
1. Converting entity
Using EL
<div class="tipBox">
<b>Tip of the day:</b> <br/> <br/>
${fn:convEntity(pageContent.currentTip)}
</div>
// Convert the HTML special characters into entity format
Better way is to use c:out (JSTL)
<div class="tipBox">
<b>Tip of the day:</b> <br/> <br/>
${c:out value="${pageContent.currentTip}" escapeXml="true"/>
</div>
For no conversion to happen;
<div class="tipBox">
<b>Tip of the day:</b> <br/> <br/>
${c:out value="${pageContent.currentTip}" escapeXml="false"/>
</div>
// By default escapeXml is true
Convertable items are : > - > < - < & - & ' - ' " - "
2. Use instead of EL the JSTL <c:out> to avoid cross-site-scripting
3. <c:out> to handle the null scenarios
In case of EL and Scriplets/expressions, when the value is missing, it renders empty !
But if you want a default value to be presented in this case, <c:out> comes very useful
<c:out value="${userName}" default="guest" />
or <c:out value="${userName}">guest</c:out>
4. Looping withour Scripting
Take an example of rendering a movieList that is set in the servlet request attribute in a JSP using JSTL
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<body>
<table>
<c:forEach var="movie" items="${movieList}">
<tr>
<td> ${movie} </td>
<tr>
</c:forEach>
</table>
</body>
</html>
* NOTE: Here collection movieList can be either a array or Collection or Map or Comma-delimited String
Getting to know the loop counter here in the forEach
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<body>
<table>
<c:forEach var="movie" items="${movieList}" varStatus="movieCount">
<tr><td> Count: ${movieCount.count} </td><tr>
<tr><td> Movie: ${movie} </td><tr>
</c:forEach>
</table>
</body>
</html>
* Even Nesting of forEach loops is possible
5. Using Conditional Statements with JSTL
<c:if test="empty ${userName} or ${username} == "guest"">
Welcome guest user
</c:if>
<c:if test="${userName}!="guest" ">
Welcome ${userName}
</c:if>
6. Switch statement in JSTL
Example:
<c:choose>
<c:when test="${userPrefer} == 'performance' ">
You have choosen performance
</c:when>
<c:when test="${userPrefer} == 'safety' ">
You have choosen safety
</c:when>
<c:when test="${userPrefer} == 'maintanance' ">
You have choosen maintanance
</c:when>
<c:otherwise>
You have choosen the default performance
</c:otherwise>
</c:choose>
* NOTE: Here <c:otherwise> is not mandatory
7. <c:set> is cooler than <jsp:setProperty>
Comes in 2 ways
1. var - This is for setting attribute variabled
2. target - This is for setting bean properties or map values
And these 2 comes in with or without body which is just another way to do
Without body:
<c:set var="userLevel" scope="session" value="Cowboy" />
or
<c:set var="fido" scope="session" value="${person.dog}" />
* Here if the session attribute doesnot exist, then it will create a new attribute (assuming the value attribute is not null)
* NOTE: If the variable value is null, then the variable will be removed
& most importantly if this var had a value earlier also it will be removed
With body:
<c:set var="userLevel" scope="session" value="Cowboy" >
Sherif, Cowboy, Bartender
</c:set>
8. Using <c:set> with Beans and Maps [only]
Without body
<c:set target="${petMap}" property="dogName" value="Beagle" />
Here,
target - is the map and it MUST NOT BE NULL
property - since the target is a Map, this field is a key
If its a bean, then this is the bean property
value - is the value for the key
With body
<c:set target="${person}" property="name" >
${foo.name} // here it can be a string or an expression
</c:set>
* Here target should not be an id.. it should be a REAL OBJECT.. its a real attribute and not bean or a map
* If the target is a bean and does not have property, the ${bean.notAProperty} exception is thrown
9. Using <c:remove> to remove the attribute:
Example:
<c:remove var="tmpVar" scope="request" />
* Here scope is optional. But when its not given, the attributes from all scopes are removed
* And the var attribute must be a String and not an expression
10. <c:import> JSTL another way to include external content into the jsp
Example:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<body>
<c:import url="http://www.wickedlysmart.org/yy/human.html" />
</body>
</html>
* The <c:import> is similar to <jsp:include> but with that, its more powerful.
* And note here, the imported URL is the one which comes from outside the domain
* And if you want to pass a param to the called page/jsp, just add <c:param> element which we did in case of <jsp:param>
Ex:
<c:import url="header.jsp" >
<c:param name="subTitle" value="This is a Header call from contact.jsp" />
</c:import>
In header.jsp, render the value of the param like: ${subTitle}
11. URL Rewriting using <c:url>
* If the cookies are disabled and one wants to support url-rewriting in a jsp, then <c:url> helps.
<html><body>
Hyperlink with URL Enabled
<a href="<c:url value='/input.jsp' />">Please click here</a>
</body></html>
* And this will append the JSESSIONID to the end of the url if cookies are disabled
* If you want to combine URL Rewriting and Encoding (remember the space between words)
<c:set var=”last” value=”One” />
<c:set var=”first” value=”Ra”/>
<c:url value=”/inputComments.jsp” var=”inputURL” >
<c:param name=”firstName” value=”${first}” />
<c:param name=”lastName” value=”${last}” />
</c:url>
By doing above, URL rewriting and encoding both are taken care
12. User Defined Error Pages
// error.jsp
<%@ page isErrorPage="true" %>
<html><body> <!-- Paste some error image here --> </body></html>
// some_buggy_page.jsp
<%@ page errorPage="true" %>
<% int x = 1/0; %>
13. Configuring Error pages in DD
* Can configure based on Error code and Exception type
<error-page>
<exception-type>java.lang.Throwable</exception-type>
<location>/error.jsp</location>
</error-page>
<error-page>
<error-code>404</error-code>
<location>/not404Found.jsp</location>
</error-page>
And in the errorPage.jsp,
* We can access the exception object using scriplet reference exception
and in EL using ${pageContext.exception}
14. Using catch tag to handle exception catch
Here the <c:catch> acts as both try and catch, meaning the risky code is written between stard and end tag
& when exception happens, the code execution resumes from the point where </c:catch> ends
<html><body>
<c:catch>
<% int i = 100/0; %>
</c:catch>
</body></html>
* Here, we can make exception as an attribute and use. Normally we cannot use exception reference because there is no exception created
<html><body>
<c:catch var="myExceptionObj">
<% int i = 100/0; %>
</c:catch>
</body></html>
<c:if test="${myExceptionObj} != null">
There is an Exception ${myExceptionObj.message}
</c:if>
15. Tag Library example
<tlib-version>1.2</tlib-version> // Mandatory tag but not the value
<short-name>RandomTags</short-name> // Mandatory.. Its for tools to use
<function> // EL Functions
<name>rollIt</name>
<function-class>foo.DiceRoller</function-class>
<function-signature>int rollDice()</function-signature>
</function>
<uri>randomThings</uri> // Unique name used in taglib directive
<tag>
<description>random advice</description> // optional
<name>advice</name> // the real tag name we are going to use
<tag-class>foo.AdvisorTagHandler</tag-class> // For the container to know what to call
<body-content>empty</body-content> // Required. Says body should be empty
<attribute> // All about the attribute of the tag
<name>user</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue> // runtime expression value is allowed apart from String literal
</attribute>
</tag>
Used as below:
<%taglib uri="randomThings" prefix="my" %>
<my:advice user="vishravars" />
</body>
Custom Tag Handler:
import javax.servlet.jsp.tagext.SimpleTagSupport;
public class AdvisorTagHandler extends SimpleTagSupport {
private String user; // remember the attribute of the tag
public void doTag() throws JspException, IOException { // Container calls this when jsp invokes the tag
getJspContext().getOut().write( “Hello “ + user + “ <br>” );
getJspContext().getOut().write( “Your advice is: “ + getAdvice() );
}
public void setUser(String user) {
this.user=user;
}
}
String getAdvice()
{
String[] adviceStrings = {“That color’s not working for you.”, “You should call in sick.”, “You might want to rethink that haircut.” };
int random = (int) (Math.random() * adviceStrings.length);
return adviceStrings[random];
}
}
* NOTE: The functions are purely the EL invoking static functions. For tags, only the doTag
* The <rtexprvalue> is not only for EL but for Scripting expressions and <jsp:attribute> standard actions
<mine:advice>
<jsp:attribute name=”user”>${userName}</jsp:attribute>
</mine:advice>
// Here name attribute tells the name of the actual element attribute
<body-content>scriptless</body-content> - only scripting elements not allowed.. template text and EL allowed
<body-content>empty</body-content> - nothing
<body-content>tagdependent</body-content> // only plain text
<body-content>JSP</body-content> // anything that can go inside a jsp
* NOTE: The taglib uri is not a location but just a name
* From Jsp 2.0, no need to map taglib uri to a TLD file in web.xml file..
The container automatically created a map for uri names and TLD files
16. 4 places where container looks for TLDs
1. Directly inside WEB-INF
2. Directly inside a subdirectory of WEB-INF
3. Inside META-INF directory which inside a JAR file under WEB-INF/lib
4. Inside a sub-directory of META-INF directory which inside a JAR file under WEB-INF/lib
Taglib Checklist:
1. Do not use the reserver prefixes for taglib... jsp:, jspx:, java:, javax:, servlet:, sub:, sunw:
2. Choose unique URI names in TLDs
Advertisement
Entry filed under: Education, programming, web. Tags: .
Trackback this post | Subscribe to the comments via RSS Feed