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

JSTL Function in JSP 2.0

March 3, 2009 by Krishna Srinivasan Leave a Comment

In JSP 2.0 we can perform string operations in JSP without using any java code inside scriptlets. This is possible with the latest release of JSTL 1.1. The new library called Functions with prefix as fn allows us to perform string operations in JSP 2.0.

also read:

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

The following example explains all the string operation which we can perform with the new fn tags.
Note:

  • You will need the following files to run this example :
  • jstl.jar and standard.jar inside /WEB-INF/lib
  • fn.tld, c.tld inside any location under any lcation under WEB-INF
  • JSP 2.0 Function : Example

    1) File Name : firstPage.jsp
    [code lang=”html”]
    <%@ page contentType="text/html" %>
    <html>
    <body>
    <form name="myForm" method="post" action="functionsUsage.jsp">
    Select an operation and click the button
    <input type="radio" name="radioBtnGroup" value="uCaseOp" />Convert a string to upper Case
    <input type="radio" name="radioBtnGroup" value="lCaseOp" />Convert a string to lower Case
    <input type="radio" name="radioBtnGroup" value="subStrOp" />Get a substring of a string
    <input type="radio" name="radioBtnGroup" value="subStrAfterOp" />Get substring after
    <input type="radio" name="radioBtnGroup" value="subStrBeforeOp" />Get substring before
    <input type="radio" name="radioBtnGroup" value="trimOp" />Trim the string
    <input type="radio" name="radioBtnGroup" value="replaceOp" />Replaces characters in a string
    <input type="radio" name="radioBtnGroup" value="splitOp" />Split a string
    <input type="radio" name="radioBtnGroup" value="joinOp" />Join a string after it has been split
    <input type="radio" name="radioBtnGroup" value="escapeXml" />Escapes XML characters in a string
    <input type="radio" name="radioBtnGroup" value="indexOf" />Find start index of a substring in a string
    <input type="radio" name="radioBtnGroup" value="startsWithOp" />Check if the string starts with a particular substring
    <input type="radio" name="radioBtnGroup" value="endsWithOp" />Check if the string end with a particular substring
    <input type="radio" name="radioBtnGroup" value="containsOp" />Check if the string contains a particular substring(Case Sensitive)
    <input type="radio" name="radioBtnGroup" value="containsIgnoreCaseOp" />Check if the string contains a particular substring(Case In-sensitive)
    <input type="radio" name="radioBtnGroup" value="lengthOp" />Length of a String

    <input type="Submit" name="submitBtn" value="Click" />
    </form>
    </body>
    </html>
    [/code]

    2) File Name : functionsUsage.jsp
    [code lang=”html”]
    <%@ page contentType="text/html" %>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    <%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
    <html>
    <body>
    <c:choose>
    <c:when test="${param.radioBtnGroup==’uCaseOp’}">
    Source String : california

    UpperCase : ${fn:toUpperCase(‘california’)}
    </c:when>
    <c:when test="${param.radioBtnGroup==’lCaseOp’}">
    Source String : CALIFORNIA

    Lowercase : ${fn:toLowerCase(‘CALIFORNIA’)}
    </c:when>
    <c:when test="${param.radioBtnGroup==’subStrOp’}">
    Source String : California

    Substring : ${fn:substring(‘California’,4,7)}
    </c:when>
    <c:when test="${param.radioBtnGroup==’subStrAfterOp’}">
    Source String : California

    Substring After "Cali" : ${fn:substringAfter(‘California’,’Cali’)}
    </c:when>
    <c:when test="${param.radioBtnGroup==’subStrBeforeOp’}">
    Source String : California

    Substring Before "fornia" : ${fn:substringBefore(‘California’,’fornia’)}
    </c:when>
    <c:when test="${param.radioBtnGroup==’trimOp’}">
    Source String : California

    Trim the string " California " : ${fn:trim(‘ California ‘)}
    </c:when>
    <c:when test="${param.radioBtnGroup==’replaceOp’}">
    Source String : California

    Replace : ${fn:replace(‘California’,’a’,’A’)}
    </c:when>
    <c:when test="${param.radioBtnGroup==’splitOp’}">
    Source String : Cali;fornia

    Split Separator : ";"

    After Split an array is created with two items:

    Item at index 0 : ${fn:split(‘Cali;fornia ‘,’;’)[0]}

    Item at index 1 : ${fn:split(‘Cali;fornia ‘,’;’)[1]}
    </c:when>
    <c:when test="${param.radioBtnGroup==’joinOp’}">
    Source String : Cali;fornia

    Split Separator : ";"

    Join Separator : "|"

    Join :
    <c:set var="a1" value="${fn:split(‘Cali;fornia’, ‘;’)}" />
    <c:out value="${fn:join(a1, ‘|’)}" />
    </c:when>
    <c:when test="${param.radioBtnGroup==’escapeXml’}">
    ${fn:escapeXml(‘<city>California</city>’)}
    </c:when>
    <c:when test="${param.radioBtnGroup==’indexOf’}">
    Source String : California

    Index Of "for" : ${fn:indexOf(‘California’,’for’)}

    </c:when>
    <c:when test="${param.radioBtnGroup==’startsWithOp’}">
    Source String : California

    Starts With "Cal" : ${fn:startsWith(‘California’,’Cal’)}
    </c:when>
    <c:when test="${param.radioBtnGroup==’endsWithOp’}">
    Source String : California

    Ends With "nia" : ${fn:endsWith(‘California’,’nia’)}
    </c:when>
    <c:when test="${param.radioBtnGroup==’containsOp’}">
    Source String : California

    Contains "FOR" : ${fn:contains(‘California’,’FOR’)}
    </c:when>
    <c:when test="${param.radioBtnGroup==’containsIgnoreCaseOp’}">
    Source String : California

    Contains IgnoreCase "FOR" : ${fn:containsIgnoreCase(‘California’,’FOR’)}
    </c:when>
    <c:when test="${param.radioBtnGroup==’lengthOp’}">
    Source String : California

    Length of the string : ${fn:length(‘California’)}
    </c:when>
    <c:otherwise>
    Please make a selection to perform an operation
    </c:otherwise>
    </c:choose>

    <a href="home.jsp"><< Back</a>
    </body>
    </html>
    [/code]

    3) Output
    [code]
    Source String : Cali;fornia
    Split Separator : ";"
    Join Separator : "|"
    Join : Cali|fornia
    << Back
    [/code]

    JSP 2.0 Function : Explanation

    In this example we can see the usage of the string functions defined as part of the new JSTL 1.1 tag library.
    The functions are part of the new Function library and they needs to be prefixed with fn as we can see in the examples. This reduces lot of development effort and our jsps look a lot cleaner as we dont have to mix java code inside jsp.

    The Functions library includes the following string functions : toUpperCase, toLowerCase, substring, substringAfter, substringBefore, trim, replace, split, join, indexOf, startsWith, endsWith, contains, containsIgnoreCase and length

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

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

