Applying a Model/View/Controller Pattern in J2EE Platform Using Struts Framework.

(1)

Using Struts Framework

Niko Ibrahim

Jur usan Si st em Inf or masi

Fakul t as Teknol ogi Inf or masi , Uni ver si t as Kr i st en Mar anat ha Jl . Pr of . Dr g. Sur i a Sumant r i No. 65 Bandung 40164

Emai l : ni ko. i br ahi m@gmai l . com

Abstrak

Pol a desain Model / Vi ew/ Cont r ol l er (MVC), yang j uga dikenal dengan Model -2 pada pemrograman J2EE, adal ah pol a desain yang t el ah mapan dal am dunia pemrograman. Pol a ini t el ah dit erapkan sebagai pemodel an yang sanggup memisahkan berbagai komponen dal am suat u apl ikasi. Dal am pemrograman Web, pol a desain MVC ini dapat membant u para pemrogram unt uk mengkont rol perubahan pada apl ikasi yang dibuat nya. Hal ini disebabkan karakt erist ik pol a desain MVC yang sanggup memisahkan ant armuka dari l ogika program (busi ness r ul e) sert a dari dat a (dat abase) yang digunakan. Pada st udi l it erat ur ini akan dibahas dasar-dasar dari MVC dan penerapannya dal am mengembangkan apl ikasi Web berbasis Java. Pol a desain MVC yang dibahas disini adal ah yang berbasis open sour ce yang dikenal dengan nama St r ut s f r amewor k.

Kat a kunci: Model / vi ew/ cont r ol l er , Open sour ce, St r ut s f r amewor k

1. Introduction

The Int ernet has revol ut ionized our business by providing an inf ormat ion highway, which act s as a new f orm of communicat ion backbone [ Nag03] . This new inf ormat ion medium has shif t ed business f rom t he t radit ional inf rast ruct ures t o a virt ual worl d where t hey can serve cust omers anyt ime and anywhere. Addit ional l y, it enhances our organizat ions wit h signif icant benef it s in t erms of business product ivit y, cost savings, and cust omer sat isf act ion. As a resul t , modern organizat ions are required t o re-eval uat e t heir business model s and pl an on a business vision t o int eract wit h t heir st akehol ders using an Int ernet -based t echnol ogy space.

Wit h respect t o Int ernet -based t echnol ogy, modern organizat ions need t o devel op t heir web-based business appl icat ions which have a set of f undament al el ement s [ Bro03] : business obj ect s, process-orient ed or service-based obj ect s, and user int eract ion component s. For exampl e, in banking indust ry, businesses deal wit h dif f erent ent it ies al l of t he t ime. These range f rom higher-l evel ent it ies such as a cust omer t o l ower l evel s


(2)

such as deposit and wit hdrawal . These ent it ies share a number of common charact erist ics:

• Behaviors

• Propert ies

• Rel at ionships wit h ot her ent it ies

• Rul es or pol icies

Those business ent it ies are of course t he f oundat ion of obj ect -orient ed design and devel opment which undoubt edl y is a key aspect in any J2EE appl icat ion devel opment .

2. Application Design Using MVC Pattern

Much discussion and conf usion have been rel ayed in t he l it erat ure about what best approaches in devel oping compl ex business web appl icat ions. Any business appl icat ions wil l need t o incorporat e t hree primary el ement s [ Bro03] :

• User int eract ion

• Business Process

• Business Ent it ies

The st ruct ure and rel at ionship of t hese el ement s is shown in Figure 1.

Figure 1: T he St ruct ure of a Business Applicat ion

Ref erred t o a current research in IBM [ Tai04] , as web appl icat ion grow in size, it becomes more and more crit ical t o support modul ar appl icat ion design and paral l el devel opment . It al so needs t o support t he int egrat ion of various kinds of programming t echnol ogies.


(3)

2. 1. The Model/ View/ Controller Architectural Pattern

Model / View/ Cont rol l er archit ect ural design is proj ect ed t o hel p devel opers modul arise an appl icat ion. The benef it of using t he MVC pat t ern is t hat devel opers isol at e t he dif f erent port ions of t he appl icat ion in order t o provide great er f l exibil it y and more opport unit y f or reuse. A primary isol at ion point is bet ween t he present at ion obj ect s and t he appl icat ion back-end obj ect s t hat manage t he dat a and business rul es. This al l ows a user int erf ace t o have many dif f erent screens t hat can be changed t o a l arge degree wit hout impact ing t he business l ogic and dat a component s [ Bro03] [ Tai04] [ Lef 01] .

Figure 2 shows how t he Model , t he View, and t he Cont rol l er int eract wit h one anot her in J2EE pl at f orm:

Figure 2: MVC archit ect ure f or Java applicat ions Some of t he maj or benef it s of using t he MVC are [ Goo04] :

Reliability: The present at ion and t ransact ion l ayers have cl ear separat ion, which al l ows we t o change t he l ook and f eel of an appl icat ion wit hout recompil ing Model or Cont rol l er code.

