INTRODUCTION TO STRUTS Presentation by NEELIMA MULAMPAKA 2008
INTRODUCTION TO STRUTS Presentation by NEELIMA MULAMPAKA 2008 Spring Class – CSI 668 1
STRUTS - Agenda n n n History Application Framework Model-View-Controller Design Pattern Struts Architecture How Struts Works Major Struts Components The Big Picture Strengths And Weaknesses A Simple Application References Assignment 2
History n n Struts is hosted by the Apache Software Foundation (ASF) as part of its Jakarta Project. The primary architect and developer of the Struts framework is Craig R. Mc. Clanahan. MVC-based (Model-View-Controller) open source software Used for constructing web applications using Servlets and JSPs Why is it called Struts ? 3
Framework n n n Is a reusable, semi-complete application that can be specialized to produce custom applications. Application frameworks build on a common ground to provide developers with a reusable structure that can serve as the foundation for their own products. Provides developers with a set of backbone components. 4
Common Framework Strategies Java web application frameworks use several common techniques to help make products easier to design, write, and maintain. Some common components: n External configuration files. n A central controller n External presentation systems n 5
Framework Components 6
Model-View-Controller 7
MVC-based Architecture § 3 Major Components in Struts § § § Servlet controller (Controller) Java Server Pages or any other presentation technology (View) Application Business Logic in the form of whatever suits the application (Model) The centerpiece of Struts is MVC style controller. Struts is focused on Controller Struts is Model and View independent 8
Controller Is the switch board of MVC architecture n Every request goes through the controller n Responsible for flow control (action mapping) of the request handling n Reads configuration file to determine the flow control n 9
Controller Components in Struts Framework Major Struts classes as they relate to MVC n Action. Servlet - The part of the Controller that receives user gestures and state changes and issues view selections n Action. Mapping - The state change event n Action. Form - The data for a state change n Action. Class - The part of the Controller that interacts with the model to execute a state change or query and advises the Action. Servlet of the next view to select n Action. Forward - A user gesture or view selection 10
How Struts Works 11
Struts Flow (Struts 1. 0) 12
Struts View Helpers Tag Library Descriptor Purpose § struts-html. tld JSP tag extension for HTML forms § struts-bean. tld JSP tag extension for handling Java. Beans § struts-logic. tld JSP tag extension for testing the values of properties 13
The Big Picture 1. 2. 3. 4. 5. 6. 7. 8. 9. Struts request-response process A client requests a path that matches the Action URI pattern. The container passes the request to the Action. Servlet. If this is a modular application, the Action. Servlet selects the appropriate module. The Action. Servlet looks up the mapping for the path. If the mapping specifies a form bean, the Action. Servlet sees if there is one already or creates one. If a form bean is in play, the Action. Servlet resets and populates it from the HTTP request. If the mapping has the validate property set to true, it calls validate on the form bean. If it fails, the servlet forwards to the path specified by the input property and this control flow ends. 14
The Big Picture(contd) 10. 11. 12. 13. 14. 15. If the mapping specifies an Action type, it is reused if it already exists or instantiated. The Action’s perform or execute method is called and passed the instantiated form bean (or null). The Action may populate the form bean, call business objects, and do whatever else is needed. The Action returns an Action. Forward to the Action. Servlet. If the Action. Forward is to another Action URI, we begin again; otherwise, It’s off to a display page or some other resource. Most often, it is a JSP. 15
The Big Picture 16
What Does Action. Servlet Do? § § § Performs the role of Controller Process user requests Determine what the user is trying to achieve according to the request Pull data from the model (if necessary) to be given to the appropriate view, and Select the proper view to respond to the user Delegates most of this grunt work to Action classes 17
Action. Servlet(contd) n n Invoking Action. Servlet One of the standard servlet settings is the servlet mapping. The container uses this setting to decide which requests are sent to which servlet: <servlet-mapping> <servlet-name>action</servlet-name> <url-pattern>*. do</url-pattern> </servlet-mapping> 18
Action. Servlet(contd) n Action. Servlet is configured in the web. xml <servlet> <servlet-name>action</servlet-name> <servlet-class> org. apache. struts. action. Action. Servlet </servlet-class> </servlet> 19
Action. Mapping (You provide it) n n Action Mapping is configured in Struts Config File Each action element has requires the following attributes to be defined: n n n path: The application context-relative path to the action type: The fully qualified java classname of your Action class name: The name of your <form-bean> element to use with this action 20
Action. Mapping(contd) <action-mappings> <action path="/submit" type="hansen. playground. Submit. Action" name="submit. Form" input="/submit. jsp" scope="request" validate="true"> <forward name="success" path="/submit. jsp"/> <forward name="failure" path="/submit. jsp"/> </action-mappings> 21
Action. Form (You provide it) n n n n n Provided by developer Define an Action. Form bean (that is, a Java class extending the Action. Form class) for the input form Extend Struts-provided Action. Form class Define it in servlet-config. xml file <form-bean> name attribute of <Action> class Contains only property getter and property setter methods for each field-no business logic Provides standard validation mechnism 22
Action. Form(contd) <form-beans> <form-bean name="submit. Form" type="hansen. playground. Submit. Form"/> </form-beans> 23
How to write Action. Form Bean n n Add just getter and setter methods for each property of a input form Do not include any business logic code Add a standard validation method Controller will call this validation Define a property (with associated get. Xxx and set. Xxx methods) for each field that is present in the form 24
Action Class n n n Focus on control flow Process client request by calling other objects (Business. Logic beans) inside its execute() method Returns an Action. Forward object that identifies where control should be forwarded JSP Another Action 25
execute(. . ) method of Actionclass (Struts 1. 1 only) n n Invoked by controller Function Signature public Action. Forward execute( Action. Mapping mapping, Action. Form form, Http. Servlet. Request request, Http. Servlet. Response response) throws Exception; 26
Action. Forward - View n n n Action. Forward object tells Servlet controller which JSP page is to be dispatched to JSP pages use Action. Form beans to get output Model data to display Struts contains a series of tag libraries Facilitates communication between HTML designers and developers Facilitates dynamic Web content 27
Struts Configuration (strut-config. xml) It is like a Blueprint of your Application. n Lot of information collected in one place. n Every component in the struts configuration is a java object n 28
Struts Configuration(contd) A very simple application could create all of these informational objects in an initialization method and then set each object to the default values needed. For example: Action. Forward logoff = new Action. Forward(); logoff. set. Name("logoff"); logoff. set. Path("/Logoff. do"); Action. Forward logon = new Action. Forward(); logoff. set. Name("logon"); 29 logoff. set. Path("/Logon. do"); n
Struts-config. xml <? xml version="1. 0" encoding="ISO-8859 -1" ? > <!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1. 1//EN“ "http: //jakarta. apache. org/struts/dtds/strutsconfig_1_1. dtd"> <struts-config> <!-- == Form Bean Definitions == --> <form-beans> <form-bean name="submit. Form" type="hansen. playground. Submit. Form"/> </form-beans> 30
Struts-config. xml(Contd) <!-- == Action Mapping Definitions == --> <action-mappings> <action path="/submit" type="hansen. playground. Submit. Action" name="submit. Form" input="/submit. jsp" scope="request“ validate="true"> <forward name="success“path="/submit. jsp"/> <forward name="failure" path="/submit. jsp"/> </action-mappings> </struts-config> 31
Validation Indicate you want input validation as attributes of <action> element under <action-mapping> in strut-config. xml file – validate=”true” n Specify the JSP page that needs to be displayed when validation fails input=”/errorpage. jsp” n Override validate() method within Action. Form class – optional n 32
struts-config. xml: Validation n Example <action-mappings> <action path="/submit" type="hansen. playground. Submit. Action" name="submit. Form" input="/submit. jsp" scope="request" validate="true"> <forward name="success" path="/submit. jsp"/> <forward name="failure" path="/submit. jsp"/> </action-mappings> </struts-config> 33
Strengths HTTP-centric n Standard logging n Lightweight n Open source n Strongly founded in design patterns n 34
Weaknesses Logging n Loads a single configuration file per application n Single Action. Servlet n Requires understanding of Struts components n 35
A Simple Application n n Simple user registration application. Registration screen Three Fields -username, password, and confirmation password. A successful registration requires that the two passwords match. If the registration is successful, control flows to a page that says successful!. If the two passwords do not match, control flows to a page that says failure. 36
Create The Action. Form package app; import org. apache. struts. action. *; public class Register. Form extends Action. Form { protected String username; protected String password 1; protected String password 2; public String get. Username () {return username; } public String get. Password 1() {return password 1; } public String get. Password 2() {return password 2; } public void set. Username (String username) {this. username = username; } public void set. Password 1(String password) {this. password 1 = password; } public void set. Password 2(String password) {this. password 2 = password; } } 37
Creating the Register. Action package app; import org. apache. struts. action. *; import javax. servlet. http. *; import java. io. *; public class Register. Action extends Action { public Action. Forward perform (Action. Mapping mapping, Action. Form form, Http. Servlet. Request req, Http. Servlet. Response res) { // b Cast the form to the Register. Form rf = (Register. Form) form; String username = rf. get. Username(); String password 1 = rf. get. Password 1(); String password 2 = rf. get. Password 2(); 38
Creating the Register. Action(contd) // c Apply business logic if (password 1. equals(password 2)) { try { // d Return Action. Forward for success User. Directory. get. Instance(). set. User(username, password 1); return mapping. find. Forward("success"); } catch (User. Directory. Exception e) { return mapping. find. Forward("failure"); } } // E Return Action. Forward for failure return mapping. find. Forward("failure"); } } 39
Creating the Struts configuration file (strutsconfig. xml) <? xml version="1. 0" encoding="ISO-8859 -1" ? > <!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1. 0//EN" "http: //jakarta. apache. org/struts/dtds/strutsconfig_1_0. dtd"> <struts-config> <form-beans> <form-bean name="register. Form" type="app. Register. Form"/> </form-beans> <action-mappings 40
Creating the Struts configuration file (strutsconfig. xml)(contd) <action path="/register" type="app. Register. Action" name="register. Form" input="/register. jsp"> <forward name="success" path="/success. html"/> <forward name="failure" path="/failure. html"/> </action-mappings> </struts-config> 41
References Struts In Action By Ted Husted n Jakarta Struts By O’Reilly n 42
Assignment The application you are going to create mimics entering an employee into a database. The user will be required to enter an employee's name and age. 43
QUESTIONS ? ? NEELIMA MULAMPAKA nm 121262@albany. edu 44
- Slides: 44