New Features in JSP 2.0

September 19, 2008 by Krishna Srinivasan Leave a Comment

New Features in JSP 2.0

JSP 2.0 is released with new promises. JSP 2.0 is an upgrade to JSP 1.2 with several new and interesting features. These features makes the life of web application developers and designers easier.

also read:

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

The JavaServer Pages 2.0 Specification is fully backwards compatible with version 1.2. JSP 2.0 allows the developer to write script-free code without without declarations, scriptlets and expressions.

JSP 2.0 is released with the objective of making the life of Developers easy. Here is the new features of JSP 2.0:

  • Simple Expression Language (EL)
  • JSP Fragments
  • Simple Tag Handlers
  • Easy tags creation with .tag files
  • Easy Header and Footer template using the prelude and coda includes

With JSP 2.0 web develop has become easily and it also helps easily maintaining dynamic Web pages. Despite the fact the word “Java” appears in JavaServer Pages, with JSP 2.0 the developer can develop pages without learning Java programming language. Learning and using the features of JSP 2.0 is also very easy.

JSP 2.0 Features description is given below:

Simple Expression Language(EL): Expression Language (EL), provides a way to simplify expressions in JSP. EL provides the ability to use run-time expressions outside JSP scripting elements. Scripting elements are those elements which is used to embed Java code inside the JSP file. Mostly it contains the logic of the program.

Scripting elements have three subforms:

  • Declaration: The variables and methods are declared inside declaration.
  • Scriptlets: The business logic of the program is written inside this.
  • Expressions: output will be displayed by the expression.

