JSP | Expression tag

Expression tag is one of the scripting elements in JSP. Expression Tag in JSP is used for writing your content on the client-side. We can use this tag for displaying information on the client’s browser. The JSP Expression tag transforms the code into an expression statement that converts into a value in the form of a string object and inserts into the implicit output object. 

Syntax: JSP tag 

html




<%= expression %>


Difference between Scriptlet Tag and Expression Tag

  • In the Scriptlet tag, it’s Evaluated a Java expression. Does not display any result in the HTML produced. Variables are declared to have only local scope, so cannot be accessed from elsewhere in the .jsp. but in Expression Tag it’s Evaluates a Java expression. Inserts the result (as a string) into the HTML in the .js
  • We don’t need to write out.println in Expression tag for printing anything because these are converted into out.print() statement and insert it into the _jspService(-, -) of the servlet class by the container.

Example 

html




<html
<body
<%= w3wiki %>  <!-- Expression tag -->
</body
</html>


Output Using expression tag: 

html




<%@ page language="java" contentType="text/html;
charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
 "http://www.w3.org/TR/html4/loose.dtd">
<html>
 
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>w3wiki</title>
</head>
 
<body>
<% out.println("Hello Beginner "); %> <!-- Sriptlet Tag-->
<% int n1=10; int n2=30; %><!-- Sriptlet Tag-->
<% out.println("<br>sum of n1 and n2 is "); %> <!-- Sriptlet Tag-->
<%= n1+n2 %> <!-- Expression tag -->
</body>
 
</html>


Output

Let us take one more example.

Here we are creating an HTML file to take the username from user.save this file as index.html

HTML




<!--index.html -->
<!-- Example of JSP code which prints the Username -->
<html>
<body>
<form action="Beginner.jsp">
<!-- move the control to Beginner.jsp when Submit button is click -->
 
Enter Username:
<input type="text" name="username">
<input type="submit" value="Submit"><br/>
 
</form>
</body>
</html>


Output:

 

Here we are creating A jsp file names as Beginner.jsp

HTML




<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
 
<head>
<meta http-equiv="Content-Type" content="text/html;
charset=UTF-8">
<title>Insert title here</title>
</head>
 
<body>
<%= String name=request.getParameter("username");
out.print("Hello "+name);
%>
</body>
 
</html>


Output: 

 



Contact Us