High reuse and adapt abilit y: The MVC l et s we use mul t ipl e t ypes of views, al l accessing t he same server-side code. This incl udes anyt hing f rom Web browsers (HTTP) t o wirel ess browsers (WAP).

Very low development and lifecycle costs: The MVC makes it possibl e t o have l ower-l evel programmers devel op and maint ain t he user int erf aces.

Rapid deployment: Devel opment t ime can be signif icant l y reduced, because Cont rol l er programmers (Java devel opers) f ocus sol el y on t ransact ions, and View programmers (HTML and JSP devel opers) f ocus sol el y on present at ion.

B

R

O

W

S

E

R

Controller

View

Model


(4)

Maint ainability: The separat ion of present at ion and business l ogic al so makes it easier t o maint ain and modif y a St rut s-based Web appl icat ion.

T he Model

The model encapsul at es t he f unct ional core of an appl icat ion, it s business l ogic. The goal of MVC is t o make t he model independent of t he view and cont rol l er which t oget her f orm t he user int erf ace of t he appl icat ion. An obj ect may act as t he model f or more t han one MVC t riad at a t ime.

Since t he model must be independent , it cannot ref er t o eit her t he view or cont rol l er port ions of t he appl icat ion. The model may not hol d direct inst ance variabl es t hat ref er t o t he view or t he cont rol l er. It passivel y suppl ies it s services and dat a t o t he ot her l ayers of t he appl icat ion [ Tai04] . T he View

The view obt ains dat a f rom t he model and present s it t o t he user and represent s t he out put of t he appl icat ion. It general l y has f ree access t o t he model , but shoul d not change t he st at e of t he model . Views are read onl y represent at ions of t he st at e of t he model and read dat a f rom t he model using query met hods provided by t he model

T he Cont roller

The cont rol l er component isol at es how a user’ s act ions on t he screen are handl ed by t he appl icat ion. This al l ows f or an appl icat ion design t o f l exibl y handl e t hings such as page navigat ion and access t o t he f unct ional it y provided by t he appl icat ion model in t he case of f orm submissions. This al so provides an isol at ion point bet ween t he model and t he view. Because t he cont rol l er component handl es t he user request s and invokes f unct ions on t he model as necessary, it al l ows f or a more l oosel y coupl ed f ront and back end. Int eract ion bet ween t he model and t he view is onl y t hrough an event -based mechanism t hat inf orms t he view of changes t o t he model ’ s dat a [ Bro03] .

3. J2EE Plat form

The J2EE pl at f orm specif ies t echnol ogies t o support mul t it ier ent erprise appl icat ions. These t echnol ogies f al l int o t hree cat egories: component , service, and communicat ion. The component t echnol ogies are t hose used by devel opers t o creat e t he essent ial part s of t he ent erprise appl icat ion, namel y t he user int erf ace and t he business l ogic. The component t echnol ogies al l ow t he devel opment of modul es t hat can be reused by mul t ipl e ent erprise appl icat ions. The component t echnol ogies are support ed by J2EE pl at f orm’ s syst em-l evel services. These syst em-l evel services simpl if y appl icat ion programming and al l ow component s t o be cust omized t o use resources avail abl e in t he environment in which t hey are depl oyed [ Sin02] .


(5)

Since most ent erprise appl icat ions require access t o exist ing ent erprise inf ormat ion syst ems, t he J2EE pl at f orm support s APIs t hat provide access t o dat abases, ent erprise inf ormat ion syst ems such as SAP and CICS, and services such as t ransact ion, naming and direct ory, and asynchronous communicat ion. Final l y, t he J2EE pl at f orm provides t echnol ogies t hat enabl e communicat ion bet ween cl ient s and servers and bet ween col l aborat ing obj ect s host ed by dif f erent servers.

Figure 3 shows t he basic archit ect ure of J2EE pl at f orm:

Figure 3: Basic J2EE Archit ect ure 3. 1. The Client Tier

From a devel oper’ s point of view, a J2EE appl icat ion can support many t ypes of cl ient s. J2EE cl ient s can run on l apt ops, deskt ops, pal mt ops, and cel l phones. They can connect f rom wit hin an ent erprise’ s int ranet or across t he Worl d Wide Web, t hrough a wired net work or a wirel ess net work or a combinat ion of bot h. They can range f rom somet hing t hin, browser-based and l argel y server-dependent t o somet hing rich, programmabl e, and l argel y sel f -suf f icient .

From a user’ s point of view, t he cl ient is t he appl icat ion. It must be usef ul , usabl e, and responsive. Because t he user pl aces high expect at ions on t he cl ient , we must choose our cl ient st rat egy caref ul l y, making sure t o


(6)

consider bot h t echnical f orces (such as t he net work) and non-t echnical f orces (such as t he nat ure of t he appl icat ion) [ Bro03] .

