JavaBeat

  • Home
  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)
  • Privacy
  • Contact Us

What is load on startup element in web.xml file

February 21, 2013 by Krishna Srinivasan Leave a Comment

specify the order in which we want to initialize various Servlets. Like first initialize Servlet1 then Servlet2 and so on.
This is accomplished by specifying a numeric value for the  <load-on-startup> tag. <load-on-startup> tag specifies that the servlet should be loaded
automatically when the web application is started.

The value is a single positive integer, which specifies the loading order. Servlets with lower values are loaded before servlets with
higher values (ie: a servlet with a load-on-startup value of 1 or 5 is loaded before a servlet with a value of 10 or 20). When loaded, the init() method of the servlet is called. Therefore this tag provides a good way to do the following:

start any daemon threads, such as a server listening on a TCP/IP port, or a background maintenance thread perform initialisation of the application, such as parsing a settings file which provides data to other servlets/JSPs If no <load-on-startup> value is specified, the servlet will be loaded when the container decides it needs to be loaded – typically on it’s first access. This is suitable for servlets that don’t need to perform special initialisation.

I hope that clears all the doubts regarding <load-on-startup> in web.xml.

Filed Under: Java EE Tagged With: JSP, Servlets

Accessing Portlet-specific Objects in JSP Pages

April 30, 2011 by Krishna Srinivasan Leave a Comment

This article is based on Portlets in Action, to be published June 2011. I t is being reproduced here by permission from Manning Publications. Manning publishes MEAP (Manning Early Access Program,) ebooks and pbooks. MEAPs are sold exclusively through Manning.com. All print book purchases include an ebook free of charge. When mobile formats become available all customers will be contacted and upgraded. Visit Manning.com for more information.

also read:

  • Java EE Tutorials
  • Servlets Interview Questions
  • New Features in Servlets 3.0
  • Asynchronous Servlets in Servlets 3

Introduction

In a lot of cases, JavaServer Pages (JSPs) may rely on JSP implicit objects to achieve their functionality. It is perfectly fine to use JSP implicit variables in your JSP pages, but, on the downside, your JSP is dealing with servlet-specific objects (like HttpServletRequest and HttpSession) and not portlet-specific objects (like RenderRequest and PortletSession).

If we add an attribute to RenderRequest, it’s mirrored by HttpServletRequest and vice versa. The same applies to HttpSession and PortletSession. So what difference does it make if we use portlet-specific objects in JSPs? Subtle differences between servlet and portlet API can answer this question. For instance, in your JSP page, you can’t use HttpServletResponse to create a portlet URL (only a RenderResponse object provides methods to create portlet URLs). HttpServletRequest can’t provide the information about the portlet mode and the window state (PortletRequest provides methods to obtain the portlet mode and the window state). This is like rain and freezing rain—both are forms of precipitation with the only difference in what happens when raindrops hit the ground.

In general, your JSP pages will use a combination of portlet and servlet objects to generate content. For instance, if you want to set the expiration time for the content in the JSP page, you will use the RenderResponse portlet object. If you need to obtain the value of an APPLICATION_SCOPE portlet session attribute, you may prefer to use session (which refers to HttpSession object) or sessionScope (which is a java.util.Map of session attributes stored in HttpSession object) for a JSP implicit object to obtain its value.

NOTE

JSPs included by portlets have access to JSP implicit objects because portlet application is also a web application.

The name defineObjects gives the impression that it can be used by JSP developers to define custom objects in their JSP pages, but that’s not the case. The defineObjects tag of portlet tag library provides JSPs with access to portlet objects like RenderRequest, RenderResponse, PortletSession, and so on. Table 1 lists the scripting variables (and their type) that are available to JSP pages that use defineObjects tag.

