|
||||||||||||||||||||||||||||||
Struts 1.1by Thomas PaulIntroductionLast year I wrote an article about Struts 1.0. With the release of Struts 1.1 beta, it is time for an update to that article. First we will look at how to change last year's simple logon application to run correctly in Struts 1.1. Then we will look at one of the interesting new additions to Struts, the validator framework, and show how it can simplify our application.
Installing Struts 1.1The installation of Struts has not changed much except that there are more files to install. The struts.jar file has had many of the common classes pulled out and placed into separate jar files. There are now thirteen jar files to place in your applications lib directory. Also, the TLD files have been changed a little bit. The struts.tld file has been eliminated and its functionality moved into other TLD files. There are two additional TLD files to add to your WEB-INF directory. You need to update the web.xml file for the changes to the tag library descriptors but no other changes are required.
Upgrading Our ApplicationOur Struts 1.0 application won't work as it was written. At the very minimum, we need to make changes to our
two JSP files because we no longer have the struts.tld file. The change is simple. We first remove the taglb directive
that contains struts.tld and then we change struts:message to bean:message
everywhere it appears.
As you can see, the only difference is that execute() is declared to throw Exception rather than IOException and ServletException. The second change was to the Action.ERROR_KEY constant. It was decided to move the constants into their own class called Globals. So the original statement needs to be changed to Globals.ERROR_KEY. Since Globals is in the org.apache.struts package, we need to add an import statement for that package. And that is it. Recompile your code and it should work exactly the same as the original version. The listing of the revised LoginAction class is here:
The Validator FrameworkMost ActionForm classes (and our example one is no exception) are fairly simple, containing little more than
field level validations. In our example, we are simply testing to insure that the user actually filled in the fields.
Imagine a large application with dozens of forms and you get the idea that you can wind up maintaining a large
number of extremely simple and similar classes.
Note that the plug-in tag is new in Struts 1.1. As such, it's not described in the Struts 1.0 Configuration Document Type Definition (DTD). So, you also need to update the DOCTYPE tag at the top of the struts-config.xml file to use the Struts 1.1 Configuration DTD.
Notice that there are two validation files listed. The first, validator-rules.xml was included as part of the Struts installation. The second, validation.xml, will be created by you. This file contains the rules that link fields in the form with the rules in the validator-rules.xml file. The validator framework comes with a basic set of validations. If these are insufficient for your needs, you can write your own validations and either add them to the validator-rules.xml file or put them in a separate file and add the file to the <plug-in> tag. The basic validations included in the validation framework are:
These commands tell the validation framework that user id and password are both required fields and that the user id must be at least 4 characters in length. Let's look at the main pieces of the validation.xml.
<form name="login"> - identifies the form-bean that this validation is associated with. Some of the validators provide JavaScript validation that can be included in your JSP page if you wish. If you use JavaScript validation, the form will be validated in the browser and if it fails validation an alert box will appear and the form will not be sent to the browser. To invoke JavaScript validation first add the html:javascript tag to the page specifying the form to be validated. Then add an onsubmit event handler to the html:form tag and you are finished. The finished LoginView.jsp looks like this with the changes highlighted:
We need to add two new entries to our MessageResource.properties file for the error messages generated by the automatic validation.
There is only one change left to make. We need to update the struts-config.xml to change the form to use the DynaValidatorForm instead of the custom form we used in Struts 1.0. Here is the change we need to make:
Each of the fields on the form must be described by giving its name and type. We are now finished. The ActionForm class can be deleted and our application will run. Any changes to the validation for our form can be done by making changes to our validation.xml file. ConclusionStruts 1.1 is still in beta and the documentation is far from complete. Information on running the validators included with Struts is difficult to find. A lot of the code you work with will be trial and error to get it to run correctly. If you need help getting a feature of Struts to work there are quite a few resources listed on the Struts web site, there is the Struts mailing list, and of course the JavaRanch Framework forum. When will 1.1 become a release? As with all Apache projects it is difficult to say. This version, beta 3, has been very stable in my testing and provides many improved features to make Struts easier to use. There are a few known issues and once those are fixed we can look forward to a release candidate. Return to Top |
||||||||||||||||||||||||||||||
Small and Simple Web Applications - the Friki Way (Part 1)Frank Carver, February 2003AbstractThis article is the first of a series which laments the bloated and unmaintainable state of so many J2EE web applications and looks at ways to keep web applications small, simple and flexible. The series uses the author's Friki software as a case study, and discusses ways to design and build a powerful, flexible and usable web application in less space than a typical gif image. This article introduces some problems of J2EE applications. It also gives some requirements for a wiki-like application. First steps are taken in the design of the application, with a focus on deferring storage decisions and deciding on a technology for dynamically producing web pages. IntroductionJava is extremely popular for developing server-based web applications. Lots of big name web sites use Java technology to drive their customer interactions. Any Java developers' web site is full of material about J2EE, JSP, EJB, JMS, JNDI, JDBC, XML, SOAP and many more. It's an alphabet soup of abbreviations and jargon. New technologies are added to Java faster than we can keep up. Making sense of it all and trying to use the best of each bit could drive anyone crazy. Sure, all this stuff is powerful, but sometimes it pays to stop, calm down, and think for a while.
The above is a quote from Shaker Built: The Form and Function of Shaker Architecture by Paul Rocheleau and June Sprigg. You can read a little more about this quote, and this book (appropriately enough) on Ward Cunningham's Wiki. I have worked on many server-side Java applications in my years as a consultant, and vanishingly few of them exhibited any of the virtues of that simple Shaker quote. I've seen applications with a maze of twisty JSP pages, all (almost) alike. I've seen business data squeezed in and out of XML just because it seemed "cool". I've seen software which only works on old and unsupported versions of application servers and databases. I've seen software where none of the developers dared touch the existing code for fear it might break something. I've seen software where changing a text label on a web page required a database rebuild. I've seen a project running on six high-spec Sun workstations and needing a team of over 20 developers, testers and managers to maintain it switched off and replaced by a spreadsheet!
I don't want to build unmaintainable monsters like this, and I hope you don't either. But how can we learn to do things right? Surely there are some well-thought-out applications to study? Sad as it may be, there are very few, particularly if we are interested in Java web applications. In this article I will use one of my own applications (Friki) as a case study. I don't claim that it is perfect, and I actively encourage anyone reading this to look for ways to simplify things. I also encourage you all to look for other examples of web applications which do a useful job in a simple, small and flexible way. About FrikiFriki (pronounced "freaky") is "Frank's Wiki". A "Wiki" is a web site, where any user can create new pages, edit existing pages, create links, and search the site whenever they want to. This may seem weird, but it can be an extremely powerful and flexible way to take notes, collaborate and work on the web. All you need to view and edit pages is the browser you are using to read this. Every page on a Wiki has some sort of "edit button", which shows the text of the page in an edit box, and allows you to change it and re-save the new version. Once you have created or edited some pages, most Wikis have a built-in "search" facility to find them. Making links and creating pages is as easy as typing the name of the (new or old) page while editing. You don't need to know HTML, Java, XML or any of the other buzzwords to use a Wiki. In most cases you can just type paragraphs of text, and the software will do its best to lay it out for you. Friki is a pure Java web application which can be installed as simply as dropping "friki.war" into any modern servlet container or Java application server. Strictly that means anything which implements version 2.3 or later of the Java Servlet API. Friki is small, fast and flexible. The complete web application archive (war) file is just 66k bytes, and needs nothing apart from a servlet container to run. Pre compiled web applications, source code and other documentation for Friki is available from http://www.efsol.com/. The original Wiki implementation by Ward Cunningham is in Perl and hosted at http://c2.com/cgi/wiki. For more information I highly recommend the definitive book: The Wiki Way - Quick Collaboration on the Web by Bo Leuf and Ward Cunningham. ISBN 0-201-71499-X. Let's Make OneTo show the design techniques which can help us keep things small, simple and flexibile, let's work through the process of designing and building a Wiki (which we'll call "Friki"). The most important part of a Wiki is the collection of pages. Pages are where people put their information, notes or opinions. Pages and their content are what makes a Wiki come alive! Such a page collection must support a few basic operations: The system needs to get the content of a named page to display it, save some new content to a named page, create a new page, and search all the pages for some supplied text or pattern. Although not strictly necessary, most Wikis also support a "does this page exist?" operation, so that an indicator can be shown to users if a linked page has no text yet. If you are like me, your mind is already fizzing with ideas how to implement such a page store -- maybe a JDBC database, or perhaps a JNDI repository, even a high-performance distributed caching package you have recently read about.... Stop! That is the way to a bloated, multi-megabyte, undeployable, unmaintainable nightmare. Instead, I suggest we defer the implementation details of how to store pages. Instead, we'll create an interface (a special type of Java class), with the operations we need, and use that. When we actually need to store some pages, we can use the simplest implementation we can get away with, as long as it implements this interface. Later, if we ever do need more performance, scalability or distributability, we just need to code a slightly more complex implementation of the same simple interface. Eventually, this approach might let us automatically build several specific versions of the software for different situations, each containing only what is actually needed and used. package com.efsol.friki; import java.util.Iterator; public interface PageRepository { public Page get(String name); public void put(String name, Page page); public boolean contains(String name); public Iterator matchingPageNames(String pattern); } There are a few things to note about this interface:
The next most important part of a Wiki is the user interface. We have already decided that we will be using a web interface, so it's pretty obvious that we need at least some way of producing HTML to send to a browser. What's not obvious is the best way to do this. Conventional Java "wisdom" would indicate that this is a natural fit for JSP. Indeed, I did try an attempt at this using JSP, but found far too many problems. The main problems with JSP stem from the way that pages are compiled by the server after deployment (the rest of the code is compiled much earlier on the development machine). To run even the simplest common-sense validity check on a JSP can often involve building a war file, transferring the war file to the server machine, deleting an old directory structure, restarting the server, waiting for the server to expand the war file, using a browser to navigate to the page being tested (pausing for all intermediate pages to be compiled and loaded as we go) and eventually attempting to run the page. Only to see it fail with a simple syntax error in an embedded script. Yuck! Testing JSPs is hard and slow. Debugging JSPs is hard and slow. Hard to test and debug means hard to change and hard to keep simple. If we are going to use JSP, we need to get all that code out of the pages and into real Java which can be compiled and tested before it is deployed. In an attempt to solve this problem, the J2EE jargon machine provides "custom tag libraries", or "taglibs". Taglibs are a way of formalizing JSP scripts and referring to them using XML syntax in the JSP pages. For each script you would have put in the page, you create a class which implements an interface or extends a supplied base class, then make a method in your new class containing what you would have put in the script, then describe your new class in 10-20 lines of XML or so in a "TLD" file, put the "TLD" file in the right place, then make sure the application "web.xml" configuration refers to the TLD file. Does that sound easy, simple, or error-free? It isn't. The latest enhancement added to JSP is JSTL, a "standard" tag library which is provided by the container, and you just need to link in to your "web.xml". Using JSTL can simplify the use of tags a bit; sometimes you can use the provided tags instead of writing your own. Taglibs can definitely help reduce some sorts of JSP problems. But maybe if you didn't use JSP, you wouldn't have these problems in the first place! So, JSP seems problematic. But what other implementation choices are there? JSP is usually contrasted against a beginners' approach to server-side code: embedding random fragments of HTML all through some huge servlet. In this case, the comparisons are right, even JSP is better than that! Imagine how slow and cumbersome things would be if you had to edit, recompile and redeploy the whole application every time you made a tiny change to the HTML. Happily, there is another alternative. One that seems strangely absent from the J2EE examples. It's called "templates", and is actually very simple. In essence, a template is just a file with some "tokens" in it. Before the file is shown to the user, the "tokens" are replaced with real values. No compilation, no messing about. For maximum flexibility, I like to allow web pages to be designed, produced and viewed using whatever tool the designer is most happy with. That may be Dreamweaver, it may be Notepad or Emacs. For this to work, we must be able to use "tokens" which don't get in the way of the text of the page. That means no "pseudo-html" (as used by JSP, Zope and FreeMarker). I reckon there aren't many "~" characters in most web pages, so let's use that as a way to indicate our tokens, at least for the moment. In the case of Friki, all we really need is one token for the page content and one for the page title. To keep things simple, we'll use ~title~ for the page title, and ~content~ for the content. A very simple example web page using this format might look like: <html><head><title>Friki: ~title~</title><head> <body> <h2>~title~</h2> ~content~ <hr width='100%'> <a href='edit?~title~'>edit this page</a> </body> </html> I hope you can see just how easy that is. You can create and edit such HTML with any tool which can work with basic web pages. No fancy support for weird formats needed. How are We Doing?Well, we haven't made a Wiki yet! So far we have an interface which defines the API for a page repository, and an example HTML page with tokens for viewing page contents. This may not seem like much, but if we were working in a team, we'd already be able to start working three times as fast. One person could make the page repository, another could design some web pages, and another could carry on thinking about servlets and template processing and stuff. This is important, we've done just enough design to split off some achievable tasks and get productive straight away. Next session we'll go into more details about how to make our own very lightweight template "engine" to expand these templates into web pages, and how to get some page content to put in them. In the meanwhile, to see what you can do with "full fat" templating software, you might enjoy looking at WebMacro and Velocity. Remember :- don't just take their word for it; it's your job to keep software small, simple and flexible. Return to Top |
||||||||||||||||||||||||||||||
It's where you come to learn Java, and just like the cattle drivers of the old west, you're expected to pull your weight along the way. The Cattle Drive forum is where the drivers get together to complain, uh rather, discuss their assignments and encourage each other. Thanks to the enthusiastic initiative of Johannes de Jong, you can keep track of your progress on the drive with the Assignment Log. If you're tough enough to get through the nitpicking, you'll start collecting moose heads at the Cattle Drive Hall of Fame. Gettin' them doggies... Fresh riders on the Drive... Another moose on the wall
for... Jay Lyche and Juliane Gross each bagged their first moose on the Java Basics Trail of the drive. Way to go Jay and Juliane! While Elouise Kivineva was busy a ramblin' down the Classes and Objects Trail and baggin' her second moose, long timer Michael Matola got 'round to baggin' his third moose on the Servlets Trail. A big cloud of dust was a followin' Barry Gaunt, Ken Cobbs, and David Mason as together they stormed through the assignments on the first two trails and are already half-finished with the Servlets Trail. That's one hard-working trio. We're all lookin' forward to hearing some darn good fish stories in the Saloon from Manju Jain, who recently hung a fourth moose on the wall. Good job Ranchers! Nitpicking is hard work too... Tips for the Trail... Content and format adapted from Ol' Timer Pauline McNamara's original column. -Dirk Schreckmann. Return to Top |
||||||||||||||||||||||||||||||
SCJP - Accept the Challenge
I decided to go for my SCJP because the company I work for has introduced a new performance management system that lets the employees set measurable objectives at the beginning of a year. As I've played around with Java for awhile and we use a bit of Java at work, I decided why not make SCJP one of my objectives. My boss loved the idea. Heck, what better excuse at the end of the year to say,. "Hey Johannes, no pay rise since you did not pass your SCJP". As I love my yearly pay rise and Kathy & Bert's book got rave reviews all over the Java Ranch, and elsewhere, I decided to go out and buy their book. Now let?s be honest, up to now getting my SCJP was simply an objective I HAD to accomplish. Deep down in my heart I felt like a kid that had to do his homework, until I read the intro of Kathy & Bert's book. What did this intro do for me?? Imagine someone tells you about this high mountain and what a challenge it is to climb it. They don't attempt to lie to you, they tell you it is a HARD, MEAN mountain to climb, but they are nice people and they also give you a map, compass, and everything else you need to climb it. First of all, they tell you how you should approach your preparation. They give some very simple but fantastic study tips, that I wish I knew when I was at school and which I will share with my 12 year old son when he is in a perceptive mood again. And then they give some solid advice on how you should sit for the exam. Man, I never knew taking a exam was such a challenge. I always saw it as, sit down and write the damn thing. The way Kathy and Bert explained it in their book makes me want to go out there and beat the hell out of the exam. It's my opponent. He is there to challenge my knowledge and I will beat him like I will beat someone in a game of squash, which I never do by the way. Lets face it we. All of us have to learn new computer languages from time to time. Most of these languages we learn by doing. Learning a computer language, often means only learning the instructions you need. One seldom has to learn and understand the "deeper", inner workings of a language. Sun forces us to do just that, if one wants to get your SCJP. Heck getting your SCJP is like getting a at primary school for knowing your work. With the intro to their book, Kathy and Bert have convinced me that I want to know for myself that I really know the Java language and not simply a subset of the language. Some might say I don't need a piece of paper as proof that I know my stuff, but I say it's all about climbing that mountain. Just smell the air when you stand up on the top and you've beaten it. Do it for yourself . Good luck and have fun getting your SCJP. I know I will. Kathy and Bert have kindly allowed us to make the intro available to our readers. So go read the INTRO and let them convince you to take up the challenge. Please note that Bert could not find the final version of the intro, so I had to retype certain parts of it from my book, so please forgive the typo's - Johannes de Jong. Return to Top |
||||||||||||||||||||||||||||||
Return to Top |
||||||||||||||||||||||||||||||
March Scheduled Book
Promotions:
Return to Top |
||||||||||||||||||||||||||||||
Shout out a BIG welcome to our new Bartenders. JavaRanch likes to reward those special people who have been
a big part in making JavaRanch one of the most popular Java web sites. Here they are:
JavaRanch has been named as a Jolt finalist by Software Development Magazine! For those who missed it, we have added a few new forums. Forums for security and testing have been added to the "Engineering" section. Forums for ANT and Resin have been added to the "Products" section. Hey, we've added a Tack Room. No one should be out on the range without their vital JavaRanch supplies. T-shirts, caps, lunch bags, and mugs will keep you ready whether you are out on a cattle drive or just dropping in to the saloon.
This month's special item is the JavaRanch Official Teddy Bear. Show them you care with the JavaRanch Teddy Bear!
As always JavaRanch is dedicated to providing you with the best source of information on Java Programming and Engineering.
by Thomas Paul Return to Top |
Managing Editor: Johannes de Jong
Comments or suggestions for JavaRanch's NewsLetter can be sent to the NewsLetter Staff
For advertising opportunities contact NewsLetter Advertising Staff