3. 2. The Web Container

A t ypical Java Web appl icat ion consist s of a col l ect ion of JavaServl et s and JSPs t hat run inside a J2EE server’ s Web cont ainer. The cont ainer manages each component ’ s l if ecycl e, dispat ches service request s t o appl icat ion component s, and provides st andard int erf aces t o cont ext dat a such as session st at e and inf ormat ion about t he current request . [ Bro03] .

JavaServl et s and JSPs are depl oyed in t he Web cont ainer and t ypical l y perf orms t he f ol l owing f unct ions in a J2EE appl icat ion:

• Web-enabl es business l ogic - t hey manage int eract ion bet ween Web cl ient s and appl icat ion business l ogic.

• Generat es dynamic cont ent - t hey generat e cont ent dynamical l y, i n ent irel y arbit rary dat a f ormat s, incl uding HTML, images, sound, and video.

• Present s dat a and col l ect s input - t hey t ransl at e HTTP PUT and GET act ions int o a f orm t hat t he business l ogic underst ands and present resul t s as Web cont ent .

• Cont rol s screen f l ow - The l ogic t hat det ermines which “ screen” (t hat is, which page) t o displ ay next usual l y resides in t hese component s, because screen f l ow t ends t o be specif ic t o cl ient capabil it ies.

• Maint ains st at e - t hey have a simpl e, f l exibl e mechanism f or accumul at ing dat a f or t ransact ions and f or int eract ion cont ext over t he l if et ime of a user session.

• Support s mul t ipl e and f ut ure cl ient t ypes - Ext ensibl e MIME t ypes describe Web cont ent , so a Web cl ient can support any current and f ut ure t ype of downl oadabl e cont ent .

• May impl ement business l ogic - Whil e many ent erprise appl icat ions impl ement business l ogic in ent erprise beans, Web-onl y, l ow- t o medium-vol ume appl icat ions wit h simpl e t ransact ional .

Java Servlet s

A Java Servl et is a Java cl ass t hat ext ends a J2EE-compat ibl e Web server. Each servl et cl ass produces dynamic cont ent in response t o service request s t o one or more URLs.

Servl et s of f er some import ant benef it s over earl ier dynamic cont ent generat ion t echnol ogies. Servl et s are compil ed Java cl asses, so t hey are general l y f ast er t han CGI programs or server-side script s. Servl et s are saf er t han ext ension l ibraries, because t he Java Virt ual Machine (JVM) can recover f rom a servl et t hat exit s unexpect edl y. Servl et s are port abl e bot h at t he source-code l evel (because of t he Java Servl et specif icat ion) and at t he binary l evel (because of t he innat e port abil it y of Java byt ecode). Servl et s al so provide a richer set of st andard services t han any ot her widel y adopt ed server ext ension t echnol ogy.


(7)

Figure 4 shows a Java Servl et s t hat print s “ Hel l o Worl d” in a browser.

Figure 4: A “ Hello World” Java Servlet

JavaServer Pages (JSP)

Most Web appl icat ions produce primaril y dynamic HTML pages t hat , when served, change onl y in dat a val ues and not in basic st ruct ure. For exampl e, al l of t he cat al og pages in an onl ine st ore may have ident ical st ruct ure and dif f er onl y in t he it ems t hey displ ay. JSP t echnol ogy exist s f or producing such cont ent [ Rod03] [ Bro03] .

A JSP page is a document cont aining f ixed t empl at e t ext , pl us special markup f or incl uding ot her t ext or execut ing embedded l ogic. The f ixed t empl at e t ext is al ways served t o t he request er j ust as it appears in t he page, l ike t radit ional HTML. The special markup can t ake one of t hree f orms: direct ives, script ing el ement s, or cust om t ags (al so known as “ cust om act ions” ) [ Sin02] .

Figure 5 shows a JSP page t hat print s a “ Hel l o Worl d in a browser:

Figure 5: A “ Hello World” JSP

The f irst t ime t he JSP f il e is request ed, it is t ransl at ed int o a servl et and t hen compil ed int o an obj ect t hat is l oaded int o resident memory. The generat ed servl et t hen services t he request , and t he out put is sent back t o t he request ing cl ient . On al l subsequent request s, t he server checks t o see whet her t he original JSP source f il e has changed. If it has not changed, t he

import java.io.*;

import javax.servlet.*; import javax.servlet.http.*;

public class HelloWorld extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException

{

PrintWriter out = response.getWriter(); out.println("Hello World");

} }

<html>

<hody> <p>

<%= "Hello, world!" %> </p>

</body> </html>


(8)

server invokes t he previousl y compil ed servl et obj ect . If t he source has changed, t he JSP engine re-parses t he JSP source. The st eps are as f ol l ow (Figure 5):

1) Cl ient request s a JSP page

2) The JSP Engine compil es t he JSP int o a Servl et 3) The generat ed servl et is compil ed and l oaded

