Escolar Documentos
Profissional Documentos
Cultura Documentos
Struts
Agenda
Introduction to MVC What is a Framework Struts Overview Struts Components Struts Flow Implementation of View Sample Codes Important Points Struts Positives and Negatives Conclusion
Struts 2
Introduction to MVC
Model View Controller Architecture Layered Approach to Designing Web Applications Model - Data contained in the Application - Core of the Application functionality - User Interface of the Application
View
Controller
Servlet
Application Framework
EJB JDO CORBA
Model
Get JavaBean
View
Struts
Storage
What is a Framework?
A framework is a set of classes and interfaces that cooperate to solve a specific type of software problem.
A good framework should provide generic behavior that can be utilized across many different types of applications.
Struts 5
What is Struts?
Open Source Jakarta Project (package: struts.jar) Started in May 2000 by Craig McClanahan Current Version : 1.1 Final Version released. A Presentation Layer Framework MVC Implementation Combines two of the Most Popular server-side technologies JSPs and Servlets into a Server-Side Implementation of MVC design pattern. Supported by all the major app. Servers, BEA, Sun, Jakarta- Tomcat etc.
Struts
Why struts?
Http Centric Model Neutral Support for Internationalization(i18N Support) Centralized Configuration of Application flow Open Source with Strong
Developer Community Vendor Community Product Support. Well Documented Stable Release
Struts
7 contd
Avoid Java code (scriptlets) in the html. To separate page designer and Java Programmers roles. High Reuse and adaptability. Separation of Presentation and business logic makes it easier to maintain and modify.
Struts
Struts Implementation
Populates
Accesses
Event
Controller
ActionServlet
Http Request
Business logic
Action
Client Browser
Forward
web.xml
Creates/Sets struts-config.xml
View
JSP
Get <Tag>
Struts
Model
JavaBean
Struts
10
Struts-Flow
1 the client submits an HTML form, do*** method is called to allow the the HtppServlet ActionServlet to handle the POST request 1.1 The Struts Controller ActionServlet delegates to RequestProcessor the process of the request RequestProcessor does the following actions :
1.1.1 retrieve and return the ActionForm bean associated with the mapping, creating one if necessary 1.1.2 populates the ActionForm bean with the input fields of the HTML form 1.1.3 validates the input field values and creates error messages if validation errors 1.1.4 acquires an UserAction instance to process the request, calling the overwritten execute method of UserAction
1.1.4.1 retrieves data from the UserActionForm bean by getProperties methods 1.1.4.2 calls business services through the BusinessDelegate 1.1.4.3 populates a value object bean (optional) 1.1.4.4 forwards to the specified destination in struts-config.xml
The forwarded page retrieves data from :
2 the HelperBean
Struts
11
Implementation of Controller
ActionServlet - Struts Supplied. - All client Requests go through here. - Automatically populates a JavaBean (ActionForm) with request parameters. - Determines which Action or JSP to dispatch to. Action - User Defined. - Must extend org.apache.struts.action.Action. - Override the execute() method. - Coordinates with Business Layer. - Gets data and determines which view to render next.
Struts 12
Struts
14
ActionErrors -Collection of ActionError Objects -Each Error Object holds a message key -These Errors are passes back to the input form for display to the user
eg.
ActionErrors errors = new ActionErrors(); errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("error.logon.invalid")); saveErrors(request,errors);
Struts 15
struts-config.xml
Struts Application Configuration File. Placed in WEB-INF folder of the application. Contains the Configuration data to hook all the pieces together. Maps Form events to Action Classes. Maps HTML Forms to ActionForm classes. Introduces a level of indirection to isolate the back-end code (Actions and JSPs). Four main types of information:
Contd
Struts 16
struts-config.xml
1. Bean Declarations - Used by ActionServlet Controller when it automatically populates the ActionForm. - Tells the controller where to physically locate the referenced ActionForm. 2. Action Mappings - Defines a mapping between a logical Action name and physical action class (path, type). - Specifies an associated ActionForm (name). - Declares the input page (input) to return to if errors occur. - Defines local forwards (forward tag).
Struts 17 Contd
struts-config.xml
3. Global Forwards - Level of Indirection (path change has to be updated at one place). 4. Message Resource Bundle Declaration - Internationalization. e.g. ApplicationResources_it.properties will be used for an Italian speaking client where it represents the two letter ISO language code. - Tells where to find application.properties.
Struts 18
Sample struts-config.xml
<struts-config> <form-beans> <form-bean name=LogonForm type=app.LogonForm/> </form-beans> <global-forwards type="org.apache.struts.action.ActionForward"> <forward name=Login" path="/Login.jsp redirect="false" /> </global-forwards> <action-mappings> <action path="/LogonSubmit" type="app.LogonAction" name="logonForm" scope="request" validate="true" input="/pages/Logon.jsp"> <forward name="success" path="/pages/Welcome.jsp"/> </action> </action-mappings> <message-resources parameter="resources.application"/> <plug-in className="com.infosys.sample.PlugIn.InitPlugIn"/> </struts-config>
Struts 19
Web.xml
Identify as web application descriptor- The first two lines identify the file as web application descriptor
Configure the action servlet This block tells the container to load the ActionServlet under the name action. Four parameters are passed to the ActionServlet : application config debug detail Identify Struts requests This block tells the container to forward any file requests matching the pattern *.do to the action servlet. Configuring Tag Libraries The tag libraries used in the application are configured here. Struts 20
Struts
22
2. On Controller Servlet loading - As the ActionServlet is loading,it searches for the struts-config.xml file. - struts-config.xml file contains the configuration information for the behavior of the Servlet itself.It contains the associations between the Struts Components. - As the ActionServlet reads struts-config.xml,it begins to create and register struts based classes which we have designed and mentioned in the file.It places them in memory associated with a lookup name. The Servlet is now ready to react to requests
Struts
23
3.After Servlet Controller has been loaded: - User sends out an URI request from the browser e.g.: http://localhost:7001/Logon.do - The ActionServlet would ideally be configured to respond to any URI request that matches a particular String (for e.g.: any URI that ends with .do). - The ActionServlet will strip off the .do and will try to look up an Action Class by matching the remaining un-stripped string e.g.:/Logon
Struts
24
- The ActionServlet now uses this looked up class(of type Action) to process request. - A different request with a different URL ending could have called upon a different Action class to perform a different function. - The controller will create only a single instance of each Action Class for the application.Hence,it must be ensured that all the Action Classes operate properly in a multithreaded environment.
Struts
25
- If an ActionForm instance of the appropriate scope and type is present for this new request, then re-use it. - Otherwise, create a new instance and store it in the appropriate scope. - The reset() method is called on the ActionForm instance. - Iterate through the request parameters and populate their values in the ActionForm using the corresponding Set-Method. - After the user data is loaded into the ActionForm(view bean),the validate() method is automatically called. - If no validation problems,the controller will proceed to call the execute() method of the appropriate Action class.
Struts
26
- If there are validation problems,an instance of ActionErrors is returned that contains the error message keys that should be displayed. -The actual values for the error message keys are mentioned in the applications MessageResource bundle. -The controller stores the ActionErrors collection as a request attribute suitable for use by the <html:errors/> tag and Will forward control to the input form(identified by the input property for this ActionMapping).
Struts
27
- The execute() method of the Action class a)does all What To Do functions b)Calls whatever model classes it needs to call to perform the actual business validations & operations (How to Do) c)finally looks up or creates an ActionForward object which it returns. - An ActionForward object contains the destination URI. - The Controller then forwards/redirects the resulting destination URI to the user.
Struts
28
Implementation of View
struts Taglibraries
Use of standard Struts taglibs to have greater code re-use and easier maintenance:
- Bean
-
: to access javabeans and resources Logic : manages conditions HTML: creates input forms Template: original page templating system Nested: lets base tags relate to each other Tiles : new advanced templating system
contd 29
Bean Tags:
<bean:message> Outputs a message stored in a resource bundle. Provides a mechanism for Internationalization E.g.: <bean:message key=label.entername/> <bean:write> Outputs a value from the given bean. Provides formatting attribute E.g: <bean:write name=entityBean property=name/> <bean:define> Define a scripting variable based on the value(s) of the specified bean property Some others: cookie, header, size, parameter, include etc.
Struts
contd 30 ...
Logic Tags:
Conditional statements to determine output text. <logic:equal> Evaluate the nested body content of this tag if the requested variable is equal to the specified value. e.g.<logic:equal name=entityBean property=variable value=1/> <logic:iterate> Allows looping over collections E.g.<logic:iterate name=collection id="list" indexId="index> Other important and useful logic tags are: empty, notEmpty, greaterThan, lessThan, lessThan, present, match, forward, redirect etc.
Struts 31
HTML Tags:
Used to create input forms. Tags are available for all of the HTML form input types. E.g. button, checkbox, image, select, option, password, radio, reset, text, textarea, link, submit etc. Sample Code: Note:The actual HTML available to client shows normal input tags. E.g. <html:text property=strLoginId/> will be available to client as <input type="text" name="strLoginId>
Templates Tags:
Templates are JSP pages that include parameterized content. That content comes from put tags that are children of insert tags. e.g. Get, Put and Insert Tags
Struts 32 contd
Handling Inputs
HTML Forms :
The html tags in struts usually only work within the context of an html:form tag. For example:
<html:form action="/LogonAction.do" scope="session"> </html:form>
Struts
33
Struts
34
Struts
35
Logon.jsp
<%@ 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> Struts </HTML>
36
LogonForm.java
public final class LogonForm extends ActionForm { private String password = null; private String username = null; public String getPassword() { return (this.password); } public void setPassword(String password) { this.password = password; } public String getUsername() { return (this.username); } public void setUsername(String username) { this.username = username; } public void reset(ActionMapping mapping, HttpServletRequest request) { setPassword(null); setUsername(null); }
contd
Struts 37
LogonForm.java
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; } }
Struts
38
LogonAction.java
public final class LogonAction extends Action { public boolean isUserLogon(String username, String password){ if(username.equals("Naren") && password.equals("infosys")){ return true; } return false; } public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String username = ((LogonForm) form).getUsername(); String password = ((LogonForm) form).getPassword();
Struts
contd
39
LogonAction.java
boolean validated = false; validated = isUserLogon(username,password); if (!validated) { ActionErrors errors = new ActionErrors(); errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("error.logon.invalid")); saveErrors(request,errors); return (new ActionForward(mapping.getInput())); } return (mapping.findForward(Constants.SUCCESS)); } }
Struts 40
Struts
42
Struts: Positives
Ready to use Controller Servlet. Extensive JSP Tag libraries. Manage complexity in large applications. Free-to-use Open Source with extensive online support. Tested and tried Industry level standard. Struts automatically takes care of repopulating the form. Allows for multiple struts-config.xml files. Large development teams can work on same project. Avoids need to navigate through all pages to understand the flow of the application.
Struts 44
Struts Negatives
Increased Complexity of the system. Developer needs to be trained. Periodic changes to Struts source code. Overhead in case of small systems. An Open Framework No Vendor Support. Does not allow to have more than a limited number of tags in one JSP or the JSP size exceeding a limit (64K) needs R&D.
Struts 45
Conclusion
Model-View-Controller Implementation. Division of work between JSP and Java developers. Ideal for large web applications. Increased productivity and Code- Reuse. Effectively, the User develops a config file, JSP, Action Class and Action Form Bean.
Struts
46
Questions?
(We can discuss.)
Struts
47
Thanks
Struts
48