Table 1 shows the scripting variables defined by the defineObject tag. As you can see, defineObjects provides JSP pages with all Portlet 2.0 API objects they’ll ever need to use portlet-specific features. In JSP pages, you’ll usually use a combination of JSP implicit objects and the implicit objects made available by defineObjects tag. You’ll probably never use actionRequest, actionResponse, eventRequest, and eventResponse objects in your JSP pages because the portlet container ignores the content written out to the response in action and event processing phases.

NOTE

defineObjects tag doesn’t define any attributes.

The sample Book Catalog portlet in this article uses scripting variables introduced by defineObjects tag to show the debugging information, as shown earlier in figure 1.

Listing 1 shows debug.jsp page and is included by all JSP pages in the Book Catalog portlet. The debug.jsp page prints the information about the portlet mode, the window state, the value of myaction attribute from request, the content expiration time, and so on, most of which is obtained using scripting variables introduced by defineObjects tag.

Listing 1 debug.jsp—Using variables introduced by defineObjects tag
[code lang=”java”]<%@ taglib prefix="portlet" #1
uri="http://java.sun.com/portlet_2_0"%> #1
<%@ page contentType="text/html" isELIgnored="false"
import="javax.portlet.PortletSession"%>
<portlet:defineObjects /> #2
….
Value of myaction request attribute:
${requestScope.myaction} #3
Portlet mode of request:
<%=renderRequest.getPortletMode()%> #4
Window state of request:
<%=renderRequest.getWindowState()%> #5
Content Expiration time:
<%=renderResponse.getCacheControl().getExpirationTime()%> #6
seconds
uploadFolder init parameter value:
<%=portletConfig.getInitParameter("uploadFolder")%> #7
myaction attribute value in PortletSession:
${portletSessionScope.myaction} #8
Search criteria stored in PortletSession:
Book name –
<%=portletSession.getAttribute("bookNameSearchField", #9
PortletSession.APPLICATION_SCOPE)%> #9
Author name –
<%=session.getAttribute("authorNameSearchField")%> #10

#1 Declare portlet tab library
#2 defineObjects tag
#3 myaction HttpRequest attribute
#4 Portlet mode from RenderRequest
#5 Window state from RenderRequest
#6 Cache expiration time from RenderResponse
#7 uploadFolder portlet initialization parameter
#8 myaction PortletSession attribute
#9 bookNameSearchField PortletSession attribute
#10 authorNameSearchField HttpSession attribute[/code]
At #1, the JSP page declares the portlet tag library using the taglib directory. The value of the uri attribute is http://java.sun.com/portlet_2_0 if you want to use Portlet 2.0 tag library. If you are using Portlet 1.0 tag library, specify the value of uri as http://java.sun.com/portlet. The defineObjects tag in Portlet 2.0 introduced additional variables like portletSessionScope, portletSession, and so on, which makes it easy to develop portlets using JSP as the view technology. At #2, the defineObjects tag is used to introduce scripting variables in the JSP page. At #3, the requestScope JSP implicit variable is used to obtain the value of the myaction attribute. At #4, the renderRequest variable is used to obtain the current portlet mode. At #5, the renderRequest variable is used to obtain the window state information. At #6, the renderResponse variable is used to obtain CacheControl object, which, in turn, is used to obtain the expiration time for the generated content. At #7, the portletConfig object is used to obtain the uploadFolder portlet initialization parameter. At #8, the portletSessionScope variable is used to obtain the value of the myaction attribute from PortletSession. At #9, the portletSession variable is used to obtain the value of the bookNameSearchField attribute from APPLICATION_SCOPE of PortletSession. At #10, the session JSP implicit variable is used to obtain the value of the authorNameSearchField attribute from HttpSession. We see here that using the session JSP implicit variable makes it easy to retrieve the APPLICATION_SCOPE attribute stored in PortletSession.

Listing 1 shows that we’ll usually use JSP implicit variables and variables introduced by the defineObjects tag to create JSP pages. If you browse through the pages of the Book Catalog portlet, the debugging information will change to reflect the current value of various attributes displayed by the debug.jsp page.

