Monday, October 19, 2009

JSP and Java EE

If you are looking for a good intro into the semantics of JSP then may I suggest here.

So what are Java Server Pages (JSP)? If you have done any work with PHP then you'll be right at home with JSP.

JSP is a method of creating Servlets with specially formatted HTML pages. You add in Java code scripts inside tags delimited by <% and %> (properly called: scriptlets I know, I find myself calling them Java Script sometimes too, but that's a whole different thing)

Expressions, one line shots of Java code that return a String, are encapsulated in <%= %>

Here is a quick sample of the two intermixed:

int j = 0;
while (j != 12 {
<div style="border:1px dotted #338833">
This is line #<%= j %>
</div><br />
<% } %>

If that brings up memories of PHP, you wouldn't be the first. JSP also adds Directives <%@ %> and Declarations <%! %>. The latter being important because this is how you add methods to the servlet that will be created from your JSP.

The servlet that is created for also has some special data members added to help you out. The tutorial covers how to use these quite well. It is important that you use these members because most of the time you're JSP is assumed to be thread safe (try not to break that assumption.)

The really cool thing is JSP tags! Unlike PHP (but like ColdFusion, if you've ever used it) you have access to a tag library. These tags quickly provide functions that you're most likely to use (like include another page.) You can also write your own library of JSP tags to encapsulate logic in your pages. This effectively allows you to separate logic from presentation (the ultimate goal in web application.)

But this brings us bark to the idea of MVC vs. Three Tier. JSP acts as our presentation in Java EE, however JSP brings us almost too close to Three-Tier design. Things that you want to go from page to page (shopping cart contents come to mind) have to either be pushed down to the database or passed through cookies/URL. This can make a lot of developers feel uneasy because it is a lot of work for such a small gain (easy presentation of Java objects.) If only there was a way to keep the ease of MVC design, have the ease of JSP presentation, and still have the flexibility of Three-Tier design.

Lucky for you, there is. There has been a lot of Java community members banging their heads over this, and over the years it has yielded about a dozen or so very mature frameworks. All coming together in the Java standard call Java Server Faces (JSF).

As you can see JSP offers a very powerful method of building presentations of Java objects. Many companies use JSP as the display end of their products. Later I'll cover JSF and show you how to bring the ease of MVC design into a Multi-Tier development platform.

No comments: