Monday, March 15, 2010

EL functions in JSP

EL Functions:
Very simple used to invoke any functions with names.......

For Ex:

create a class as below:com.fun.Message

package com.fun;
/*
* A class Which contains the user defined funcion sayHello
*/
public class Message{

public static String sayHello(){

return "hello!!";
}
}

Keep this .class under /WEB-INF/classes/com/fun/Message.class


Then we have to create TLD file which describes your functions :
myfucntions.tld:

<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>1.1</jsp-version>

<function>
<name>hello</name>
<function-class>com.fun.Message</function-class>
<function-signature>java.lang.String sayHello()</function-signature>
</function>

<function>
<name>rand</name>
<function-class>java.lang.Math</function-class>
<function-signature>long random()</function-signature>
</function>

<function>
<name>absolute</name>
<function-class>java.lang.Math</function-class>
<function-signature>int abs(int)</function-signature>
</function>

</taglib>

You can observer this TLD is describing some predefined functions of java.lang.Math class also.

Save this file as " myfunctions.tld" keep this under /WEB-INF folder of your application.

"name" tag in function is necessary with that name only user is going to call the functions.

Then at last create your jsp:

<%@page isELIgnored="false" %>
<%@taglib uri="/WEB-INF/myfunctions.tld" prefix="f" %>

${f:hello()}
${f:rand()}
${f:abso lute(10)}


Rocking
Shyamala

Tuesday, March 9, 2010

Difference between @include & jsp:include

To get to know the difference between these two

<%@include file="" %> is a directive

Action tag:

<jsp:include page="{relativeURL | <%= expression %>}" flush="true" />
or
<jsp:include page="{relativeURL | <%= expression %>}" flush="true" >

<jsp:param name="parameterName"

value="{parameterValue | <%= expression %>}" />

</jsp:include>



one.jsp
=========

<%@page isELIgnored="false"%>

<jsp:declaration>int cnt=0;</jsp:declaration>
<jsp:expression>"Shyamala"+cnt++</jsp:expression>
<jsp:include page="two.jsp"/>

two.jsp
==========
I am just included

now go to work directory of tomcat and check out there will be two seperate servlets created

and even u can observe one line in one_jsp.java file
org.apache.jasper.runtime.JspRuntimeLibrary.include(request, response, "two.jsp", out, false);

which specifies the page is included at run time

just change your one.jsp file as following

one.jsp

<%@page isELIgnored="false"%>


<jsp:declaration>int cnt=0;</jsp:declaration>
<jsp:expression>"Shyamala"+cnt++</jsp:expression>
<%@ include file="two.jsp"%>

you will not be created with two different java files in work directory the two.jsp contents also will be included in the same one_jsp.java file.

That means it is done at the time of compilation!!


Rocking !!
Shyamala