Summary

In this article, we saw how the portlet tag library tags can be used to simplify development of JSP pages used by portlets. Specifically, we learned how to use JSP implicit variables and variables introduced by the defineObjects tag to create JSP pages.

Filed Under: Java EE Tagged With: JSP, Portlets

Dynamic Attributes in Tag File in JSP 2.0

February 26, 2009 by Krishna Srinivasan Leave a Comment

As we know that we can develop custom tag library as a simple tag file in JSP 2.0 and these tag files can accept attributes from the invoking JSP page. But one drawback of this approach is that we need to declare all the attributes in the tag file. JSP 2.0 provides a feature called dynamic attributes by using which we need not declare the attributes in the tag file using the attribute directive.

1) File Name : firstPage.jsp
[code lang=”html”]
<%@ page contentType="text/html" %>
<%@ taglib prefix="my" tagdir="/WEB-INF/tags/mytags" %>
<html>
<head>
<title>Headers</title>
</head>
<body bgcolor="white">
<my:person Age="28" EmployeeId="74852" Name="Bruce Wayne" />
</body>
</html>
[/code]

2) File Name : person.tag
[code lang=”html”]
<%@ tag body-content="empty" dynamic-attributes="dynattrs" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<table border="1" width="30%" height="20%" style="background-color:#EFEFEF">
<c:forEach items="${dynattrs}" var="a">
<tr>
<td>${a.key}</td>
<td>${a.value}</td>
</tr>
</c:forEach>
</table>
[/code]

3) Output

EmployeeId 74852
Name Bruce Wayne
Age 28

Explantion:
In the file firstPage.jsp I invoke a custom tag named person with three attributes : employee id, age and name.

The file person.tag holds the code to handle the person tag invocation. In this file I use the tag directive to declare a page scope attribute named dynattrs. This attribute is a Map of all the attributes and attribute values passed from the JSP page tag invocation. Next, I iterate through each item of dynattrs using c:forEach jstl tag. The property: key returns the map key and the property : value returns the key’s value. I use Expression language syntax ${} to display each key and value stored in the map.

also read:

  • Java EE Tutorials
  • Servlets Interview Questions
  • New Features in Servlets 3.0
  • Asynchronous Servlets in Servlets 3

Filed Under: Java EE Tagged With: JSP, JSP 2.0

Variable Directive in JSP 2.0 Custom Tags

February 25, 2009 by Krishna Srinivasan Leave a Comment

This tips explains how to use the variable directive in the custom tags in JSP 2.0. There is time when JSP page needs to access the variable declared inside the Tag files. In the previous version we have to extend the tag library to declare the variables and need the special handling for those variables. In JSP 2.0, it is done very easily using the variable directive. Syntax for the variable directive is as follows:
[code lang=”html”]
<%@ variable (attribute="value")* %>
[/code]

or

[code lang=”html”]
<@ variable attribute1="value1" attribute2="value2" … %>
[/code]

The following are the list of attributes in variable directive:

  • name-given
  • name-from-attribute
  • alias
  • variable-class
  • declare
  • scope
  • description

Look into the following example:

index.jsp

[code lang=”html”]
<%@ taglib prefix="print" tagdir="/WEB-INF/tags/" %>
<html>
<body bgcolor="white">
<print:varTag>
${testValue}
</print:varTag>
</body>
</html>
[/code]

varTag.jsp

[code lang=”html”]
<%@ variable name-given="testValue" %>
<%
jspContext.setAttribute("testValue", "testValue");
%>
<jsp:doBody/>
[/code]

In the above example it declares one simple variable named testValue and it is access from the JSP page. This example is only very simple and the purpose is to explain how the variable directive is working. Like this you can declare asmany variables in the Tag Files and can be used in the JSP file. at the end of tag file is important to execute the tag body.

