JSP Expression Tag

This is the third article of JSP Tutorial. In this article, we use JSP expression tag to compute some type of expression and the result of that is included in the HTML page that's returned to the browser.
Expression tag evaluates the expression placed in it, converts the result into String and send the result back to the client through response implicit object.

The Syntax of JSP Expression Tag

<%= expression %>

JSP Expression Tag Examples

Convert String to Upper Case Example

Here is sample snippet which 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 tag to get values from implicit objects. For example:
<%=request.getAttribute("projectName")%>
<%= application.getAttribute("MyName") %>
We also use JSP expression tag to display a value of Strings or Objects. For example, consider we have 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 Task class:
<%= task.getName() %>
<%= task.getId() %>
In the next article, we will learn JSP scriptlet tag with examples.

Comments