Sunday, December 02, 2012

Expression Language quickie!

Okay I'll make this post really quick!

Let's head back to our project that we've been working on and open up index.jsp.

Change your code to look like this...

<%@ 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">
<jsp:useBean id="mybean" type="com.blogger.beans.HelloBean" class="com.blogger.beans.HelloBean" scope="page"></jsp:useBean>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
 <p>
  ${mybean.currentDate}<br />
  ${mybean.randomNumber}<br />
  ${mybean.randomNumber+5}<br />
  ${mybean.someMessage}
 </p>
</body>
</html>

Here what I've done is replace our jsp:getProperty code with what is known as expression language, or better known as EL.

The nice thing is that Tomcat 7 supports EL out of the box.  Now I know that you are tempted to think that EL is just a simple replacement for getters, but as you can see in my code I've done some addition.  You can do mathematical operations in EL to things that make sense.  That can cast to a numeric automatically.  So that basically limits you to floats, ints, doubles, and what not.

However, the cool thing about EL is that you can also do logic within EL.  That's right you can compare things in equality, or less than/great than, or other types of logical testing.  In addition, you can call methods and access arrays in EL.  EL is a pretty important thing in the world of JSP 2.

So here's what we've done so far:

We started at JSP 1.0 with the <% %> tags, which eventually we will drop completely to come fully into JSP 2.
We started using beans as opposed to scriptlets, which brings us deeper into JSP 2.
We are now using EL which will help us understand some new concepts in JSP 2.

As you can see, brick by brick we are tearing down JSP 1.0 and moving to the world of JSP 2.  The next thing I want to do it show you how to use servlets, JSP 2, EL, and beans together to make a more interactive web application.

Cheers!

No comments: