Head first Servlets and Jsp Chapter 13 Short Notes

Filters and Wrappers

Objectives:
1. Write web container request processing model; write and configure filter; create request response wrapper;
Given a design scenario decide bw filter or wrapper
2. Knowing Patterns: Intercepting filters, MVC, Front Controller, Service Locator, Business Delegate and Transfer Object

1. Filters:

* Filters are java classes that are used to process before request reaches container and after the response is sent to client but before it reaches client
* Request and Response filters are possible with Filter interface
* These filters are configured in DD and is in total control with the deployment expert and not the servlet developer
* Filters can be chained

2. Request Filters:
* Perform security checks
* Reformat req. headers and body
* Audit or log requests

3. Response Filters:
* Compress response streams
* append or alter response
* create a different response altogether

4. Filters are like Servlets in 3 ways
* Container knows their API (moment when u implement the Filter interface plain class becomes special class)
* They have life cycle methods like: init(), destroy() and doFilter()
* They are declared in DD

5. Creating a request filter to track who made request:

* MUST implement init() method to save the FilterConfig reference
* implement doFilter(ServletRequest, ServletRespose, FilterChain) method
Forward the request and response by calling chain.doFilter(req,res)
Type case request to HttpServletRequest
Get the user name by calling request.getRemoteUser()
And also use filterConfig.getServletContext().log(“blah blah” + remoteUser)
* MUST implement the destroy() method to do cleanup stuffs

6. Declaring and ordering filters

* Declare the filter
<filter>
BeerRequest
<filter-class>example.web.BeerRequestFilter
<init-param>
LofFileName
<param-value>log.txt
</filter>

* Declaring filter mapping to a URL pattern
<filter-mapping>
<filter-name>BeerRequest</filter-name>
<url-pattern>*.do</url-pattern>
</filter-mapping>

* Declaring filter mapping to a Servlet Name

<filter-mapping>
<filter-name>BeerRequest</filter-name>
<servlet-name>BeerAdviceServlet</servlet-name>
</filter-mapping>

If more than one filter is mapped to a Servlet or URL Pattern, all filters are taken up and then executed in the order they appear

* From Servlet spec 2.4, filters are applicable for dispatcher call as well

<filter-mapping>
<filter-name>BeerRequest</filter-name>
<url-pattern>*.do</url-pattern> or <servlet-name>
<dispatcher>REQUEST</dispatcher> or INCLUDE or FORWARD or ERROR where REQUEST is the default when not specified
</filter-mapping>

* When we need to write a response filter, then create one new response class by extending any of the response Wrapper classes
so that the response is not immediately written back to client when the servlet finishes !

May 26, 2011 at 3:56 am Leave a comment

Head first Servlets and Jsp Chapter 12 Short Notes

Web app Security

Coverage:

1. Security issues: Authentication, Authorization, data integrity and confidentiality
2. Security configurations in DD
3. Describe authentication mechanisms (BASIC, DIGEST, FORM and CLIENT-CERT)

1. Importance
	Authentication - Medium
	Authorization - High
	Confidentiality - Low
	Data Integrity - Low

2. Authentication & Authorization example

Problem with tomcat-users.xml is every time you change, we need to restart the server to reload the table

Authentication Step1:

tomcat-users.xml
	<tomcat-users>
		<role rolename="guest"/>
		<role rolename="member"/>
		<user username="vicky" password="vicky123" roles="guest,member" />
		.......
	</tomcat-users>

Authentication Step2:

Enabling the authentication
in DD,

<login-config>
	<auth-method>BASIC</auth-method>
</login-config>

Authorization Step 1:

Map the vendor specific roles in DD

<security-role><role-name>guest</role-name></security-role>
<security-role><role-name>member</role-name></security-role>

Now container can map roles with the users & hence with the resources

