Declaration in JSP is way to define global java variable and method. This java variable method in declaration can be access normally. Normally declaration does not produce any output, and access of this code is also limited. The declaration code does not reside inside service method of JSP. Declaration we use method to convert null convert of string in JSP.
Example of Declaration in JSP
declaration.jsp
<%@ page language="java" errorPage="" %>
<%!
public String nullconv(String str)
{
if(str==null)
str="";
else if(str.equals("null"))
str="";
else if((str.trim()).equals(""))
str="";
else if(str.equals(null))
str="";
else
str=str.trim();
return str;
}
%>
<%
String myVariable=null;
%>
<html>
<head>
<title>Declaration in JSP</title>
</head>
<body>
This is null variable : <%=nullconv(myVariable)%>
</body>
</html>
We can see declaration code is not used to produce any direct output; it is used for reusable code.
Instead of <%! Declaration code%> can use
<jsp:declaration>
public String nullconv(String str)
{
if(str==null)
str="";
else if(str.equals("null"))
str="";
else if((str.trim()).equals(""))
str="";
else if(str.equals(null))
str="";
else
str=str.trim();
return str;
}
</jsp:declaration>
|