4) The compil ed servl et services t he request and sends a response back t o t he cl ient

Figure 6: T he execut ion of a Java servlet

4. Development Frameworks

Frameworks, l ike many t hings, are of t en born out of necessit y. In t he process of creat ing mul t ipl e appl icat ions, devel opers discover t hat t here are some areas of f unct ional it y t hat are common. These areas are t hen abst ract ed and general ized t o f orm t he f eat ures of t he f ramework.

Frameworks provide benef it at many dif f erent l evel s of appl icat ion devel opment [ Sin02] [ Goo04] :

• St ruct ure: f rameworks provide a st ruct ure f or appl icat ion devel opment - a backbone t o buil d f rom, making t he devel opment process a l it t l e easier. They ensure t hat our proj ect incl udes al l of t he key el ement s such as securit y, dat abase access, UI, and so f ort h by providing an out l ine int o which t he det ail s of our part icul ar appl icat ion are f il l ed.

• Services: a f ramework provides a wide array of services t o it s appl icat ions, f or use in bot h t he devel opment and depl oyment phases. These services very of t en begin wit h eit her a component cont ainer, or access t o a component cont ainer provided by t he appl icat ion server.

• Compl et eness: using a f ramework can expand t he horizons sl ight l y: if adding some of t he "nice t o have" f unct ional it y does not cost any

Web Server

2

3 Web

Browser

JSP Page

Generated Servlet

Compiled Servlet

1

4

Request


(9)

addit ional t ime, we can end up wit h a richer, more compl et e appl icat ion t hat is comparat ivel y more pol ished t han it coul d have been wit hout t he f ramework.

An appl icat ion f ramework is dif f icul t t o creat e. It is dif f icul t , not so much because t he code is dif f icul t t o writ e, or t hat t here is a l arge amount of code. Indeed, many ent erprise appl icat ions have several t imes more code t han t he f rameworks t hat hel ped creat e t hem. The code of a f ramework is of t en compl ex; however, proper design hel ps t o make it underst andabl e. This compl exit y, t hough, is not t he reason f or f rameworks being so dif f icul t t o creat e. The dif f icul t y l ies in obt aining t he experience t hat is dist il l ed int o t hem. Frameworks evol ve f rom t he ef f ort t o reuse bot h design and code, and f rom repeat ed ref act oring t hat resul t s in widel y appl icabl e services and component s. This is what is dif f icul t about t heir creat ion. Because f rameworks t end t o be l arge and f airl y compl ex pieces of sof t ware, t hey are of t en not a cost -ef f ect ive proj ect f or a singl e organizat ion. It is al so a good t hing when a part icul ar f ramework is used in many proj ect s - it grows, it becomes a de f act o st andard t o a degree, and t he organizat ions using it get t he benef it s. Al l of t hese f act ors mean t hat f rameworks are good candidat es f or open-source proj ect s, and indeed many of t he best f rameworks are open source.

4. 1. Overview of Struts Frameworks

The most widel y adopt ed MVC f ramework is t he open source Apache St rut s (ht t p: / / j akart a. apache. org/ st rut s/). St rut s was original l y writ t en by Craig McCl anahan, t he main devel oper of t he Tomcat servl et engine, and was rel eased in mid 2000, making it t he l ongest -est abl ished open source web appl icat ion f ramework. Part l y because of it s rel at ivel y l ong hist ory, St rut s has achieved remarkabl e buy-in by devel opers, wit h many add-ons now avail abl e around it [ Goo04] .

St rut s provides key capabil it ies t o t he devel oper f or buil ding virt ual l y any Web appl icat ion - especial l y t hose t hat make use of JSP pages as t heir user int erf ace t echnol ogy. St rut s can, however, int eract wit h many ot her present at ion t echnol ogies t hat incl ude XML/ XSLT [ Nas03] .

The primary el ement s of St rut s are [ Bro03] :

• A cont rol l er Act ionServl et t hat delegat es specif ic request handl ing t o Act ion cl asses

• An ext ensive JSP cust om t ag l ibrary


(10)

The basic St rut s archit ect ure is shown in Figure 6:

Figure 6: T he basic St rut s archit ect ure

In f igure 6, we can see t hat t he St rut s cont rol l er l ayer has a component cal l ed Act ions. Act ion is essent ial l y a Java cl ass t hat is responsibl e f or examining inf ormat ion f rom t he request , perf orming some operat ion, opt ional l y popul at ing dat a t hat wil l l at er be used by t he view l ayer, and t hen communicat ing t o t he Act ionServl et where cont rol shoul d be f orwarded next .

4. 2. Benefits and Issues of Struts Framework

St rut s addresses a gap in t he J2EE t echnol ogical st ack not covered by Servl et / JSP or EJB. St rut s shoul d be one of t he t op choices when we are considering t he adopt ion of an MVC f ramework due t o it s numerous benef it s. However, despit e of t he benef it s of St rut s, we shoul d al so consider some issues of using it [ Rod03] .

