Abbey Workshop

JSP: JSP Expressions

JSP expressions are a quick way to insert data into an HTML page. In Math, an expression is a way to represent a single value different ways. I could represent the number 6 with the expressions, (3+3) or (2*3). In JSP, the idea is the same. But instead of coming up with a mathimatical value, the result of an expression is converted to a string it can be displayed as part of an HTML Page.

An expression is enclosed in these tages: <%= %> For example, To add 2+2 and display the result, you would enter the following:

<%= 2+2 %>

Here is an example JSP page with a few expressions.

Get source for: jspexpress.jsp

   3:<title>JSP Expression Page</title>
   6:<h2>JSP Expression Page</h2>
   7:<p>Ex1: What is 3+3? <%= 3+3 %><br>
   8:Ex2: What is 2*3? <%= 2*3 %><br>
   9:Ex3: Can I combine them?  <%= (2*3) + (3+3) %><br>
  10:Ex4: Add a string? <%= "Here is some text " + (2*3) + (3+3) %><br>
  11:Ex5: Add a string? <%= "Here is some text " + ((2*3) + (3+3)) %><br>
  12:<%! String aString = "What is two times 3? "; %>
  13:<%! int x = 2; %>
  14:<%! int y = 3; %>
  15:Ex6: Let's use variables: <%= aString + (x*y) %>

Notice that when just numbers are added, the entire expression is converted to a single integer and displayed (Ex1 - Ex3). However, if a string is added, Java rules of precedence take effect. Thus, Ex3 and Ex4 produce different results unless we define things better like Ex5. Finally, Ex6 uses variables to display the values, which would be the most common use of an expression.

Important Note: Do NOT end expressions with a semi-colon.