also read:

  • Java EE Tutorials
  • Servlets Interview Questions
  • New Features in Servlets 3.0
  • Asynchronous Servlets in Servlets 3

Filed Under: Java EE Tagged With: JSP, JSP 2.0

Custom Tags in JSP 2.0

February 25, 2009 by Krishna Srinivasan Leave a Comment

Tag Files in JSP 2.0

This tips explains about what are the advantages in the Custom Tags in JSP 2.0. It also compares it with the previous JSP versions.

also read:

  • Java EE Tutorials
  • Servlets Interview Questions
  • New Features in Servlets 3.0
  • Asynchronous Servlets in Servlets 3

Lets look into the tips for more detail.
Developing custom tags in the previous JSP versions are tedious and it is considered as one of the complex task for the JSP developers. Because inorderto write a simple custom tag you have to learn many things and should have good knowledge on Java also. Apart from that you have to use Tag APIs to create a complete tag library. Any small mistake will cause the error and tag files will not work. To make the things easy for the JSP developers, JSP 2.0 has the advanced features for creating JSP custom tag libraries.
The following are the mandatory for writing the custom tags in previous versions:

  • Writing and compiling a tag handler.
  • Defining the tag that is associated with the tag handler.
  • Creating the TLD(Taglib Descriptor) files.

What is Tag Files?

JSP 2.0 has introduced the concept called tag files, which are nothing but the simple files works like a JSP file. They define all the functionalities required for a custome tag. You are no longer required to write the Java file and compile it. These tag files are compiled dynamically by the JSP container. Even though, it is simple file, JSP container will convert these files into a Tag Library. But developers need not worry about them.
Tag files just work like an JSP pages, it has the following implicit objects:

  • request -> javax.servlet.http.HttpServletRequest
  • response -> javax.servlet.http.HttpServletResponse
  • out -> javax.servlet.jsp.JspWriter
  • session -> javax.servlet.http.HttpSession
  • application -> javax.servlet.ServletContext
  • config -> javax.servlet.ServletConfig
  • jspContext -> javax.servlet.jsp.JspContext

All the abobe objects are available in the normal JSP files also.
All the tag files must be put under the folder WEB-INF/tags or you can create the sub directory under it. The directory name must be specified while importing the tags in JSP file as follows:

[code lang=”html”]
<%@ taglib prefix="tagFiles"
tagdir="/WEB-INF/tags" %>
[/code]

Tag Files Example

This tips explains only the very basic points about the new features in custom tags and Tag Files. You can find simple example on writing the custome tags in JSP 2.0.

Filed Under: Java EE Tagged With: JSP, JSP 2.0

Custom Tag Libraries and Tag Files in JSP 2.0

February 25, 2009 by Krishna Srinivasan Leave a Comment

With previous versions of JSP developing custom tag libraries was possible only by writing Java classes. As a result knowledge of Java was a must. JSP 2.0 introduces a new way of developing custom tag library using plain JSP. This enables JSP developers, who dont know Java, to develop custom tag libraries as Tag files. JSP 2.0 also provided added features of passing parameters to tag files. I will demonstrate this in the following examples.

also read:

  • Java EE Tutorials
  • Servlets Interview Questions
  • New Features in Servlets 3.0
  • Asynchronous Servlets in Servlets 3

1) File Name : firstPage.jsp
[code lang=”html”]
<%@ page contentType="text/html" %>
<%@ taglib prefix="my" tagdir="/WEB-INF/tags/myCustomTags" %>
<html>
<body bgcolor="white">
Random Number : <my:generateRandomNum />
</body>
</html>
[/code]

2) File Name : generateRandomNum.tag
[code lang=”html”]
<%@ tag body-content="empty" %>
<%
out.println(java.lang.Math.random());
%>
[/code]

3) Output
[code lang=”html”]
Random Number : 0.029871659130147776
[/code]

Explantion:

