July 30, 2004
The last couple of days, I've managed to convert the MyUsers sample app from JSP
to Velocity, and also to FreeMarker. Since this app uses SiteMesh, this was fairly
easy thanks to its Velocity
Decorator and FreeMarker
Decorator support. Of course, Spring supports both technologies as well -
ref: Spring+Velocity
and Spring+FreeMarker.
The real slick part of Spring's integration is that I didn't really need to change
any code to support either templating engine. All I had to change was the XML
in action-servlet.xml! Very cool!
In the process, I found out that FreeMarker is a bit more strict about the
whole MVC thing. With Velocity and JSP, I can remove session variables using
$request.session.removeAttribute("varName") and <c:remove var="varName"/>.
I agree that doing this isn't very MVC-ish, but I was surprised to find that
FreeMarker doesn't even allow this. It allows access to "request attributes",
but not the "request" object itself. Of course, this makes it a pain
to get the requested URL (request.getRequestURL()) as well.
Now I should explain why I have session variables that I'm removing in the
view. The reason is because I save success messages in the session to survive
redirects. It just seemed easier (at the time) to remove this variable after
I rendered it in the view. Spring doesn't have any out-of-the-box support for
success messages (like Struts ActionMessages), so it seems like a reasonable
solution. To workaround the the FreeMarker limitation, I decided to add a MessageFilter
that grabs messages from the session and puts them into the request. I also
added "requestURL" as a request attribute - solving both of the issues
I found with FreeMarker, and making my views more MVC-ish.
The one thing I really like about FreeMarker over Velocity is the ability to
use JSP Tags in your template. To me, this is very powerful since displaytag
and struts menu
are my primary reasons for sticking with JSP. After implementing JSP 2.0, Velocity
and FreeMarker - it's funny to see how the variable rendering syntax - ${...}
- is very similar in all three. Even after implementing Velocity and FreeMarker,
I think I'll stick with JSP (2.0) - it just seems a lot more powerful. No limitations
if you will.
About the author
Matt Raible
matt@raibledesigns.com
Blog: http://www.raibledesigns.com/page/rd
Matt currently resides in Denver where he consults as a J2EE Developer for Raible Designs and is always striving to find the easiest solutions for web applications. His current favorite technologies can be found within his open source AppFuse application. He is actively involved in the Open Source community and loves Java.
|