Expression Language can be enabled in scriptfree JSP pages:

  1. By using a page directive: We can enable EL by using
    [code lang=”xml”]
    <%@ page isScriptingEnabled="true|false" isEnabled="true|false"%>
    [/code]
  2. By using an element of the deployment descriptor:
    [code lang=”xml”]
    <jsp-config>
    <jsp-property-group>
    <url-pattern>*.jsp</url-pattern>
    <el-enabled>true</el-enabled>
    <scripting-enabled>true</scripting-enabled>
    </jsp-property-group>
    </jsp-config>
    [/code]

JSP Fragments: Jsp fragments is a new feature of JSP 2.0 which allows page author to create custom action fragments that can be invoked. The JSP fragments allows a portion of Jsp code to be encapsulated into a Java object that can be passed around and evaluated zero or more times. Methods for creating a JSP fragment:

  1. Providing the body of a :

    [code lang=”xml”]
    <% attribute name="attributeName" fragment="true">
    [/code]

  2. Providing the body of a tag invocation

Simple Tag Handlers:
Easy tags creation with .tag files: With the introduction of JSP 2.0, knowledge of Java is no longer a prerequisite to create a custom tag action. Easy Header and Footer template using the prelude and coda includes. With JSP 2.0 web development has become easy and it also helps in maintaining dynamic web pages easily. To learn JSP 2.0 there is no need to learn java.

Filed Under: Java EE Tagged With: JSP 2.0

Expression Language in JSP 2.0

August 20, 2007 by Krishna Srinivasan Leave a Comment

1)Introduction

Expression Language was first introduced in JSTL 1.0 (JSP Standard Tag Library ). Before the introduction of JSTL, scriptlets were used to manipulate application data.JSTL introduced the concept of an expression language (EL) which simplified the page development by providing standerd tag libraries. These tag libraries provide support for common, structural tasks, such as: iteration and conditionals, processing XML documents, internationalization and database access using the Structured Query Language (SQL).

also read:

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

The Expression Language introduced in JSTL 1.0 is now incorporated in JavaServer Pages specification(JSP 2.0). This articie gives some idea about what is Expression Language and how to simplify the maintenance for JSP applications by avoiding scripting elements.

2)Expression Language

The pattern that identifies Expression Language is ${ }. To deactivate the evaluation of EL expressions, we specify the isELIgnored
attribute of the page directive:
[code lang=”html”]
<%@ page isELIgnored ="true|false" %>
[/code]

The valid values of this attribute are true and false. If it is true, EL expressions are ignored when they appear in static text or tag attributes. If it is false, EL expressions are evaluated by the container.

Operators which can be used in EL expression
[code]Operator    Description
    .         Access a bean property or Map entry.
    []         Access an array or List element.
    ()         Grouping of a subexpression for evaluation order.
    ? :         Conditional test: condition ? ifTrue : ifFalse.
    +         Addition.
    –         Subtraction.
    *         Multiplication.
    /or div     Division.
    % or mod M    Modulo (remainder).
    == or eq     equality.
    != or ne     inequality.
    < or lt     less than.
    > or gt     greater than.
    <= or le     less than or equal.
    >= or ge     greater than or equal.
    && or and     logical AND.
    || or or     logical OR.
    ! or not     Unary Boolean complement.
    empty         Test for null,empty String,array or Collection.
    func(args)     A function call.