The f ol l owing are some benef it s of using St rut s:

Use of JSP tag mechanism

The t ag f eat ure promot es reusabl e code and abst ract s Java code f rom t he JSP f il e. This f eat ure al l ows nice int egrat ion int o JSP-based devel opment t ool s t hat al l ow aut horing wit h t ags.

Tag library

St rut s provides devel opers wit h an ext ensive range of t ag l ibrary.

Open source

We have al l t he advant ages of open source, such as being abl e t o see t he code and having everyone el se using t he l ibrary reviewing t he code. Many eyes make f or great code review.

Manage the problem space

Divide and conquer is a nice way of sol ving t he probl em and making t he probl em manageabl e.

Controller

Client

Browser

Servlet

ActionServlet

Business

Logic

Model

Application

View

JSP

Event

HTTP

Request

Dispatch

Forward

Update

HTTP

Response

Get

<tag>

struts-config.xml

Access


(11)

The f ol l owing are some issues of using St rut s t hat might be considered by devel opers:

Limited scope

St rut s is a Web-based MVC sol ut ion t hat is meant be impl ement ed wit h HTML, JSP f il es, and servl et s. Devel opers must be expert in J2EE pl at f orm if t hey int ended t o use St rut s in t heir devel opment phases.

Complexity

Separat ing t he probl em int o part s int roduces compl exit y. There is no quest ion t hat some educat ion wil l have t o go on t o underst and St rut s. Wit h t he const ant changes occurring, t his can be f rust rat ing at t imes.

4. 3. Example of Struts Application: Login

The purpose of t he l ogin appl icat ion is t o give a l ook at t he basic of a St rut s appl icat ion. To hel p us st ay on t rack, t his appl icat ion cont ains onl y t he component s needed t o demonst rat e t he f ramework. It cont ains no real business l ogic, unit t est s, or compl ex f orms.

Basical l y, t he appl icat ion has t wo screens: wel come and l ogin page (Figure 7).

Figure 7: Welcome and Login Page

The appl icat ion al so has a buil t -in val idat ion mechanism t hat check an empy input . Final l y, right af t er t he users l ogged in, t hey wil l be redirect ed t o t he Wel come page (Figure 8).


(12)

Figure 8: Login Page (validat ion) and Redirect ed Welcome Page

We put al l t he source code in t he appendix A f or space-saving purposes. We al so draw t he UML diagram f or t he l ogin process in t he appendix B. The source code f or t he exampl e appl icat ion may al so be obt ained f rom t he aut hor.

Conclusions and Suggest ions

We have discussed t hat J2EE is used f or devel oping, depl oying, and execut ing appl icat ions in a dist ribut ed environment . The J2EE appl icat ion server act s as a pl at f orm f or impl ement ing various server-side t echnol ogies such as servl et s, Java Server Pages (JSP), and Ent erprise JavaBeans. J2EE al l ows us t o f ocus on business l ogic in your programs. The business l ogic is coded in Ent erprise JavaBeans, which are reusabl e component s t hat can be accessed by cl ient programs.

Moreover, we al so t al ked about St rut s which sol ved some probl ems using t ags and Model / View/ Cont rol l er archit ect ure pat t ern. This approach aided in code re-usabil it y and f l exibil it y. By separat ing t he probl em int o smal l er component s, we wil l be more l ikel y t o reuse when changes do occur in t he t echnol ogy or probl em space. Addit ional l y, St rut s enabl ed page designers and Java devel opers t o f ocus on what t hey do best . Yet , t he t rade of f in increased robust ness impl ies an increase in compl exit y. St rut s is much more compl ex t han a simpl e singl e JSP page, but f or l arger syst ems St rut s act ual l y hel ps manage t he compl exit y.

As f inal words, we suggest t hat we may have a l ook at ot her f ramework t echnol ogies avail abl e in t he market . St rut s is not t he onl y f ramework t hat we can use f or devel oping Java Web appl icat ions. Recent l y, Sun Microsyst ems rel eased a new approach f or devel oping Web appl icat ions namel y JavaServer Faces (JSF). JSF has l earnt a l ot f rom St rut s al t hough it has not considerabl y mat ured yet .


(13)

Bibliography

Broemmer, D. (2003). J2EE Best Pr act i ces - Java Desi gn Pat t er ns, Aut omat i on, and Per f or mance. Canada : Wil ey Publ ishing, Inc.

Goodwil l , J. , & Hight ower, R. (2004). Pr of essi onal Jakar t a St r ut s. Canada : Wil ey Publ ishing, Inc.

Lef f , A. , & Rayf iel d, J. T. (2001). Web-Appl icat ion Devel opment Using t he Model / View/ Cont rol l er Design Pat t ern. Proc. IEEE Int er nat i onal Ent er pr i se Di st r i but ed Obj ect Comput i ng Conf er ence, Seat t l e, USA, 11: 118-127, IEEE.

