JSP Expression Tag

The JSP expression tag allows developers to insert Java expressions directly into the HTML content of a JSP page. The expression is evaluated, converted to a string, and inserted into the output stream at the location of the expression tag. This tag is useful for displaying dynamic content without needing to write additional Java code in scriptlets.

The Syntax of JSP Expression Tag

<%= expression %>

How It Works 

When the JSP page is processed, the expression within the <%= ... %> tag is evaluated, and the result is converted to a string and included in the HTML response sent to the client. This makes it easy to include dynamic data in the HTML output.

JSP Expression Tag Examples

Convert String to Upper Case Example

Here is a sample snippet that basically converts this string to all caps or to all upper case.
<html>
   <body>
        Converting a string to uppercase:
        <%=new String("Hello World").toUpperCase()%>
   </body>
</html>
Output:
Converting a string to uppercase: HELLO WORLD

Mathematical Expressions Example

<html>
    <body>
       25 multiplied by 4 equals 
       <%=25 * 4%>
   </body>
</html>
Output:
25 multiplied by 4 equals 100

Boolean Expressions Example

<html>
    <body>
        Is 75 less than 69?
        <%=75 < 69%>
    </body>
</html>
Output:
Is 75 less than 69? false

Complete Example with Output

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

     Converting a string to uppercase:
     <%=new String("Hello World").toUpperCase()%>
     <br />
     <br />
     Port of Server :
     <%= request.getLocalPort() %> 
     <br />
     <br />
     Context path :
     <%= application.getContextPath() %>
     <br />
     <br /> 
     25 multiplied by 4 equals
     <%=25 * 4%>
     <br />
     <br /> Is 75 less than 69?
     <%=75 < 69%>

</body>
</html>
Let's invoke this JSP page from a Web browser. You see the table on a browser:

Real-time Examples

In real-time projects, we use JSP expression tags to get values from implicit objects. For example:
<%=request.getAttribute("projectName")%>
<%= application.getAttribute("MyName") %>
We also use the JSP expression tag to display the value of Strings or Objects. For example, consider we have a Task class with id and name as fields:
public class Task {
     private int id;
     private String name;
     // getter and setters
Now, we can display the value of each field of the Task class:
<%= task.getName() %>
<%= task.getId() %>
In the next article, we will learn JSP scriptlet tag with examples.

Comments