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.
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
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
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 .
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.
• 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.
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,
public class HelloWorld extends HttpServlet {
server invokes t he previousl y compil ed servl et obj ect . If t he source has
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
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 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
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
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.
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.
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>
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>
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;
5. LoginAct ion Source (LoginAct ion. j ava) public final class LogonAction extends Action { // Validate credentials with business tier
public boolean isUserLogon (String username, String password) throws UserDirectoryException {
// Obtain username and password from web tier
String username = ((LogonForm) form).getUsername();
catch (UserDirectoryException ude) {// couldn't connect to user directory ActionErrors errors = new ActionErrors();
// 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);
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
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