[/code]

  • Arithmetic operators.

    [code] Before JSP2.0/JSTL
    <%! int k = 0; %> <% k = 10 + 20; out.println("value of k is.."+k); %>
    Using JSP2.0/JSTL (without using scriptlet)
    value of k is ${10 + 20} [/code]
    Few more examples on arthmetic operations.
    [code] EL Expression Result
    ${10.2 + 20.3} O/P: 30.5
    ${-40 – 20} O/P: -60
    ${20 * 2} O/P: 40
    ${3/4} O/P: 0.75
    ${3 div 4} O/P: 0.75
    ${10/0} O/P: Infinity
    ${50%8} O/P: 2
    ${50 mod 8} O/P: 2
    ${(10==20) ? "true" : "false"} O/P: false [/code]

  • comparison operators.

    [code] Numeric EL Expression Result
    ${10 (4/2)} false
    ${1 gt (4/2)} false
    ${4.0 >= 3} true
    ${4.0 ge 3} true
    ${40 <= 30} false
    ${40 le 30} false
    ${10 == 10} true
    ${100 eq 100} true
    ${(5*20) != 100} false
    ${(5*20) ne 100} false

    Alphabetic EL Expression Result
    ${‘a’ 3} true [/code]

  • EL implicit objects

    [code] Identifier Description
    pageContext PageContext instance
    pageScope Map-associates name and values of page-scoped attributes
    requestScope Map-associates name and values of request-scoped attributes
    sessionScope Map-associates name and values of session-scoped attributes
    applicationScope Map-associates name and values of application-scoped attributes
    parametersparam Map-stores the primary values of the request parameters by name
    paramValues Map-stores all values of the request parameters as String arrays
    header Map-stores the primary values of the request headers by name
    headerValues Map-stores all values of the request headers as String arrays
    cookie Map-stores the cookies accompanying the request by name
    initParam Map-stores the context initialization params of the appln by nam[/code]

  • Note:EL impilcit objects are not as same as the implicit objects available for JSP scripting except for pageContext.JSP and EL implicit objects have only one object in common (pageContext),and pageContext has properties for accessing all of the other eight JSP implicit objects.The first four maps represent the various attribute scopes which can be used to look up identifiers in specific scopes. The next four maps are for fetching the values of request parameters and headers.The cookie implicit object provides access to the cookies set by a request and the final EL implicit object, initParam, is a map storing the names and values of any context initialization parameters associated with the Web application.Lets look at few examples on how to use implicit objects.
    [code] First.jsp
    First Name: <input type=’text’ name=’Name’/>
    Last Name: <input type=’text’ name=’Address’/>
    <input type=’submit’ value=’Submit’/>

    Second.jsp
    Name is : ${param.Name}
    Address is : ${param.Address}
    Similarly

    Header Key : ${header.key}
    Header Value : ${header.value} [/code]
    Here in First.jsp we are entering the details of Name and Address, when we click on submit button the flow goes to Second.jsp.
    We can retrieve the values by using ${param.xxxx}

  • Scope Examples:

    [code] Accessing a page-scoped attribute named as firstName: ${pageScope.firstName} Accessing a request-scoped attribute named as firstName: ${requestScope.firstName} Accessing a session-scoped attribute named as ‘lastName’ (null if not found): ${sessionScope.lastName} [/code]

  • Page Context Examples
    [code] ${pageContext.request.protocol} ${pageContext.response.locale} ${pageContext.session.id} ${pageContext.servletContext} [/code]
    Above we are accessing request, response, session, and application properties, using the pageContext implicit object.
  • Cookie Example:

    [code lang=”java”] addCookies.java
    Cookie c=new Cookie("name","test");
    res.addCookie(c);

    Test.jsp
    Name : ${cookie["name"]}
    Value : ${cookie["name"].value} [/code]
    Here in addCookies.java we are creating a new Cookie,These values can be retrieved in jsp by using ${cookie.xxxx}.

  • Init Parameter Example
    [code lang=”xml”] XML:
    <context-param>
    <param-name>email</param-name>
    <param-value>Hello@xyz.com</param-value>
    </context-param>

    Test.jsp email is: ${initParam.email} [/code]

  • Functions
    Defining Functions:The JSP expression language allows you to define a function that can be invoked in an expression. Functions are defined using the same mechanisms as custom tags.
    [code lang=”java”] public class MyFunctions { public static String toCaps( String text ) { return text.toUpperCase(); } } [/code]
    Using Functions:
    [code lang=”xml”] XML: <uri>testFunctionsURI</uri>
    <function> <name>toCaps</name>
    <function-class>mypkg.MyFunctions</function-class>
    <function-signature>String toCaps( java.lang.String)</function-signature>
    </function>

    JSP: <%@ taglib prefix="myFunctionTest" uri="testFunctionsURI"%> ${myFunctionTest.toCaps("testingCaps")} [/code]

Conclusion

By using this expression language, page authors could drastically reduce the amount of scripting in their pages, resulting in greater productivity, easier maintenance, and a flatter learning curve in terms of page development. Over the years, the expression language has evolved to include more advanced functionality, while still maintaining its simplicity.

Filed Under: Java EE Tagged With: 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