JSP Expression tag evaluates the expression placed in it, converts the result into String and send the result back to the client through response object. Simply put, it writes the result to the client(browser).
Syntax of expression tag in JSP:
<%= expression %>
JSP Expression tag Example 1: Expression of values
Here we are simply passing the expression of values inside expression tag. The numbers along with mathematical operators such as +, -, * is placed inside an expression tag. The calculation of this expression is done and the result is displayed.
<html> <head> <title>JSP expression tag example1</title> </head> <body> <%= 2+4*5 %> </body> </html>
Output:
JSP Expression tag Example 2: Expression of variables
In this example we have initialized three variables and passed the expression of variables in the expression tag for result evaluation.
<html> <head> <title>JSP expression tag example2</title> </head> <body> <% int a=10; int b=20; int c=30; %> <%= a+b+c %> </body> </html>
Output:
Expression tag Example 3: String and implicit object output
In this example we have set an attribute using application implicit object and then displaying the value of that attribute and a simple string on another JSP page using expression tag.
index.jsp
<html> <head> <title> JSP expression tag example3 </title> </head> <body> <% application.setAttribute("MyName", "Chaitanya"); %> <a href="display.jsp">Click here for display</a> </body> </html>
display.jsp
<html> <head> <title>Display Page</title> </head> <body> <%="This is a String" %><br> <%= application.getAttribute("MyName") %> </body> </html>
Output:
Expression tag Example 4: using method inside tag to display current date/time
The getTime()
method of Calendar class returns date and time together in a form like this: Mon Feb 24 16:45:47 UTC 2022
. We are using this method inside expression tag to display current date and time. You can also refer this guide to find current date time in java.
<html>
<body>
Current Date and Time: <%= java.util.Calendar.getInstance().getTime() %>
</body>
</html>
Leave a Reply