<web-app>
	<security-constraint>
		<web-resource-collection>
			<web-resource-name>MandatoryNameUsedByTools</web-resource-name>

			<url-pattern>/Beer/Dish/*</url-pattern>
			/Beer/recipe/*

			<http-method>GET</http-method>
			<http-method>POST</http-method>
		</web-resource-collection>

		<auth-constraint>
			<role-name>guest</role-name>
			<role-name>member</role-name>
		</auth-constraint>
	</security-constraint>

</web-app>

* Can have more than one <web-resource-collection> for a <security-constraint>
* And <auth-constraint> is common/applies for all security constraints
* <http-method>ANY<http-method> says all methods are allowed for the role if specified
* Here constraints are not at RESOURCE lever but they are at REQUEST level

Ex: If url pattern is specified with HTTP method and mapped roles, then these roles are contained by url based on the HTTP method
* Like wise if you specify one <http-method>, then all the other methods are unconstrained!
Good practice;
1. Do not specify ANY in <http-method>
2. Specify particular http method to apply the constraint

<role-name> rules:

* Within <auth-constraint> this element is optional
* If role is specified, only that role is allowed for authentication
* If <role-name> is NO, then no user is allowed
* If <role-name> is * then all users are allowed
* Role names are case-sensitive

<auth-constraint> rules:

* It's an optional stuff
* If exists, container must perform authentication
* If not present, container must present unauthenticated access to the URLs
* <auth-constraint/> -> then no roles are allowed access !
* <auth-constraint>NO</auth-constraint> - All are allowed

* NOTE:- Here the access or non-access is applicable only for users / clients who tried to enter directly.
* And rules does not apply for a request dispatch internally happening !

Programmatic Security:

In HttpServletRequest, there are 3 methods which could be used to achieve programmatic security

* getUserPrinciple() and getRemoteUser() are 2 methods not discussed for the exam

* isUserInRole() 

	1. If the user is not authenticated, then this method returns false
	2. If authenticated, the container checks if the user is mapped to the role
	3. If the user is mapped under the role (passed as argument), then returns true

Declarative side of Programmatic Security:

<web-app>
....
	<servlet>
		<security-role-ref>
			<role-name>manager</role-name>
			<role-link>admin</role-link>
		</security-role-ref>
	</servlet>

	<security-role>
		Admin
	</security-role>

</web-app>

<security-role-ref> element maps programmatic role (hard-coded) names to the declarative role names (actual)

* In the above example, the developer has hard-coded "manager" as the role name in code but the company uses "admin" as <security-role>.
	So in this case we can link the actual role with the used role (programmatic) in code
* Container will use <security-role-ref> even if the role matches with the actual <security-role>. Hence it always takes precedence.

Authentication types

* BASIC
	<login-config>
		<auth-method>BASIC</auth-method>
	</login-config>

	Basic form sends the data in encoded (non-encrypted) form which is not strong. It uses base64 scheme of encoding
* DIGEST
	<login-config>
		<auth-method>DIGEST</auth-method>
	</login-config>

	Not supported much because of its weakness
* CLIENT-CERT
	<login-config>
		<auth-method>DIGEST</auth-method>
	</login-config>
	It uses the public key encryption and is v.rarely used because client has to keep the certification which does not happen in most of the cases
* FORM
	It allows the developer to create his own custom form (html) with input controls
	This is the weakest of all methods and has no encryption
In dd
	<login-config>
		<auth-method>DIGEST</auth-method>
		<form-login-config>
			<form-login-page>/loginPage.html</form-login-page>
			<form-error-page>/loginError.html</form-error-page>
		</form-login-config>
	</login-config>

In loginPage.html

	<form method="post" action="j_security_check">
		<input type="text" name="j_username"/>
		<input type="password" name="j_password"/>
		<input type="submit" value="Login/Enter"/>
	</form>

In loginError.html
	<b>Sorry entered invalid login info</b>

Data Integrity and Confidentiality:
	These can be maintained by using the HTTPS with ssl (remember verisign for ssl certificates !). This comes handy in the custom FORM based authentication.

This can be achieved with the help of <user-data-constraint> element which needs to be placed under <security-constraint>

<webapp>
	<security-constraint>
		...........

		<user-data-constraint>
			<transport-guarantee>CONFIDENTIAL</transport-guarantee>
		</user-data-constraint>
	</security-constraint>
</webapp>

NONE - default and means no data protection
INTEGRAL - data must not be changed along the way
CONFIDENTIAL - Data must not be seen by anybody along the way

here both INTEGRAL and CONFIDENTIAL means the same in most of the container implementations

May 25, 2011 at 6:16 pm Leave a comment

Head first Servlets and Jsp Chapter 11 Short Notes

Note: Feel free to copy the post, modify and comment
Deploying your webapp

Objectives:
* Deployment directory structure
* Describe purpose and semantics of error-page, init-param, mime-mapping, servlet, servlet-class, servlet-mapping, servlet-name and welcome-file
* Explain structure and purpose of WAR file
* Write a jsp language with xml based syntax

1. Need to consider 3 things to understand the deployed app

1. Where to put the files and directories
2. Where will the container look for things in webapp
3. How does the client request things in web app

Building directory structure for the following
* TLDs, Tags, web.xml, static-htmls, Jsps, Classes, jars etc..,

2. WAR File
* In tomcat, the name of the WAR file becomes the webapp name
* META-INF/MANIFEST.MF where you can declare the WAR library dependencies so that container can check at runtime instead of blowing up with application runs

3. Making JSPs and static htmls accessible
* Can prevent direct access by placing the files under WEB-INF or META-INF (in case of war file). And will return 404 on error

4. Configuring welcome-file
<web-app>
	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
		<welcome-file>default.html</welcome-file>
	</welcome-file-list>
</web-app>
* no slash allowed in beginning or end

5. Error pages in DD

<error-page>
	<exception-type>java.lang.throwable</exception-type>
	<location>/errorpage.jsp</location>
</error-page>

<error-page>
	<error-code>404</error-code>
	<location>/notFoundpage.jsp</location>
</error-page>

or

response.sendError(HttPServletResponse.SC_FORBIDDEN);

6. Configuring Servlet initialization

<servlet>
	<servlet-name>....
	<load-on-startup>1</load-on-startup>
</servlet>

Any number > 0 can be used
The number says the order of startup. For same values, its loaded as per the order of appearance in DD

7. XML Compliant JSP

directive: <jsp:directive.page import=""/>
declaration: <jsp:declaration>int a = 3;
scriplet: list.add("")
text: <jsp:text>this is a text
Scription expression: aVariable

8. EJB Related Deployment descriptor

Local reference:

<ejb-local-ref>
	<ejb-ref-name></ejb-ref-name>
	<ejb-ref-type>Entity</ejb-ref-type>
	<local-home></local-home>
	<local></local>
</ejb-local-ref>

Remote Reference:

<ejb-ref>
	<ejb-ref-name></ejb-ref-name>
	<ejb-ref-type>Entity</ejb-ref-type>
	<home></home>
	<remote></remote>
</ejb-ref>

9. Memorizing the JNDI  DD tag

<env-entry>
	rates/discountRate
	<env-entry-type>java.lang.Integer
	<env-entry-value>10
</env-entry>

* Env entry cannot be primitive and can declare any type which can take string as an arg in constructor
* And this works only if you have a fully j2ee compliant server and not just web container

10. Mime mapping

<mime-mapping>
	<extension>mympg</extension>
	<mime-type>video/mpeg</mime-type>
</mime-mapping>

May 25, 2011 at 6:11 pm Leave a comment

Head first Servlets and Jsp Chapter 10 Short Notes

Note: Feel free to copy the post, modify and comment

Custom Taglibraries

Classic custom tag event model
Using PageConext API to access implicit variables
Accessing Parent Tag
semantics of Tag File model

1. Tag Files
Alternative and better way to implement <jsp:include> or is to use tag file.
This helps including the reusable components using just a tag and not using standard actions.

Example:

1. Create a Header.jsp and rename it to Header.tag
2. Place the tag file under web-inf directory and under tags directory
3. Now Use the tag include in the Main.jsp like below

<%@ taglib prefix=”myTags” tagDir=”/WEB-INF/tags” %>

<myTags:Header/> — This includes the re-usable content dynamically

But how do we pass the parameters ? remember <jsp:param> element we used while using and ?

Here we use attrubute directly,
<myTags:Header subTitle=”This is the subtitle given to page dynamically” />

In Header.tag, use the following to retrieve the value passed by above statement
<em>${subTitle}</em>

* PS: Once the tag is closed, the tag attribute goes out of scope
* In the approach one good thing is the attribute that is passed has lesser scope and restricted to only the tag file associated,
whereas in the earlier approach of <jsp:include>, a new request parameter is created which is exposed to all jsps and servlets that interact with the page.

Using Attribute Directive in Tag file:

When you want to force the attribute usage of the tag, we can do that by using attribute directive

In Header.tag
<%@ attribute name=”subTitle” required=”true” rtexprvalue=”true”%>
<em>${subTitle}</em>
in Main.jsp
<%@ taglib prefix=”myTags” tagDir=”/WEB-INF/tags” %>
<myTags:Header subTitle=”This is the subtitle given to page dynamically”/>

doBody> :
In case if the attribute value is too long.. like a paragraph, then use the tag in the tag file and do not use attrubute directive

In Header.tag
<em><jsp:doBody/></em>
in Main.jsp
<%@ taglib prefix=”myTags” tagDir=”/WEB-INF/tags” %>
<myTags:Header>
This is the subtitle given to page dynamically,This is the subtitle given to page dynamically,This is the subtitle given to page dynamically
<!–myTags:Header>

How to force the body-content rule then ?

Use the tag directive !

In Header.tag
<%@ attribute name=”fontColor” required=”true”%>
<%@ tag body-content=”tagdependant”%>
in Main.jsp
<%@ taglib prefix=”myTags” tagDir=”/WEB-INF/tags” %>
<myTags:Header fontColor=”blue”>
This is the subtitle given to page dynamically,This is the subtitle given to page dynamically,This is the subtitle given to page dynamically
</myTags:Header>

body-content,
tagdependant – Scriptlets, EL and tags are not evaluated
empty – nothing should be there in body
scriptless – only scripts are not evaluated

Where does container search for tag files:

1. Directly inside WEB-INF/tags
2. Inside a subdirectory of WEB-INF/tags
3. Inside META-INF/tags directory inside a jar file thats inside WEB-INF/lib
4. Inside subdirectory of META-INF/tags directory inside a jar file thats inside WEB-INF/lib
5. If the tag is deployed inside a jar, there must be a tld for the tag file

* The tag file have access to request and response
* EL works
* And we have access to JspContext instead of ServletContext
* We can combine tld and tag files to be considered by container as a same library. Use tag reference inside TLD

Referring tag file inside a tld

<tag-file>
<name>Header</name>
<path>/META-INF/tags/Header.tag</path>
</tag-file>

2. Simple Tag Handler:

1. Write a class that extends SimpleTagSupport
2. Override the doTag() method
3. Create a TLD for the tag
4. Deploy the tag handler and the TLD
5. Write the jsp that uses the TLD

Simple Tag API Hierarchy:

JspTag (Interface) -> SimpleTag (Interface) -> SimpleTagSupport(Class)

Life Cycle of Simple Tag Handler:

1. Load the class SimpleHandler
2. Instantiate class object of your class (tag handler)
3. Call setJspContext(JspContext) – gives the handler a reference to PageContext (subclass of JspContext)
4. If the tag is nested, then call the setParent(JspTag) method (nested tags can communicate with parent tags)
5. If the tag has setters, then call them (remember java Bean standard ?)
6. If the tag can have body, then call setJspBody() method
7. Then finally the overrided method doTag()

What if the tag body uses an expression ?

in public void doTag() {
getJspContext().setAttribute(“message”,”this is a message from class to the jsp”);
getJspBody().invoke (null); // sets attribute and invokes the body
}

<myTags:simple>
Message is: ${message}
</myTags:simple>

Or

Can also loop the body call with for loop and print an array of messages. But every time remember to call invoke()

What about attributed of the Tag ?

Set the attribute value in bean setter method and later can also be used in body evaluation !

SkipPageException:

throw this exception if you feel some value is not supplied properly.
* It shows everything upto the point of exception is thrown !
* And when u throw this exception in an included page, then main page functions or continues after the exception in included page
* If you wish to specify attribute type as non primitive, then use <rtrexprvalue>true</rtrextrvalue>

If the body is declared to have content and if we do not give body then setJspBody() will not be called

JspFragment has 2 methods -> invoke() and getJspContext()

3. Classic Tag Handler:

It has 5 interfaces and 3 support classes. We would always be extending the support classes for tlds.

* Create the TLD v.similar to the simple tag handler
* Create the tag handler class to extend TagSupport
* Override the doStartTag() method which throws JspException and not IOException. Hence need to handle IO errors.
Return type is int which tells the container what to do next.
* return int to instruct the container. Ex. SKIP_BODY
* Override the doEndTag() method and return EVAL_PAGE (to evaluate rest of the page)

When the tag has Body !

* In the doStartTag() method, return EVAL_BODY_INCLUDE to evaluate the body

Classic tags lifecycle:

* Container loads the ClassicTagHandler.class
* Instantiate the class
* Call the setPageContext() method -> This gives handle reference to Context object
* If tag is nested, then call setParent(Tag) method
* If tag has attributes, then call the attribute setters
* Call doStartTag() method
* If the tag tld does not say empty body and if the body is not empty and if doStartTag() returns EVAL_BODY_INCLUDE, body is evaluated
* If body is evaluated, the calls doAfterBody() method
* Call doEndTag() method

Possible Return values:

doStartTag()
SKIP_BODY
EVAL_BODY_INCLUDE
doAfterBody()
SKIP_BODY
EVAL_BODY_AGAIN – only constant declared in IterationTag interface
doEndTag()
SKIP_PAGE
EVAL_PAGE

Example:-
int movieCounter=0;
String movies[] = new String []{“Spider man”,”Amelie”};
public int doAfterBody() throws JspException {
if (moieCounter < movies.length) {
pageContext.setAttribute(“movie”,movies[movieCounter]);
movieCounter++;
return EVAL_BODY_AGAIN;
}else {
return SKIP_BODY;
}
………..
}

JSP that invokes;

<%@ taglib prefix=”my” uri=”ClassicTagsTest” %>
<html><body>
<my:iterateMovies>
${movie}
</my:iterateMovies>
</body></html>

This calls the movie to get printer 2 times

Default return values of the methods:

doStartTag() -> SKIP_BODY
doAfterBody() -> SKIP_BODY -> body evaluated only once !
doEndTag() -> EVAL_PAGE

Dynamic Attributes:

To handle any non-mandatory attributes, implement DynamicAttributes interface and use a hashmap to set the key(attribute name) and value in it.
This can later by used within the doTag() method

In the tld file we need entry like below.

<attribute>
<dynamic-attributes>true</dynamic-attributes> // this says any number of dynamic attributes are allowed
</attribute>

May 25, 2011 at 9:36 am Leave a comment

Head first Servlets and Jsp Chapter 9 Short Notes

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 : > - &gt; < - &lt; & - &amp; ' - ' " - "

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

April 28, 2011 at 6:53 pm Leave a comment

Older Posts



Follow

Get every new post delivered to your Inbox.