Nagappan, R. , Skoczyl as, R. & Sriganesh, R. P. (2003). Devel opi ng Java Web Ser vi ces. Canada : Wil ey Publ ishing, Inc.

Nash, M. (2003). Java Fr amewor ks and Component s - Accel er at e Your Web Appl i cat i on Devel opment . Unit ed Kingdom : Cambridge Universit y Press.

Rod, J. (2003). Exper t One-on-One J2EE Desi gn and Devel opment . USA : Wil ey Publ ishing, Inc.

Singh, I. , St earns, B. , & Johnson, M. (2002). Desi gni ng Ent er pr i se Appl i cat i ons wi t h t he J2EETM Pl at f or m, 2nd Edi t i on. USA : Sun Microsyst ems, Inc.

Tai, H. , Mit sui, K. , Nerome, T. , Abe, M, Ono, K. & Hori, M. (2004). Model -driven devel opment of l arge- scal e Web appl icat ions. IBM Jour nal of Resear ch and Devel opment 48(5): 797-809.


(14)

Appendix A

The purpose of our l ogin appl icat ion is t o give a l ook at t he basic of a St rut s appl icat ion. To hel p us st ay on t rack, t his appl icat ion cont ains onl y t he component s needed t o demonst rat e t he f ramework. It cont ains no real business l ogic, unit t est s, or compl ex f orms.

1. The Wel come Screen

The f irst t ime we visit t he wel come screen, t here wil l be onl y one l ink, which reads, “ Sign in” (Figure A-1)

Figure A-1: Wel come Screen

The f ol l owing is t he JSP source code f or t he wel come screen:

<%@ taglib uri="/tags/struts-bean" prefix="bean" %> <%@ taglib uri="/tags/struts-html" prefix="html" %> <%@ taglib uri="/tags/struts-logic" prefix="logic" %> <HTML><HEAD><TITLE>Welcome World!!</TITLE><html:base/> </HEAD><BODY>

<logic:present name="user">

<H3>Welcome <bean:write name="user" property="username"/>!</H3> </logic:present>

<logic:notPresent scope="session" name="user"> <H3>Welcome World!</H3>

</logic:notPresent> <html:errors/> <UL>

<LI><html:link forward="logon">Sign in</html:link></LI> <logic:present name="user">

<LI><html:link forward="logoff">Sign out</html:link></LI> </logic:present></UL>

<IMG src='struts-power.gif' alt='Powered by Struts'> </BODY></HTML>


(15)

2. Login Screen

The l ogon screen submit s t he username and password, as you can see in f igure A-2.

When we submit t he f orm wit hout ent ering anyt hing, t he l ogin screen ret urns but wit h a message, l ike t he one shown in t he f igure A-3.

Figure A-2: Login Screen

Figure A-3: Login Screen wit h Val idat ion Messages

The f ol l owing is t he JSP source code f or t he Login Screen:

<%@ taglib uri="/tags/struts-html" prefix="html" %> <HTML><HEAD><TITLE>Sign in, Please!</TITLE></HEAD><BODY> <html:errors/>

<html:form action="/LogonSubmit" focus="username"> <TABLE border="0" width="100%">

<TR><TH align="right">Username:</TH>

<TD align="left"><html:text property="username"/></TD></TR> <TR><TH align="right">Password:</TH>

<TD align="left"><html:password property="password"/></TD></TR> <TR><TD align="right"><html:submit/></TD>

<TD align="left"><html:reset/></TD></TR> </TABLE></html:form></BODY></HTML>


(16)

3. The Login Form Source

When an HTML f orm is submit t ed, t he name-val ue coupl et s are caught by t he St rut s cont rol l er and appl ied t o an Act ionForm. The Act ionForm is a JavaBean wit h propert ies t hat correspond t o t he cont rol s on an HTML f orm. St rut s compares t he names of t he Act ionForm propert ies wit h t he names of t he incoming coupl et s. When t hey mat ch, t he cont rol l er set s t he propert y t o t he val ue of t he corresponding coupl et . Ext ra propert ies are ignored. Missing propert ies ret ain t heir def aul t val ue (usual l y nul l or f al se). Here are t he publ ic propert ies f rom our LogonForm:

private String password = null; public String getPassword() {

return (this.password); }

public void setPassword(String password) { this.password = password;

}

private String username = null; public String getUsername() {

return (this.username); }

public void setUsername(String username) { this.username = username;

}

4. Val idat ion Source

Here is t he val idat e met hod f rom our LogonForm. It checks t hat bot h f iel ds have somet hing ent ered int o t hem.