In my first example I use a tag file to generate random numbers. I will first explain the code in generateRandomNum.tag file. This is just a simple file with a .tag extension and a tag directive. In this file I write the logic to generate random numbers using the java.lang.Math class. Once this file is ready place the file under any location below WEB-INF directory. I have placed it inside /WEB-INF/tags/myCustomTags directory.

Now in the firstPage.jsp I use a taglib directive. In the taglib directive I set the value for two attributes : prefix and tagdir. The prefix sets a prefix to invoke the custom tag and the tagdir attribute
tell the container that the tag file is placed at the location specified. Next I invoke the tag file simply by using
the prefix and the name of the tag file, without the .tag extension

4) File Name : secondPage.jsp
[code lang=”html”]
<%@ page contentType="text/html" %>
<%@ taglib prefix="my" tagdir="/WEB-INF/tags/myCustomTags" %>
<html>
<body bgcolor="white">
Sum of two numbers : <my:addNumbers firstNum="10" secondNum="20" />
</body>
</html>
[/code]

5) File Name : addNumbers.tag
[code lang=”html”]
<%@ tag body-content="empty" %>
<%@ attribute name="firstNum" required="true"%>
<%@ attribute name="secondNum" required="true"%>

${firstNum + secondNum}
[/code]

6) Output
[code]
Sum of two numbers : 30
[/code]

Explantion:

In this second example I explain the usage of passing attributes to tag files. In the file addNumbers.tag I have used a directive called attribute. This is basically used to tell the web container that this tag file expects an attribute and whether the attribute is mandatory or optional.

We should use the attribute directive for each attribute passed from the invoking jsp file. I declare two attributes and use them to perform an add operation using Expressions Langauge (EL).

In the file secondPage.jsp I invoke the tag and pass attributes with some values. The values will be received by the attributes declared in the tag file and will be used to perform the addition.

Filed Under: Java EE Tagged With: JSP, JSP 2.0

Error Pages in JSP 2.0

February 24, 2009 by Krishna Srinivasan Leave a Comment

We can configure error pages in jsp and servlets to direct the control to a custom error page, showing a friendly error message to the user when an exception is thrown in the page. But tracking or logging the exception information is not very easy in JSP 1.2.

also read:

  • Java EE Tutorials
  • Servlets Interview Questions
  • New Features in Servlets 3.0
  • Asynchronous Servlets in Servlets 3

JSP 2.0 fixes this problem by switching to the servlet specification: javax.servlet.error.exception. In addition, a new property of the implicit EL pageContext variable, named errorData, exposes other information about the problem. The errorData property is an instance of the javax.servlet.jsp.ErrorData class that can be used as a bean with the following properties:

[code lang=”html”]
<table border="1" width="55%" style="background-color:#EFEFEF">
<tr align="center">
<td width="10%"><b>Property</b></td>
<td width="12%"><b>Java Type</b></td>
<td><b>Description</b></td>
</tr>
<tr align="left">
<td>requestURI</td>
<td>String</td>
<td>The URI for the request that failed.</td>
</tr>
<tr>
<td>servletName</td>
<td>String</td>
<td>The name of the servlet or JSP page that failed.</td>
</tr>
<tr>
<td>statusCode</td>
<td>int</td>
<td>The failure status code. </td>
</tr>
<tr>
<td>throwable</td>
<td>Throwable</td>
<td>The exception that caused the error page to be invoked.</td>
</tr>
<table>
[/code]

1) File Name : firstPage.jsp
[code lang=”html”]
<%@page errorPage="/jsp/errorpage.jsp" contentType="text/html" %>
<html>
<head>
<title>Error Pages in JSP 2.0</title>
</head>
<body>
<%
String s = null;
out.println(s.trim());
%>
</body>
</html>
[/code]

2) File Name : errorpage.jsp
[code lang=”html”]
<%@page isErrorPage="true" contentType="text/html" %>
<html>
<body>
Request that failed: ${pageContext.errorData.requestURI}

