7 The Sprig Web MVC Framework
128 Chapter 7 The Sprig Web MVC Framework IN THE PREVIOUS CHAPTER, I gave you a overview of the Sprig Framework.We looked at what Sprig is, how it is packaged, ad the various modules it cotais. I also metioed that with Sprig, you do ot have to take a all-or-othig approach whe tryig to decide whether you should use Sprig. I other words, based o your eeds, you ca phase i the Sprig Framework oe module at a time (alog with ay depedecies). I this chapter, I will demostrate how to use Sprig Web MVC Framework (module), to build Time Expressio, our sample web applicatio. Note that from this poit o, I will refer to the Sprig Web MVC Framework as simply Sprig MVC, i most places. What s Covered i This Chapter I this chapter, we will Look at the various beefits of usig Sprig MVC Take a i-depth look at the Sprig Web MVC Framework Build three of the screes i Time Expressio usig Sprig MVC: a o-form cotroller, two form cotrollers, ad a Sprig HTTP iterceptor. Note The complete code for the examples used i this chapter ca be foud withi this book s code zip file (available o the book s website). This is a excitig chapter, so I wo t waste ay more time borig you with itroductory material. Let s sprig ito actio! Beefits of the Sprig Web MVC Framework The Sprig Web MVC Framework is a robust, flexible, ad well-desiged framework for rapidly developig web applicatios usig the MVC desig patter.the beefits achieved from usig this Sprig module are similar to those you get from the rest of the Sprig Framework. Let s review a few of these. I will demostrate some of these beefits later i this chapter. Easier testig This is a commo theme you will fid across all the Sprig classes. The fact that most of Sprig s classes are desiged as JavaBeas eables you to iject test data usig the setter methods of these classes. Sprig also provides mock classes to simulate Java HTTP objects (HttpServletRequest, for example), which makes uit testig of the web layer much simpler. Bid directly to busiess objects Sprig MVC does ot require your busiess (model) classes to exted ay special classes; this eables you to reuse your busiess objects by bidig them directly to the HTML forms fields. I fact, your
Sprig Web MVC Cocepts 129 cotroller classes are the oly oes that are required to exted Sprig classes (or implemet a Sprig cotroller iterface). Clear separatio of roles Sprig MVC icely separates the roles played by the various compoets that make up this web framework. For example, whe we discuss cocepts such as cotrollers, commad objects, ad validators, you will begi to see how each compoet plays a distict role. Adaptable cotrollers If your applicatio does ot require a HTML form, you ca write a simpler versio of a Sprig cotroller that does eed all the extra compoets required for form cotrollers. I fact, Sprig provides several types of cotrollers, each servig a differet purpose. For example, there are o-form cotrollers, simple form cotrollers, wizardlike form cotrollers, views with o cotrollers, ad eve prepackaged cotrollers that eable you to write views without your ow custom cotroller. Simple but powerful tag library Sprig s tag library is small, straightforward, but powerful. For example, Sprig uses the JSP expressio laguage (EL) for argumets to the <sprig:bid> tag. Web Flow This module is a subproject ad is ot budled with the Sprig core distributio. It is built o top of Sprig MVC ad adds the capability to easily write wizardlike web applicatios that spa across several HTTP requests (a olie shoppig cart, for example). View techologies ad web frameworks Although we are usig JSP as our view techology, Sprig supports other view techologies as well, such as Apache Velocity (jakarta.apache.org/velocity/) ad FreeMarker (freemarker.org).this is a powerful cocept because switchig from JSP to Velocity is a matter of cofiguratio. Furthermore, Sprig provides itegratio support for Apache Struts (struts. apache.org), Apache Tapestry (jakarta.apache.org/tapestry), ad OpeSymphoy s WebWork (opesymphoy.com/webwork/). Lighter-weight eviromet As I metioed i the previous chapter, Sprig eables you to build eterprise-ready applicatios usig POJOs; the eviromet setup ca be simpler ad less expesive because you could develop ad deploy your applicatio usig a lighter-weight servlet cotaier. Sprig Web MVC Cocepts The world of Java has see may MVC desig patter-based web frameworks crop up i the past few years (several are listed at the very ed of this chapter). MVC was origially coceived at XEROX PARC aroud the 1978 79 time frame ad was later implemeted i the Smalltalk-80 class library (also at XEROX PARC). It is a relatively simple cocept to grasp ad provides for a clea separatio of presetatio ad data, as I ll explai briefly here.
130 Chapter 7 The Sprig Web MVC Framework First, let s look at our architecture diagram established earlier i the book ad show here i Figure 7.1. Figure 7.1 High-level architecture diagram for Time Expressio. As you ca see, all icomig HTTP requests from a web browser are hadled by Cotrollers. A cotroller, as the ame idicates, cotrols the view ad model by facilitatig data exchage betwee them.the key beefit of this approach is that the model ca worry oly about the data ad has o kowledge of the view.the view, o the other had, has o kowledge of the model ad busiess logic ad simply reders the data passed to it (as a web page, i our case).the MVC patter also allows us to chage the view without havig to chage the model. Let s review some basic Sprig MVC cocepts. First, we will look at the cocepts related to Java codig, ad the we will look at the cofiguratio required to make all this work. Sprig MVC Java Cocepts Figure 7.1 provided us a high-level view of the architecture for Time Expressio. Now let s take a slightly more detailed ad focused look at the Sprig MVC compoets. Figure 7.2 shows a ed-to-ed flow for a typical scree i Time Expressio.This diagram shows may of the cocepts we will discuss ext. Cotroller Sprig provides may types of cotrollers.this ca be both good ad bad.the good thig is that you have a variety of cotrollers to choose from, but that also happes to be the bad part because it ca be a bit cofusig at first about which oe to use. The best way to decide which cotroller type to use probably is by kowig what type of fuctioality you eed. For example, do your screes cotai a form? Do you eed wizardlike fuctioality? Do you just wat to redirect to a JSP page ad have o cotroller at all? These are the types of questios you will eed to ask yourself to help you arrow dow the choices.
Sprig Web MVC Cocepts 131 Figure 7.2 Ed-to-ed flow for Eter Hours scree usig Sprig ad Hiberate. Figure 7.3 shows a class diagram of some of the more iterestig cotrollers that are part of Sprig MVC.Table 7.1 provides brief descriptios o the iterface ad classes show i Figure 7.3. (Note:The descriptios provided i this table are take directly out of the Sprig Framework Javadocs.) I ted to use SimpleFormCotroller, UrlFileameViewCotroller, ad AbstractCotroller most ofte.we will see examples of these later i this chapter. Figure 7.3 Class diagram showig a partial list of Sprig cotrollers. Table 7.1 Descriptio of Various Sprig Cotrollers Descriptio (Take Directly from the Sprig Cotroller Javadocs) AbstractCommadCotroller Abstract base class for custom commad cotrollers. AbstractCotroller Coveiet superclass for cotroller implemetatios, usig the Template Method desig patter.
132 Chapter 7 The Sprig Web MVC Framework Table 7.1 Cotiued Cotroller AbstractFormCotroller AbstractUrlViewCotroller AbstractWizardFormCotroller BaseCommadCotroller CacellableFormCotroller Cotroller ParameterizableViewCotroller SimpleFormCotroller UrlFileameViewCotroller Descriptio (Take Directly from the Sprig Javadocs) Form cotroller that autopopulates a form bea from the request. Abstract base class for Cotrollers that retur a view ame based o the URL. Form cotroller for typical wizard-style workflows. Cotroller implemetatio that creates a object (the commad object) o receipt of a request ad attempts to populate this object with request parameters. Extesio of SimpleFormCotroller that supports cacellatio of form processig. Base Cotroller iterface, represetig a compoet that receives HttpServletRequest ad HttpServletRespose like a HttpServlet but is able to participate i a MVC workflow. Trivial cotroller that always returs a amed view. Cocrete FormCotroller implemetatio that provides cofigurable form ad success views, ad a osubmit chai for coveiet overridig. Cotroller that trasforms the virtual fileame at the ed of a URL ito a view ame ad returs that view. Model ad View May of the methods i the Cotroller related subclasses retur a org. sprigframework.web.servlet.modeladview object.this object holds the model (as a java.util.map object) ad view ame ad makes it possible to retur both i oe retur value from a method.we will see examples of this later i this chapter whe we build two of the screes for Time Expressio. Commad (Form Backig) Object Sprig uses the otio of a commad object, which essetially is a JavaBea style class that gets populated with the data from a HTML form s fields.this same object is also passed to our validators (discussed ext) for data validatio, ad if the validatios pass, it is passed to the osubmit method (i cotroller related classes) for processig of valid data. Give that this commad object is a simple JavaBea-style class, we ca use our busiess objects directly for data bidig istead of writig special classes just for data bidig. I will demostrate this beefit later i this chapter.
Sprig Web MVC Cocepts 133 Validator A Sprig validator is a optioal class that ca be ivoked for validatig form data for a give commad (form) cotroller.this validator class is a cocrete class that implemets the org.sprigframework.validatio.validator iterface. Oe of the two methods required by this iterface is the validate method, which is passed a commad object, as metioed previously, ad a Errors object, which ca be used to retur errors. I will demostrate a example of a Validator class later i this chapter. Aother otable validatio class is org.sprigframework.validatio.validatioutils, which provides coveiet methods for rejectig empty fields. Sprig Tag Library (sprig:bid) The sprig bid tag library is simple yet powerful. It is typically used i JSP files via the <sprig:bid> tag, which essetially bids HTML form fields to the commad object. Furthermore, it provides access to special variables withi JSP, such as ${status.value}, ${status.expressio}, ad ${status.errormessages}, which we will look at later i the chapter. Sprig MVC Cofiguratio Cocepts I this sectio, we will review some core cocepts related to cofigurig the Sprig Web MVC Framework. DispatcherServlet DispatcherServlet (part of the org.sprigframework.web.servlet package) is the etry poit to the world of Sprig Web MVC, as depicted i Figure 7.2. It essetially dispatches requests to the cotrollers. If you have worked with Java web applicatios before, you will ot be surprised to fid out that this class is cofigured i the web.xml file, as show i the followig excerpt from the complete web.xml for Time Expressio: <servlet-class> org.sprigframework.web.servlet.dispatcherservlet </servlet-class> We will discuss DispatcherServlet i detail later i this chapter. Hadler Mappigs You ca map hadlers for icomig HTTP requests i the Sprig applicatio cotext file.these hadlers are typically cotrollers that are mapped to partial or complete URLs of icomig requests.the hadler mappigs ca also cotai optioal iterceptors, which are ivoked before ad after the hadler.this is a powerful cocept. I will demostrate a example of this later i this chapter whe we use such a web iterceptor for autheticatio ad close our Hiberate sessio for the give HTTP request.
134 Chapter 7 The Sprig Web MVC Framework The followig code excerpt take from our complete timex-servlet.xml file shows how a hadler ca be mapped to a partial URL: <bea id= urlmap class= org.sprigframework.web.servlet.hadler.simpleurlhadlermappig > <property ame= urlmap > <props> <prop key= /sigi.htm >sigicotroller</prop> <prop key= /sigout.htm >sigoutcotroller</prop> </props> </property> </bea> View Resolvers Sprig uses the otio of view resolvers, which resolve view ames to the actual views (eterhours to eterhours.jsp, for example).we will use Sprig s IteralResourceViewResolver class to resolve our view ames. (This is covered i the ext sectio.) Sprig Setup for Time Expressio Now that I have provided you some fudametal cocepts for Sprig MVC, let s begi settig it up for developmet of Time Expressio screes. We eed a couple of compoets to get Sprig up ad ruig for us. Figure 7.1 showed the Time Expressio high-level architecture we established early i this book. As you ca see, we eed a servlet cotaier that Sprig ca ru withi for our web applicatio. So let s start with the istallatio of a Servlet cotaier first, ad the we will dowload ad istall the Sprig Framework. Istallig a Servlet Cotaier (Apache Tomcat) I have chose to use Apache Tomcat (http://tomcat.apache.org/) as the Servlet cotaier for the Time Expressio applicatio. However, you ca use ay other product you wat; this ca be a servlet-cotaier-oly product, such as Tomcat, or a full-blow applicatio server, such as JBoss Applicatio Server, BEA WebLogic, or IBM Websphere. Note If you have bee followig alog the examples i this book, you will recall the timex/local.properties file used by our At build.xml file (both files are provided i this book s code zip file). Note the deploy.dir property i the timex/local.properties file; this ca be adjusted to poit to your servlet cotaier s deploymet directory. For example, i my case, the deploy.dir property is set up as show here: deploy.dir=/apache-tomcat-5.5.15/webapps
Sprig Setup for Time Expressio 135 Now we ca ru the at deploy from a commad lie usig our build.xml file. By ruig this at commad, a fresh ew timex.war web archive file will be built ad deployed to the specified directory (i deploy.dir). Hot Deployig WAR Files ad HTTP Mock Style Testig I 2001, I wrote a article titled How May Times Do You Restart Your Server Durig Developmet? (http://www.javaworld.com/javaworld/jw-04-2001/jw-0406-soapbox.html). Although various servlet cotaiers or applicatio servers hadle reloadig of applicatios differetly, restartig the server every time you make a chage to your applicatio ca become a waste of time. Much of this has to do with the way Java s class loadig works, but it still does t make it ay less frustratig. If your server does t (hot) redeploy your war files successfully, you could cosider tweakig your style of codig ad testig. Oe good alterative (discussed i this chapter) is to use Sprig s mock classes to simulate a HTTP request ad use JUit to uit test the code istead of relyig completely o the web applicatio server for your testig. Icidetally, I recetly came across a optio for Apache Tomcat that will eable to us to avoid restarts whe deployig our applicatio. This ca be activated by settig the followig attributes i the cof/cotext.xml file foud uder the Tomcat istall directory, <Cotext atijarlockig= true atiresourcelockig= true >. Documetatio o these attributes ca be foud at http://tomcat.apache.org/tomcat-5.5-doc/cofig/ cotext.html#stadard%20implemetatio. Alteratively, we could use the Tomcat At deploy tasks; however, I wated to keep our build.xml geeric for most web servers. Nevertheless, documetatio o these tasks ca be foud at the tomcat.apache.org website. Istallig the Sprig Framework By ow, you should have a thorough uderstadig of what Sprig ca do for you. Next, it is time to dowload Sprig, istall it, ad begi usig it! The Sprig Framework ca be dowloaded from http://sprigframework.org.we will ow follow the istructios provided o the website to dowload ad istall it. The followig are oe-time setup steps we will eed to follow to get Sprig set up for our eviromet. From here, you might add exteral jars for added Sprig fuctioality as eeded to the timex/lib/ directory. (I Chapter 10, Beyod the Basics, we will add OpeSymphoy s quartz.jar file to our directory.) Sprig Copy sprig.jar to the timex/lib/ directory of Time Expressio, based o the directory structure we established i Chapter 3, XP ad AMDD- Based Architecture ad Desig Modelig, ad show here i Figure 7.4. JSTL We also eed to obtai JavaServer Pages Stadard Tag Library (JSTL), which is part of the Jakarta taglibs project ad ca be dowloaded from http://jakarta.apache.org/taglibs/. After dowloadig this package, copy the
136 Chapter 7 The Sprig Web MVC Framework jstl.jar ad stadard.jar files to the timex/lib/ directory. JSTL helps elimiate (or at least sigificatly reduces) the amout of embedded scriptlet code i our JSP files. For example, JSTL provides tags for iteratios/loops (<foreach>, for example), coditioal tags (<if>, for example), formattig tags (fmt:formatdate, for example), ad several other tags.you will see examples of may of these tags i this chapter. Figure 7.4 Developmet directory structure for Time Expressio. Ruig Our SprigTest Icidetally, the three files we discussed i the previous chapter ca ow be created i the followig paths, ad we could ru at sprigtest (from our timex/ top-level directory) to test that we ca use Sprig i our code.the complete code for these files ca be foud i this book s code zip file: src/cof/sprigtest-applicatiocotext.xml src/java/com/visualpatters/timex/test/sprigtest.java src/java/com/visualpatters/timex/test/sprigtestmessage.java
Sprig Setup for Time Expressio 137 Cofigurig Sprig MVC Now that we have the servlet cotaier ad Sprig software istalled, we eed to cofigure Sprig MVC so that we ca begi developig ad deployig the Time Expressio sample applicatio. Cofigure DispatcherServlet i web.xml The very first thig we eed to do is to have all icomig HTTP requests (that match a certai patter) forwarded to Sprig MVC, by Tomcat. The followig excerpt from our web.xml file demostrates how we ca cofigure all requests edig with a.htm extesio to be processed by the Sprig s org. sprigframework.web.servlet.dispatcherservlet class: <servlet> <servlet-ame>timex</servlet-ame> <servlet-class> org.sprigframework.web.servlet.dispatcherservlet </servlet-class> <load-o-startup>1</load-o-startup> </servlet> <servlet-mappig> <servlet-ame>timex</servlet-ame> <url-patter>*.htm</url-patter> </servlet-mappig> Later o we will see how requests with a.jsp extesio are hadled by Sprig s DispatcherServlet. Note Our Sprig applicatio cotext file, timex-servlet.xml, will automatically be searched for ad loaded by Sprig for us. This file is stored uder timex/src/cof but automatically copied to the timex/build/timex/ WEB-INF/ directory by our At build.xml file whe the build, dist, or deploy targets are used. Create Sprig s Applicatio Cotext XML File (timex-servlet.xml) Now we eed to create our applicatio cotext XML file, timex-servlet.xml.we will review various parts of this file throughout the remaider of this chapter.you will see how this file quickly becomes a essetial part of workig with Sprig MVC. The followig excerpt from timex-servlet.xml shows how we cofigure a Sprig view resolver to resolve logical view ames to the physical view (JSP) file: <bea id= viewresolver class= org.sprigframework.web.servlet.view.iteralresourceviewresolver > <property ame= viewclass > <value>org.sprigframework.web.servlet.view.jstlview</value>
138 Chapter 7 The Sprig Web MVC Framework </property> <property ame= prefix > <value>/web-inf/jsp/</value> </property> <property ame= suffix > <value>.jsp</value> </property> </bea> Note By storig our JSP files i the build/timex/web-inf/jsp/ directory, we are essetially hidig these files so they caot be accessed directly from a web browser usig their actual fileames (that is, oly views edig with.htm are mapped to these files). To access.jsp files directly, they must be placed a couple of levels up, uder build/timex/, the same locatio where our welcome file, idex.jsp, will reside. Hidig files is a security precautioary measure. Appedix D, Securig Web Applicatios, provides additioal security guidelies. Developig Time Expressio User Iterfaces with Sprig Now that we have Tomcat ad Sprig istalled ad set up, we ca go through the steps required to develop our sample screes. Let s look at two Time Expressio screes we will develop i this chapter oe a oform scree ad the other a HTML form scree. Timesheet List Scree Figure 7.5 shows the Timesheet List scree, which is a oform scree (that is, it cotais o iput fields a user ca fill i because it is a display-oly scree). From the perspective of codig a cotroller, this is the most basic scree that you ca develop usig Sprig MVC; we will review the code behid this shortly. Eter Hours Scree Figure 7.6 shows the Eter Hours scree, a form scree (that is, it cotais iput fields a user ca fill i).this is a little more complicated tha the Timesheet List scree because we will have to bid the HTML form fields to our Java code, perform validatios o the data etered, display errors, ad so o.
Developig Time Expressio User Iterfaces with Sprig 139 Figure 7.5 Time Expressio s Timesheet List web page (view ame: timesheetlist). Figure 7.6 Time Expressio s Eter Hours web page (view ame: eterhours). Java Files By ow we have eough iformatio to come up with fileames for our Java classes ad JSP (view) fileames.table 7.2 shows a map of the view, cotroller, ad collaborator (model) classes required to complete the two screes show i Figures 7.5 ad 7.6.You might recall that we desiged this map i Chapter 3 (see Table 3.5). Table 7.2 Sample Applicatio Flow Map (from Chapter 3) Cotroller Tables Story Tag View Class Collaborators Impacted Timesheet timesheetlist TimeSheetListCotroller TimesheetMaager Timesheet List Eter Hours eterhours EterHoursCotroller TimesheetMaager Timesheet Departmet
140 Chapter 7 The Sprig Web MVC Framework Note that the collaborator classes metioed here were already developed i Chapter 5, Usig Hiberate for Persistet Objects, so we eed to develop the view ad cotroller classes ow. Figure 7.7 shows a rudimetary class diagram o how the cotroller ad model related classes fit together. Figure 7.7 Class diagram showig relatioship betwee Time Expressio model ad cotroller classes. If you have developed web applicatios i Java before, you might questio the placemet of.jsp files uder the same directory structure as my Java classes (that is, java/com/ visualpatters/timex/); this is purely a persoal preferece because I like to see my MVC files grouped together uder the same paret directory. Let s look at how to develop the Timesheet List ad Eter Hours screes, step-bystep.we will later look at how to develop the Sig I scree because it is a special case because of the autheticatio (sig i) required. Cascadig Style Sheet (CSS) Other tha the Java ad JSP files we discussed, we are also usig a cascadig style sheet (CSS) file amed timex.css (placed i our src/web/icludes directory). CSS provides a cosistet look-ad-feel across our user iterfaces; furthermore, it helps reduce the size of our JSP/HTML code because we do t have as much formattig code i our view (JSP) files.
Timesheet List Scree: A No-Form Cotroller Example 141 Timesheet List Scree: A No-Form Cotroller Example Developig a o-form cotroller i Sprig is a relatively straightforward process. Let s look at the steps ivolved to do this. Step-by-Step Cofiguratio The followig are Sprig-related items we eed to cofigure i timex-servlet.xml, our Sprig applicatio cotext file. Map Hadler The first thig we eed to do is to map the icomig request URL to a actual cotroller, which will hadle the request.the followig excerpt from the timex-servlet. xml file shows how we ca map the timesheetlist.htm URL to a iteral bea referece amed timesheetlistcotroller (discussed ext) with the help of Sprig s SimpleUrlHadlerMappig class: <bea id= urlmapautheticate class= org.sprigframework.web.servlet.hadler.simpleurlhadlermappig > <property ame= iterceptors > <list> <ref bea= httprequestiterceptor /> </list> </property> <property ame= urlmap > <props> <prop key= /timesheetlist.htm > timesheetlistcotroller </prop> Also, otice the iterceptors property; by cofigurig this, we ca itercept HTTP requests, for example, to implemet autheticatio (iterceptors are discussed i detail later i this chapter). Defie Cotroller ad Associated Class The ext step is to defie the cotroller class refereced by the map hadler.the followig excerpt from the timex-servlet.xml file demostrates how this is doe: <bea ame= timesheetlistcotroller class= com.visualpatters.timex.cotroller.timesheetlistcotroller > <property ame= timesheetmaager > <ref bea= timesheetmaager /> </property> <property ame= applicatiosecuritymaager > <ref bea= applicatiosecuritymaager /> </property>
142 Chapter 7 The Sprig Web MVC Framework <property ame= successview > <value>timesheetlist</value> </property> </bea> Notice the ref attributes. As you might guess, these are refereces to other beas defied i our applicatio cotext, as show i this XML excerpt: <bea id= timesheetmaager class= com.visualpatters.timex.model.timesheetmaager /> <bea id= applicatiosecuritymaager class= com.visualpatters.timex.util.applicatiosecuritymaager /> We already developed the TimesheetMaager class i Chapter 5; we will develop the ApplicatioSecurityMaager class later i this chapter. This is all we eed to cofigure for the Timesheet List scree. Now we eed to write the cotroller ad view code, refereced here. Let s look at that ext. Step-by-Step Codig The Timesheet List scree is a relatively simple scree ad will be developed usig the most basic type of Sprig cotroller because it cotais o form fields; therefore, it will ot require thigs such as Commad ad Validator classes. Basically, if we look at this from a MVC desig patter perspective, the files for this scree will iclude the followig: Model TimesheetMaager.java ad Timesheet.java View timesheetlist.jsp Cotroller TimesheetCotroller.java We already developed the model files i the previous chapter, so all we eed to develop here are the cotroller ad view files. Let s dissect ad review parts of our complete code. Let s begi by writig the uit test code for our cotroller class. Writig Our Test First with Mock Objects The ext few code excerpts from our TimesheetListCotrollerTest.java file show how we ca uit test cotroller classes.we will create this i the timex/src/java/com/ visualpatters/timex/cotroller directory. We start by creatig a istace of the org.sprigframework.mock.web. MockHttpServletRequest class to simulate a real HTTP request.this class ot oly provides the beefit of beig able to uit test our code but also reduces the eed to deploy the applicatio ad potetially restart the servlet cotaier (Tomcat, for example) each time we wat to test somethig. mockhttpservletrequest = ew MockHttpServletRequest( GET, /timesheetlist.htm );
Timesheet List Scree: A No-Form Cotroller Example 143 Next, we will create some test depedecy objects ad iject them, as Sprig will do for us at rutime: Employee employee = ew Employee(); employee.setemployeeid(employee_id); applicatiosecuritymaager.setemployee(mockhttpservletrequest, employee); // iject objects that Sprig ormally would timesheetlistcotroller = ew TimesheetListCotroller(); timesheetlistcotroller.settimesheetmaager(timesheetmaager); timesheetlistcotroller.setapplicatiosecuritymaager(applicatiosecuritymaager); I our test code, we istatiated our ow TimesheetMaager class for the sake of simplicity. However i real-world applicatios, you might wat to use Sprig s FileSystemXmlApplicatioCotext or ClassPathXmlApplicatioCotext classes to istatiate your classes.this way, you ot oly get a istace of a class but also have its depedet objects loaded ad ijected by Sprig. Now we ca complete our test by checkig the java.util.list we just retrieved; our test esures that list is ot empty ad also that it cotais Timesheet objects for the employee we requested the records for: ModelAdView modeladview = timesheetlistcotroller.hadlerequest( mockhttpservletrequest, ull); assertnotnull(modeladview); assertnotnull(modeladview.getmodel()); List timesheets = (List) modeladview.getmodel().get( TimesheetListCotroller.MAP_KEY); assertnotnull(timesheets); Timesheet timesheet; for (it i = 0; i < timesheets.size(); i++) { timesheet = (Timesheet) timesheets.get(i); assertequals(employee_id, timesheet.getemployeeid()); System.out.pritl(timesheet.getTimesheetId() + passed! ); } That s about it for our uit test class; ow let s review the actual TimesheetListCotroller class.
144 Chapter 7 The Sprig Web MVC Framework Writig Uit Test ad Actual Code i the Same Sittig This book s code zip file shows the complete code for our TimesheetListCotrollerTest.java class, which is the JUit test case for TimesheetCotroller.java. As I ve preached previously i this book, developmet of a uit test ad the actual code works best whe it is doe i the same sittig. For example, I wrote the TimesheetListCotrollerTest.java ad TimesheetListCotroller.java i the same sittig; that is, I coded a little, compiled ad tested a little, ad the repeated these steps util my cotroller class provided all the fuctioality I eeded. The obvious beefit of this approach was that my code was uit tested by the time I was doe! Furthermore, our cotroller class will ow cotai oly the code we eed othig more, othig less. Aother otable beefit worth metioig is that at times I fid myself gettig programmer s block (similar to writer s block). But startig out with the uit test code helps me get goig. Note that what I have metioed here is a persoal style of workig, but hopefully you will fid value i it ad give the test-first approach a try (if you do t already do so). Oe thig I do wat to stress is that like everythig else, you eed to fid the right balace. Although I believe i the test-first approach, there are times whe it is t feasible for me to write a uit test code that becomes more complicated tha the actual code or is cumbersome to write. After all, you are writig Java code to test other Java code, which raises a obvious questio do we also test the test code? Of course, I m kiddig here, but my poit is to fid the right balace ad i most cases, uit tests work out pretty well. Last, uit testig works best if you write small methods that ca be uit tested relatively easily. Cotroller Code Now it is time to review the code behid our cotroller class for the Timesheet List scree, TimesheetListCotroller.java.We will create this i the timex/src/java/ com/visualpatters/timex/cotroller directory. For starters, otice that we are implemetig the org.sprigframework.web. servlet.mvc.cotroller iterface; this is perhaps the most basic type of cotroller you ca develop usig Sprig. public class TimesheetListCotroller implemets Cotroller The ext iterestig thig to ote is the hadlerequest method; this is the oly method we must implemet to satisfy the requiremets of the Cotroller iterface. public ModelAdView hadlerequest(httpservletrequest request, HttpServletRespose respose) The hadlerequest method returs a ModelAdView object, which cotais the view ame ad the model data (a java.util.list, i our case).the view ame is resolved by JstlView, which we defied i the timex-servlet.xml file we saw earlier i this chapter. retur ew ModelAdView(VIEW_NAME, MAP_KEY, timesheetmaager.gettimesheets(employeeid));
Timesheet List Scree: A No-Form Cotroller Example 145 There are a few more variatios to how you ca costruct the ModelAdView class, as show i the followig list (see the Sprig Framework API Javadocs for details): ModelAdView() ModelAdView(Strig viewname) ModelAdView(Strig viewname, Map model) ModelAdView(Strig viewname, Strig modelname, Object modelobject) ModelAdView(View view) ModelAdView(View view, Map model) ModelAdView(View view, Strig modelname, Object modelobject) View/JSP Code We already prototyped the screes i Chapter 2, The Sample Applicatio: A Olie Timesheet System, so we ow eed to add some code to the related view (.jsp) files. This book s code zip file cotais the before file, timesheetlist.html (prototyped, static HTML), ad the after file, timesheetlist.jsp (dyamic/jsp), versios of this file. Let s review our timesheetlist.jsp a bit closer. For starters, we will create this i the timex/src/java/com/visualpatters/timex/view directory. Now let s look at some JSP code. The followig excerpt from our timesheetlist.jsp file shows the dyamic code used for populatig the HTML table o the Timesheet List scree; this is doe i a loop usig JSTLs foreach tag.withi each loop, we are geeratig the HTML table s rows ad colums (ad also formattig the hours) usig the JSTL core library. <c:foreach items= ${timesheets} var= timesheet > <tr> <td alig= ceter ><a href= eterhours.htm?eid=<c:out value= ${timesheet.employeeid} />&tid=<c:out value= ${timesheet.timesheetid} /> ><fmt:formatdate value= ${timesheet.periodedigdate} type= date Now let s look at aother iterestig piece of code from our view file, timesheetlist.jsp: <c:if test= ${ot empty message} > <fot color= gree ><c:out value= ${message} /></fot> <c:set var= message value= scope= sessio /> </c:if> All this code does is check for ay messages stored i the message sessio attribute. This message is set by the Eter Hours cotroller upo a successful save i the osubmit method, as you will see later i the chapter.
146 Chapter 7 The Sprig Web MVC Framework We just looked at how to cofigure ad code the Timesheet List scree. Now it is time to review more complex Sprig MVC features. Eter Hours Scree: A Form Cotroller Example The Timesheet List scree example we just looked at demostrated how to develop a simple o-form cotroller. Now let s look at a slightly more complex example usig the Eter Hours scree show i Figure 7.6. As you ca see from Figure 7.6, the Eter Hours scree eables users to eter their hours ad select the departmet these hours should be charged to (usig a drop-dow list).this fuctioality will require us to get a list of departmet ames, bid the HTML form fields to a Java object, validate data etered o the scree, ad display error/status messages o the scree. Step-by-Step Cofiguratio The followig are steps required to cofigure the Eter Hours scree i our timexservlet.xml file. For the sake of brevity, I will ot provide detailed explaatios for the same steps we covered previously for the Timesheet List scree. Map Hadler The followig lie provides the mappig for the Eter Hours view to the cotroller class: <prop key= /eterhours.htm >eterhourscotroller</prop> Defie Cotroller ad Associated Classes The cofiguratio for the Eter Hours cotroller is a bit more ivolved tha the Timesheet List cotroller, so let s take a closer look at it. First, you will otice that we have two model classes ad oe security-related (utility) class; these are required for the Eter Hours scree to fuctio, which are cofigured as follows: <property ame= timesheetmaager > <ref bea= timesheetmaager /> </property> <property ame= departmetmaager > <ref bea= departmetmaager /> </property> <property ame= applicatiosecuritymaager > <ref bea= applicatiosecuritymaager /> </property>
Eter Hours Scree: A Form Cotroller Example 147 The followig lies cofigure the commad class for the EterHoursCotroller: <property ame= commadclass > <value>com.visualpatters.timex.model.timesheet</value> </property> The remaider of the cofiguratio for this cotroller is Sprig specific. For example, you will otice the validator property, which is a optioal cofiguratio but oe we will use to validate the iput data from the scree.the formview is the ame of the actual form view ad successview is the view you wat Sprig to redirect to upo a successful form submittal.the sessioform property allows us to keep the same istace of the commad object i the sessio versus creatig a ew oe each time. <property ame= formview > <value>eterhours</value> </property> <property ame= successview > <value>redirect:timesheetlist.htm</value> </property> <property ame= validator > <ref bea= eterhoursvalidator /> </property> ResourceBudle Oe other cofiguratio item we should look at is related to exteralizig strig messages for iteratioalizatio ad other purposes, as show here: <bea id= messagesource class= org.sprigframework.cotext.support.resourcebudlemessagesource > <property ame= baseames > <list> <value>messages</value> </list> </property> </bea> The ResourceBudleMessageSource Sprig class relies o JDK s java.util.resourcebudle class; we will use this to exteralize our error ad status messages i a file called messages.properties (placed i our timex/src/cof directory), which cotais the followig messages: typemismatch.it=ivalid umber specified i a umeric field error.eterhours.missigdepartmet=please select a departmet error.logi.ivalid=ivalid employee id or password message.eterhours.savesuccess=timesheet saved successfully
148 Chapter 7 The Sprig Web MVC Framework Alteratively, Sprig also provides a class amed ReloadableResourceBudleMessageSource, which ca be used to reload the properties periodically usig its cachesecods parameter settig.this ca come i hady durig developmet, whe the messages file ca chage ofte. Step-by-Step Codig The followig is Sprig-related Java code we eed to write for our form cotroller. By the ed of this Eter Hours example, we will ed up with the followig files (uder our timex/src directory): cof/messages.properties java/com/visualpatters/timex/cotroller/eterhourscotroller.java java/com/visualpatters/timex/cotroller/eterhoursvalidator.java java/com/visualpatters/timex/cotroller/miutespropertyeditor.java java/com/visualpatters/timex/view/eterhours.jsp Cotroller Code Let s start by developig the cotroller. For starters, otice that istead of implemetig the org.sprigframework.web.servlet.mvc.cotroller iterface as we did for the TimesheetListCotroller, we are extedig Sprig s org.sprigframework. web.servlet.mvc.simpleformcotroller (cocrete) class. public class EterHoursCotroller exteds SimpleFormCotroller SimpleFormCotroller implemets the Cotroller iterface but also is part of a hierarchy of various abstract cotroller-related classes (as we saw i Figure 7.3). It ca also automatically redirect the user to the default form view i case of errors ad to a differet (or same) view if the form submissio is successful; this is cotrolled usig the successview ad formview properties we set i our timex-servlet.xml for the eterhourscotroller Sprig bea, as we saw earlier. Let s take a look at the various Sprig-related methods for form processig. However, before lookig at each method, let s look at the order i which these methods are called. Figure 7.8 shows three boxes: the first box is essetially whe the user first eters the scree; the secod box is whe the user submits the form with ivalid fields (that is, validatio fails), ad the third/last box shows which methods are called whe the validatio is successful. Now let s review the type of code that goes ito each of these methods. The first method I will discuss is the formbackigobject, which returs a commad object that is used to hold the iput data from the HTML form fields. Notice that we fetch a existig Timesheet record from the database if parameters are passed ito the cotroller, idicatig it is a edit operatio versus a add operatio, i which case, we costruct a ew commad object (which, icidetally, is a Time Expressio domai/ busiess object).
Eter Hours Scree: A Form Cotroller Example 149 protected Object formbackigobject(httpservletrequest request) { if (request.getparameter(tid)!= ull && request.getparameter(tid).trim().legth() > 0) retur timesheetmaager.gettimesheet(iteger.parseit(request.getparameter(tid)), false); } Timesheet timesheet = ew Timesheet(); Employee employee = (Employee) applicatiosecuritymaager.getemployee(request); timesheet.setemployeeid(employee.getemployeeid()); timesheet.setstatuscode( P ); timesheet.setperiodedigdate(dateutil.getcurretperiodedigdate()); retur timesheet; Figure 7.8 Life cycle of EterHoursCotroller. Bidig Directly to Domai (Busiess) Objects Oe vital beefit of Sprig MVC is the capability to bid the form fields directly to a domai object (Timesheet, for example)! This is oe of the thigs that separates Sprig from may other web frameworks. Next up is the iitbider method, which provides a good place to register custom property editors (discussed shortly), as show here: bider.registercustomeditor(it.class, ew MiutesPropertyEditor()); The referecedata method is a good place to retur read-oly data for forms, typically for drop-dow lists o the scree, as we have doe by returig a list of departmets for the Eter Hours scree: model.put( departmets, departmetmaager.getdepartmets()); Last, but ot least, let s look at oe of the most importat methods i our cotroller class, the osubmit method, show ext. As we saw i Figure 7.8, this method is called oly after all validatios have passed through successfully:
150 Chapter 7 The Sprig Web MVC Framework protected ModelAdView osubmit( HttpServletRequest request, HttpServletRespose respose, Object commad, BidExceptio errors) { Timesheet timesheet = (Timesheet) commad; timesheetmaager.savetimesheet(timesheet); request.getsessio().setattribute( message, getmessagesourceaccessor().getmessage( message.eterhours.savesuccess )); retur ew ModelAdView(getSuccessView()); } Also, otice the followig code i the osubmit method, which returs a successful message via the HTTP sessio.this message is extracted from the messages. properties file (usig the message.eterhours.savesuccess key) ad displayed o the Timesheet List scree. This is about all we will cover for the cotroller class. Now, let s look at the other related classes used by this cotroller. Custom Property Editor As I metioed earlier i this chapter, Sprig makes heavy use of JavaBea style property editors (that is, java.beas.propertyeditorsupport). We will write a custom property editor class, MiutesPropertyEditor, to covert the hours etered o the scree to miutes because that is how our database is desiged.the code for this class should be fairly straightforward because it performs the coversio from miutes to hours ad vice versa (that is, multiplyig or dividig by 60 miutes). Validatio Our validatio example is very also fairly straightforward.the mai code really is i the validate method of this class, as show i the followig code excerpt: Timesheet timesheet = (Timesheet)commad; if (timesheet.getdepartmetcode() == ull timesheet.getdepartmetcode().trim().legth() < 1) errors.reject( error.eterhours.missigdepartmet ); The error variable show here is of type org.sprigframework.validatio. Errors, which provides several reject methods.the example I have show here is useful for displayig global messages for the etire scree; I ted to use this method rather tha the field-specific oes. For example, oe of the field-specific reject methods has the followig sigature: rejectvalue(strig field, Strig errorcode).
Eter Hours Scree: A Form Cotroller Example 151 Also, you might have oticed a obidadvalidate method i Figure 7.8.This method has the followig sigature: obidadvalidate(httpservletrequest request, Object commad, BidExceptio errors) This method is called by Sprig automatically after the Validator object has bee ivoked.this is a great place to do additioal validatios for example, validatios based o parameters set i via HTTP request or database validatios usig oe of the ijected model classes, perhaps to check for duplicate records i the database. View/JSP Code Now that we are doe lookig at Java classes for the Eter Hours scree, we ca look at the correspodig view code, located i our eterhours.jsp file.we will ispect a few excerpts here. The first iterestig block of code i our view is the displayig of error messages set i our EterHoursValidator class, as show here: <sprig:bid path= commad.* > <c:if test= ${ot empty status.errormessages} > <c:foreach var= error items= ${status.errormessages} > <fot color= red ><c:out value= ${error} escapexml= false /></fot><br/> </c:foreach> </c:if> </sprig:bid> This is the first time we are seeig the sprig:bid tag, so let me explai a few thigs about it. The key class behid the sprig bid tag library is org.sprigframework.web. servlet.support.bidstatus.this tag eables you to bid the HTML form fields to the commad object (Timesheet, i our case). However, it also provides access to a special variable amed status.the status object cotais some of the followig attributes, which ca be used i the JSP code: status.value The value of a give attribute i the commad object status.expressio The ame of a give attribute i the commad object status.error A Boolea flag idicatig whether a error exists status.errormessage A field-specific error message status.errormessages Global error messages for the view status.displayvalue Get a strig value suitable for display usig tostrig
152 Chapter 7 The Sprig Web MVC Framework Now let s look at how fields are boud.the followig code shows how the departmetcode JSP/HTML variable is boud to the matchig variable i our Commad object (that is, Timesheet.departmetCode). <sprig:bid path= commad.departmetcode > That is really all there is to eterhours.jsp; some of the code I have ot explaied here is because we already covered similar code for the Timesheet List scree example earlier i this chapter (such as loopig through code usig the JSTL foreach tag). I wish I could tell you there is more to Sprig s bid tag library, but as I metioed earlier, this library is fairly simple; but what you ca do with it is quite powerful. Bidig to Custom (Nobusiess) Commad Objects Oe of the key beefits of Sprig MVC is that it eables you to bid HTML form fields directly to your domai object. Sprig refers to these objects as commad objects, perhaps based o the Commad desig patter, which basically ivolves ecapsulatio of a request i a object. Aother way to view the cocept of a commad object is to view it as our form object because it ca hold all the values etered o the HTML form. However, because we ca bid our HTML form fields directly to our busiess objects or have other data stored i this object, the term commad is more appropriate. For the Time Expressio screes, we bid directly to Timesheet, our domai object. However, you always have the optio to create a custom Commad class, which could, for example, exted or cotai the Timesheet class ad provide some additioal methods. For istace, I worked o a project where I eed to assemble ad disassemble a java.util.date object because the HTML form had separate drop-dows for moth, date, ad year. I that case, I used methods such as assembledate ad disassembledate i a custom commad class. There are a couple of ways you ca approach a custom commad class. For example, we could have doe somethig like the followig: public class TimesheetCommad exteds Timesheet By doig this, you ca still bid directly to the setter/getter methods of our busiess object, but also exted it by addig additioal methods, as eeded. Also, to costruct a custom commad class, you would eed to specify it i the timex-servlet.xml file ad also costruct/retur a object of this type i the formbackigobject method. The other approach is to have the TimesheetCommad class cotai a referece to the Timesheet object. For example, this class could have a costructor as follows: public TimesheetCommad(Timesheet timesheet) {...} Usig this approach, you would bid the HTML form fields to the Timesheet object usig a otatio similar to this: commad.timesheet.miutesmo
Views with No Cotrollers 153 The oe problem you ru ito with this approach is related to JavaScript validatio checkig because JavaScript gets cofused with the dots i HTML field ames. For example, commad.timesheet.miutesmo would traslate ito timesheet.miutesmo for the HTML iput text field ame if we used ${status.expressio} to fill i the ame of this iput field. DateUtil.java The oe other otable file is DateUtil.java; this file provides some utility type date methods. For example, our EterHoursCotroller class uses oe of these methods i its formbackigobject method: timesheet.setperiodedigdate(dateutil.getcurretperiodedigdate()); JSP Taglib Directives The oe thig I have t poited out explicitly util ow are the followig lies of code you might have oticed i our JSP files: <%@ taglib prefix= c uri= http://java.su.com/jsp/jstl/core %> <%@ taglib prefix= fmt uri= http://java.su.com/jsp/jstl/fmt %> <%@ taglib prefix= sprig uri= http://www.sprigframework.org/tags %> These directives are required before usig a JSP tag library. More iformatio o this ad other JSP features ca be foud o the java.su.com website. Views with No Cotrollers There might be times whe you do ot eed or wat to write a cotroller. For example, suppose we wat to implemet a help scree for Time Expressio.We wat this help scree to be accessible as /help.htm ad have the real file (help.jsp) hidde i /WEB- INF/jsp. I this case, we would first defie UrlFileameViewCotroller i timexservlet.xml, as show ext: <bea id= urlfileamecotroller class= org.sprigframework.web.servlet.mvc.urlfileameviewcotroller /> The we ca referece urlfileamecotroller i our hadler mappig (the urlmap bea i timex-servlet.xml, for example): <prop key= /help.htm >urlfileamecotroller</prop>
154 Chapter 7 The Sprig Web MVC Framework Sprig HadlerIterceptors Util ow, we developed our Timesheet List ad Eter Hours screes without worryig about autheticatio. However, oe of our fudametal requiremets from Chapter 2 is that employees ca see oly their ow timesheets, which brigs us to our Sig I ad Sig Out features. Sprig provides the cocept of iterceptors for web applicatio developmet; these eable you to itercept HTTP requests.we will use this feature to provide autheticatio for Time Expressio. To implemet our sig i/out features, we will eed to create the followig files uder the src/java/com/visualpatters/timex directory: cotroller/httprequestiterceptor.java cotroller/sigicotroller.java cotroller/sigivalidator.java cotroller/sigoutcotroller.java util/applicatiosecuritymaager.java util/dateutil.java view/sigi.jsp Autheticatio for Time Expressio The autheticatio for Time Expressio is eabled by havig all HTTP requests requirig autheticatio to be mapped as they go through our iterceptor class, HttpRequestIterceptor.java.The followig code excerpt demostrates how a itercepted request ca be preprocessed: public class HttpRequestIterceptor exteds HadlerIterceptorAdapter { private ApplicatioSecurityMaager applicatiosecuritymaager; public boolea prehadle(httpservletrequest request, HttpServletRespose respose, Object hadler) throws Exceptio { Employee employee = (Employee)applicatioSecurityMaager.getEmployee(request); if (employee == ull) { respose.sedredirect(this.sigipage); retur false; } retur true;
Our Sample Applicatio i Actio! 155 Notice the use of ApplicatioSecurityMaager here (ad refereced several times earlier i this chapter).the complete code for this class should be fairly straightforward to follow because it essetially provides methods for setig, gettig, ad removig a HTTP sessio attribute amed user (of type Employee, oe of our domai objects), as demostrated i the followig code excerpt, which sets this attribute: public static fial Strig USER = user ; public void setemployee(httpservletrequest request, Object employee) { request.getsessio(true).setattribute(user, employee); } The SigICotroller class validates the logi ad also sets the Employee domai object usig the ApplicatioSecurityMaager.setEmployee method, as show ext: Employee formemployee = (Employee) commad; Employee dbemployee = (Employee) commad; if ((dbemployee = employeemaager.getemployee(formemployee.getemployeeid())) == ull) errors.reject( error.logi.ivalid ); else applicatiosecuritymaager.setemployee(request, dbemployee); Our SigOutCotroller class sigs the user out by removig the Employee attribute from the sessio, as show here: applicatiosecuritymaager.removeemployee(request); Note Our applicatio uses a miimal idex.jsp file, which will serve as our welcome file; this is placed uder our src/web directory ad forwards the request to the our sigi.htm URL, as show here: <c:redirect url= sigi.htm /> Our Sample Applicatio i Actio! Now that we have our web user-iterface compoets (cotroller ad view) ad our model code developed, we have a completely fuctioal applicatio that ca be built, deployed, ad test drive! For example, we ca ow type at deploy o the commad lie ad have it (hot) deploy to our Tomcat webapps directory. After deploymet, the applicatio ca be accessed from a web browser usig a URL such as http://localhost:8080/timex/. Figures 7.9 through 7.11 show our screes i actio.
156 Chapter 7 The Sprig Web MVC Framework Figure 7.9 Sig I scree. Figure 7.10 Timesheet List scree.
Our Sample Applicatio i Actio! 157 Figure 7.11 Eter Hours scree. Persoal Opiio: Desigig ad Codig with Iterfaces The Sprig referece documetatio ad may articles o the web recommed desigig ad codig with iterfaces. Sprig supports both iterface-based ad class-based beas. You might have oticed i Time Expressio s class desig that I have ot used Java iterfaces. This is related to my philosophy o whe ad where to use iterfaces. Let me start out by sayig that I like programmig with Java iterfaces a lot! However, similar to the way may people jumped o the EJB badwago a few years ago, I see people jumpig o the iterface badwago recetly. So, allow me to share my thoughts o this matter; you may agree or disagree with them. I would like to begi by tellig you a little story o the topic of desigig ad codig with iterfaces. I have bee usig iterfaces sice 1996 ad love the cocept behid them. I 1997, I developed a 100% pure Java-based backup software amed BackOlie (http://visualpatters.com/backolie/). This product was metioed i several well-kow trade jourals ad wo a Best Cliet award at JavaOe; it was eve omiated by Scott McNealy (CEO, Su Microsystems) for a Computerworld-Smithsoia award. BackOlie is a cliet-server product; the server is a multithreaded ad multiuser server that essetially receives the files ad stores them usig a implemetatio class for a iterface amed DataStore. The DataStore iterface has FTP-like methods, such as get, put, ope, close, ad so o; these, had to be implemeted by cocrete classes. The BackOlie software (which is o loger beig sold) came prepackaged with two default DataStore implemetatio classes, DataStoreFileSystem ad DataStoreJDBC (the fully qualified implemetatio class ames were specified i a cofiguratio file ad dyamically loaded at rutime). DataStoreFileSystem essetially used the java.io package to store the files usig the local file system. DataStoreJDBC used JDBC to store the file cotets as Biary Large Objects (BLOBs) i a relatioal database.
158 Chapter 7 The Sprig Web MVC Framework I provided Javadoc ad additioal techical documetatio for the DataStore iterface, so Iteret Service Providers (ISPs) ad products vedors who siged a OEM (origial equipmet maufacturer) with my compay could write their ow custom implemetatios, if ecessary. For example, a ISP might have wated to take advatage of the ative operatig system s features, such as exteded file permissios. For the BackOlie example I just wet through, usig iterfaces was a obvious choice. Also, may times I fid that iterfaces work well for lower-level APIs, such as the oe I described for BackOlie or oes you fid i frameworks such as the JDK or the Sprig Framework (for example, java.util. Collectios or java.sql.coectio). Furthermore, iterfaces are great, if you thik the uderlyig implemetatio ca chage (such as loggig, autheticatio service, ad OS specific fuctioality). Of course, with remote techologies (EJB, for example), you have o choice but to use iterfaces. For busiess applicatios, more times tha ot, especially o smaller projects, I have foud that you eed oly oe implemetatio of domai (busiess) objects or service objects (such as the TimesheetMaager class for Time Expressio). Furthermore, it does t make sese to have iterfaces for domai objects (such as Timesheet.java, for example). Creatig oe iterface file for each implemetatio class amouts to uecessary overhead, i my opiio. For large projects, this ca amout to lots of extra.java (ad.class) files without potetially addig much value. O the flip side, there are times whe usig iterfaces makes sese. For example, i Chapter 2, we discussed multiple user types (roles) for the Time Expressio applicatio, such as Employee, Maager, ad Executive. These could easily be created as cocrete classes that implemet a iterface amed Perso or Role. O the other had, give the commo behavior i these objects, a abstract class would also make a lot of sese because the commo methods could be pulled up ito a super (paret) class (called Perso, for example). I summary, give the right opportuity, you should use iterfaces but do ot use them because it has bee preached i some book or article as the right thig to do. Furthermore, you should ot feel at fault for ot usig iterfaces for each ad every cocrete class you write. Focus more o havig a soud desig for your applicatio for example, clea separatio of layers, good database desig, easy-tofollow code, appropriate use of architecture/desig patters, ad so o. I hope I do ot soud dismissive about iterfaces because that is certaily ot my itetio; my poit is to use everythig i moderatio ad appropriately. New Tag Libraries i Sprig Framework 2.0 At the time of this writig, the Sprig team was gettig close to releasig additioal tag libraries to make it simpler to work with Sprig with JSP. However, the desig of these ew tag libraries was still evolvig, so I was uable to cover this with accuracy. A Word About Sprig Web Flow ad Portlet API Two additioal user-iterface Sprig techologies might be of iterest to you, if you have the eed for features they provide.
Summary 159 Sprig Web Flow Sprig Web Flow, based o similar cocepts as Sprig Web MVC Framework, essetially provides wizardlike scree fuctioality to implemet a busiess process. Good examples of such applicatios iclude a olie shoppig site such as amazo.com, which requires you to go through several screes before the trasactio is cosidered complete.this type of fuctioality requires sessio/state maagemet, which provides the capability to go back ad forth through the screes without losig the iformatio you have already etered.this is precisely the type of fuctioality Web Flow eases. However, our applicatio,time Expressio, does ot require such a feature ad would ot be a good example for the Sprig s Web Flow. Eve though Web Flow is ot covered i this book, give the scope of this book, I highly recommed that you give this techology a serious look if your requiremets call for this type of fuctioality. Sprig Portlet API The Sprig Portlet API is a ew additio to Sprig 2.0. It essetially implemets the JSR-168 Portlet Specificatio defied o the Java Commuity Process (JCP) website (http://www.jcp.org/e/jsr/detail?id=168). Accordig to this, the Portlet API ca be used for Portal computig addressig the areas of aggregatio, persoalizatio, presetatio ad security. Aother way to look at this is that portlets are part of a portal website, which might cotai several portlets. Portlets are differet from servlets i that they do ot redirect or forward ay requests from or to the browser; istead, they are maaged by a portlet cotaier. If you are iterested i this API, you should check out the JCP website. Also, you might wat to check out Apache s Pluto, a referece implemetatio for the Portlet API. Summary I this chapter, we Looked at the various beefits of usig Sprig MVC Took a i-depth look at the Sprig Web MVC Framework Built three of the screes i Time Expressio usig Sprig MVC: oe as a oform scree, the others as form screes We covered a lot material i this chapter, but we are t doe with Sprig just yet. I the ext few chapters, we will touch o various additioal facets of the Sprig Framework, icludig The Sprig IDE plug-i for Eclipse Job Schedulig Emailig
160 Chapter 7 The Sprig Web MVC Framework Meawhile, if you wat to dig ito more Sprig, take a look at Sprig s JPetstore example ad Referece Documetatio, both part of the Sprig distributio software. I the ext chapter, we will look at Eclipse, which will completely chage the way we have bee workig i this book! I other words, we will chage from commad-lie programmig to a sophisticated Itegrated Developmet Eviromet (IDE), which will make codig, uit testig, ad debuggig much easier i short, agile Java developmet! Recommeded Resources The followig websites are relevat to or provide additioal iformatio o the topics discussed i this chapter: Websites for competig techologies to oes discussed i this chapter: Apache Jakarta Tapestry http://jakarta.apache.org/tapestry/ Apache Jakarta Turbie http://jakarta.apache.org/turbie/ Apache Struts http://struts.apache.org/ Apache Tapestry http://jakarta.apache.org/tapestry/ Apache Tomcat http://tomcat.apache.org/ Apache Tomcat atijarlockig ad atiresourcelockig cofiguratio attribute http://tomcat.apache.org/tomcat-5.5-doc/cofig/ cotext.html#stadard%20implemetatio Apache Tomcat At Tasks http://tomcat.apache.org/tomcat-5.0-doc/catalia/ docs/api/org/apache/catalia/at/package-summary.html Apache Velocity http://jakarta.apache.org/velocity/ FreeMarker http://www.freemarker.org/ JavaServer Faces http://java.su.com/j2ee/javaserverfaces/ Jetty Servlet Cotaier http://jetty.mortbay.org/jetty/ Mock Objects http://mockobjects.com OpeSymphoy WebWork http://www.opesymphoy.com/webwork/ Sprig Discussio Forums http://forum.sprigframework.org/ Sprig Framework http://sprigframework.org The origial MVC http://heim.ifi.uio.o/~trygver/themes/mvc/ mvc-idex.html