public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {

ActionErrors errors = new ActionErrors();

if ((username == null) || (username.length() < 1)) errors.add ("username",new

ActionError("error.username.required"));

if ((password == null) || (password.length() < 1)) errors.add("password", new

ActionError("error.password.required")); return errors;


(17)

5. LoginAct ion Source (LoginAct ion. j ava) import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.Action; import org.apache.struts.action.ActionError; import org.apache.struts.action.ActionErrors; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.action.ActionServlet; public final class LogonAction extends Action { // Validate credentials with business tier

public boolean isUserLogon (String username, String password) throws UserDirectoryException {

return (UserDirectory.getInstance().isValidPassword(username,password)); } // end isUserLogon

public ActionForward perform(ActionMapping mapping,ActionForm

form,HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException {

// Obtain username and password from web tier

String username = ((LogonForm) form).getUsername(); String password = ((LogonForm) form).getPassword(); // Validate credentials

boolean validated = false;

try { validated = isUserLogon(username,password); }

catch (UserDirectoryException ude) {// couldn't connect to user directory ActionErrors errors = new ActionErrors();

errors.add(ActionErrors.GLOBAL_ERROR,new ActionError("error.logon.connect")); saveErrors(request,errors);

// return to input page

return (new ActionForward (mapping.getInput())); }

// Save our logged-in user in the session, because we use it again later. HttpSession session = request.getSession();

session.setAttribute(Constants.USER_KEY, form); // Log this event, if appropriate

if (servlet.getDebug() >= Constants.DEBUG) {

StringBuffer message = new StringBuffer("LogonAction: User '"); message.append(username);

message.append("' logged on in session "); message.append(session.getId());

servlet.log(message.toString); }

// Return success

return (mapping.findForward (Constants.WELCOME)); } // end perform


(18)

6. Wel come Screen Af t er Users Logged In

Af t er a successf ul l ogin, t he wel come screen displ ays again, but wit h an added ‘ Sign Out ’ l ink (Figure A-4).

Figure A-4: Wel come Screen Revisit ed

The f ol l oging is t he Logof f Act ion. j ava source code:

public ActionForward perform(ActionMapping mapping,ActionForm form,HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException {

// Extract attributes we will need

HttpSession session = request.getSession(); LogonForm user = (LogonForm)

session.getAttribute(Constants.USER_KEY);

// Log this user off

if (user != null) {

if (servlet.getDebug() >= Constants.DEBUG) {

StringBuffer message = new StringBuffer("LogoffAction: User '");

message.append(user.getUsername());

message.append("' logged off in session "); message.append(session.getId());

servlet.log(message.toString()); }}

else {

if (servlet.getDebug() >= Constants.DEBUG) {

StringBuffer message = new StringBuffer("LogoffAction: User '");

message.append(session.getId()); servlet.log(message.toString()); }} // Remove user login

session.removeAttribute(Constants.USER_KEY);

// Return success

return (mapping.findForward (Constants.SUCCESS)); }} // end LogoffAction


(19)

Appendix B – The UML Diagram f or t he Login Process

1.3.5: forward

1.3.4: setPassword(pasword): void 1.3.3: setUsername(username): void 1.3.2: getPassword(): password 1.3.1: getUsername(): username

ActionServlet loginAction loginForm Welcome Page

Client accessing the login page

browser Struts Controller Struts ActionForm Struts View

1: submit

1.1: processLoginForm():loginForm // populate loginForm

1.2: validate(): ActionErrors 1.3.: createAction

2: getProperties

1

4


(1)

The purpose of our l ogin appl icat ion is t o give a l ook at t he basic of a

St rut s appl icat ion. To hel p us st ay on t rack, t his appl icat ion cont ains onl y

t he component s needed t o demonst rat e t he f ramework. It cont ains no real

business l ogic, unit t est s, or compl ex f orms.

1.

The Wel come Screen

The f irst t ime we visit t he wel come screen, t here wil l be onl y one l ink,

which reads, “ Sign in” (Figure A-1)

Figure A-1: Wel come Screen

The f ol l owing is t he JSP source code f or t he wel come screen:

<%@ taglib uri="/tags/struts-bean" prefix="bean" %> <%@ taglib uri="/tags/struts-html" prefix="html" %> <%@ taglib uri="/tags/struts-logic" prefix="logic" %> <HTML><HEAD><TITLE>Welcome World!!</TITLE><html:base/> </HEAD><BODY>

<logic:present name="user">

<H3>Welcome <bean:write name="user" property="username"/>!</H3> </logic:present>

<logic:notPresent scope="session" name="user"> <H3>Welcome World!</H3>

</logic:notPresent> <html:errors/> <UL>

<LI><html:link forward="logon">Sign in</html:link></LI> <logic:present name="user">

<LI><html:link forward="logoff">Sign out</html:link></LI> </logic:present></UL>

<IMG src='struts-power.gif' alt='Powered by Struts'> </BODY></HTML>


(2)

Using St rut s Framework (Niko Ibrahim)

2.

Login Screen

The l ogon screen submit s t he username and password, as you can see in

f igure A-2.

When we submit t he f orm wit hout ent ering anyt hing, t he l ogin screen

ret urns but wit h a message, l ike t he one shown in t he f igure A-3.

Figure A-2: Login Screen

Figure A-3: Login Screen wit h Val idat ion Messages

The f ol l owing is t he JSP source code f or t he Login Screen:

<%@ taglib uri="/tags/struts-html" prefix="html" %> <HTML><HEAD><TITLE>Sign in, Please!</TITLE></HEAD><BODY> <html:errors/>

<html:form action="/LogonSubmit" focus="username"> <TABLE border="0" width="100%">


(3)

When an HTML f orm is submit t ed, t he name-val ue coupl et s are caught by

t he St rut s cont rol l er and appl ied t o an Act ionForm. The Act ionForm is a

JavaBean wit h propert ies t hat correspond t o t he cont rol s on an HTML

f orm. St rut s compares t he names of t he Act ionForm propert ies wit h t he

names of t he incoming coupl et s. When t hey mat ch, t he cont rol l er set s t he

propert y t o t he val ue of t he corresponding coupl et . Ext ra propert ies are

ignored. Missing propert ies ret ain t heir def aul t val ue (usual l y nul l or f al se).

Here are t he publ ic propert ies f rom our LogonForm:

private String password = null; public String getPassword() {

return (this.password); }

public void setPassword(String password) { this.password = password;

}

private String username = null; public String getUsername() {

return (this.username); }

public void setUsername(String username) { this.username = username;

}

4.

Val idat ion Source

Here is t he val idat e met hod f rom our LogonForm. It checks t hat bot h f iel ds

have somet hing ent ered int o t hem.

public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {

ActionErrors errors = new ActionErrors();

if ((username == null) || (username.length() < 1)) errors.add ("username",new

ActionError("error.username.required"));

if ((password == null) || (password.length() < 1)) errors.add("password", new

ActionError("error.password.required")); return errors;


(4)

Using St rut s Framework (Niko Ibrahim)

5.

LoginAct ion Source (LoginAct ion. j ava)

import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.Action; import org.apache.struts.action.ActionError; import org.apache.struts.action.ActionErrors; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.action.ActionServlet; public final class LogonAction extends Action { // Validate credentials with business tier

public boolean isUserLogon (String username, String password) throws UserDirectoryException {

return (UserDirectory.getInstance().isValidPassword(username,password)); } // end isUserLogon

public ActionForward perform(ActionMapping mapping,ActionForm

form,HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException {

// Obtain username and password from web tier

String username = ((LogonForm) form).getUsername(); String password = ((LogonForm) form).getPassword(); // Validate credentials

boolean validated = false;

try { validated = isUserLogon(username,password); }

catch (UserDirectoryException ude) {// couldn't connect to user directory ActionErrors errors = new ActionErrors();

errors.add(ActionErrors.GLOBAL_ERROR,new ActionError("error.logon.connect")); saveErrors(request,errors);

// return to input page

return (new ActionForward (mapping.getInput())); }

// Save our logged-in user in the session, because we use it again later. HttpSession session = request.getSession();

session.setAttribute(Constants.USER_KEY, form); // Log this event, if appropriate

if (servlet.getDebug() >= Constants.DEBUG) {

StringBuffer message = new StringBuffer("LogonAction: User '"); message.append(username);

message.append("' logged on in session "); message.append(session.getId());

servlet.log(message.toString); }

// Return success

return (mapping.findForward (Constants.WELCOME)); } // end perform


(5)

Af t er a successf ul l ogin, t he wel come screen displ ays again, but wit h an

added ‘ Sign Out ’ l ink (Figure A-4).

Figure A-4: Wel come Screen Revisit ed

The f ol l oging is t he Logof f Act ion. j ava source code:

public ActionForward perform(ActionMapping mapping,ActionForm form,HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException {

// Extract attributes we will need

HttpSession session = request.getSession(); LogonForm user = (LogonForm)

session.getAttribute(Constants.USER_KEY);

// Log this user off

if (user != null) {

if (servlet.getDebug() >= Constants.DEBUG) {

StringBuffer message = new StringBuffer("LogoffAction: User '");

message.append(user.getUsername());

message.append("' logged off in session "); message.append(session.getId());

servlet.log(message.toString()); }}

else {

if (servlet.getDebug() >= Constants.DEBUG) {

StringBuffer message = new StringBuffer("LogoffAction: User '");

message.append(session.getId()); servlet.log(message.toString()); }} // Remove user login

session.removeAttribute(Constants.USER_KEY);

// Return success

return (mapping.findForward (Constants.SUCCESS)); }} // end LogoffAction


(6)

Appendix B – The UML Diagram f or t he Login Process

1.3.5: forward

1.3.4: setPassword(pasword): void 1.3.3: setUsername(username): void 1.3.2: getPassword(): password 1.3.1: getUsername(): username

ActionServlet loginAction loginForm Welcome Page

Client accessing the login page

1: submit

1.1: processLoginForm():loginForm // populate loginForm

1.2: validate(): ActionErrors 1.3.: createAction