Status code: ${pageContext.errorData.statusCode}

Exception: ${pageContext.errorData.throwable}

${pageContext.errorData.servletName}
</body>
</html>

[/code]

3) Output
[code]
Request that failed: /TestWebApp/jsp/firstPage.jsp
Status code: 500
Exception: java.lang.NullPointerException
jsp
[/code]

Explantion:

In the first page I declare a null string and I call a function on it. The JSP engine will encounter faulty code and will throw a NullPointerException. As I have configured an error page in the page directive the control is taken to the errorpage.jsp.

In the error page I use properties of errorData to display useful information about the exception. This information is useful for the developer to track down the problem quickly and efficiently as he will know exactly which page threw the exception and what was the type of exception.

Filed Under: Java EE Tagged With: JSP, JSP 2.0

Ternary Operator in JSP 2.0 Expression Language(EL)

February 23, 2009 by Krishna Srinivasan Leave a Comment

A very common need in a JSP page is to include a piece of template text only if a certain condition is true.
With JSP 1.2 and JSTL 1.1, this is typically done using a block, but that’s a very verbose solution.

also read:

  • Java EE Tutorials
  • Servlets Interview Questions
  • New Features in Servlets 3.0
  • Asynchronous Servlets in Servlets 3

JSP 2.0 adds a new conditional operator to the Expression Language(EL) to deal with this case in a more elegant way.The
conditional operator exists in many programming languages (for instance, in Java, C, and JavaScript), so you may have seen it before. It takes a Boolean condition and one result to use if the condition is true and another if it’s false. I use a very simple example to demonstrate the usage :

1) File Name : firstPage.jsp
[code lang=”html”]
<html>
<head>
<script language="javascript">
function checkNumber()
{
var number = document.forms[‘myForm’].numberTxt.value;
if(number < 1 || number > 5 || isNaN(number))
{
alert("Please enter a number between 1 and 5");
return false;
}
}
</script>
</head>
<body>
<form name="myForm" method="post" action="secondPage.jsp">
Please enter a number between 1 and 5 and press the Ok button :
<br />
<input type="text" id="numberTxt" name="numberTxt" />
<br />
<input type="submit" name="btnSubmit" value="Ok" onclick="return(checkNumber());"/>
</form>
</body>
</html>
[/code]

2) File Name : secondPage.jsp
[code lang=”html”]
<html>
<head>
</head>
<body>
<form>
<select>
<option value="1" ${param.numberTxt == 1 ? ‘selected’ : ”}>Suresh</option>
<option value="2" ${param.numberTxt == 2 ? ‘selected’ : ”}>Ramesh</option>
<option value="3" ${param.numberTxt == 3 ? ‘selected’ : ”}>Naresh</option>
<option value="4" ${param.numberTxt == 4 ? ‘selected’ : ”}>Rajeev</option>
<option value="5" ${param.numberTxt == 5 ? ‘selected’ : ”}>Pawan</option>
</select>
</form>
</body>
</html>
[/code]

Explantion:

In the first page I enter a number between 1 and 5 and click the submit button. The request is submitted to the second page. In the second page I have used a drop down list to display some names. Out of these names one of them gets selected depending on what value is entered in the first page.

I use the param expressions language implicit object,which contains a map of request parameters, to fetch the value of numberTxt parameter. The value is compared with fixed constants for each option tag. If an expression returns true, the string selected is replaced in its place. In case the expression returns false blank string is replaced.

Filed Under: Java EE Tagged With: JSP, JSP 2.0

Follow Us

  • Facebook
  • Pinterest

As a participant in the Amazon Services LLC Associates Program, this site may earn from qualifying purchases. We may also earn commissions on purchases from other retail websites.

JavaBeat

FEATURED TUTORIALS

Answered: Using Java to Convert Int to String

What is new in Java 6.0 Collections API?

The Java 6.0 Compiler API

Copyright © by JavaBeat · All rights reserved