490 likes | 736 Views
Objectives: 1. Understand MVC and Struts 2 Architecture 2. Analyze Page-centric and Servlet-centric Designs 3. Develop JSP Interactive Interfaces. Struts 2 Architecture and Overview. Topics. Introduction to Struts 2 Model-View-Controller Architecture
E N D
Objectives: 1. Understand MVC and Struts 2 Architecture 2. Analyze Page-centric and Servlet-centric Designs 3. Develop JSP Interactive Interfaces Struts 2 Architecture and Overview
Topics • Introduction to Struts 2 • Model-View-Controller Architecture • Struts and MVC • Architecting Web Applications • Page-centric Design • Servlet-centric Design • JSP Interactive Interfaces • FormBean
Struts Classic Project • Combines JSPs and Servlets • Targets a Model-View-Controller (MVC) Architecture • Conceived by Craig McClanahan in May 2000 • Support by Application Servers • BEA • GlassFish • JBoss • Apache’s Tomcat
Struts 2 • Apache Project • Based on OpenSymphonyWebWork framework • Implements MVC • Takes advantage of the lessons learned from Struts Classic to present a cleaner implementation of MVC • New Features • Interceptors • Annotation-based Configuration • and more…
Other Web ApplicationFrameworks • Stripes • Cocoon • Echo • Nacho • Spring MVC • JBanana • WebWork (now Struts 2) • many others…
What is a Web Application Framework? A web application framework is a piece of structural software that provides automation of common tasks of the domain as well as a built- in architectural solution that can be easily inherited by applications implemented on the framework.
Common Tasks of the Web Application • Binding Request Parameters to Java Types • Validating Data • Making calls to business logic • Making calls to the data layer • Rendering presentation layer (HTML, …) • Providing internationalization and localization
Struts 2 Project • Keep Presentation Layer Separate from Data Layer • Model-View-Controller Architecture • Model (Struts 2: action) • Represents the Data Objects • View (Struts 2: result) • Screen representation of the Model • Controller (Struts 2: FilterDispatcher) • How the user interface reacts to the user’s input
Advantages of MVC • Reliability • High Reuse and Adaptability • Low Development Costs • Rapid Deployment • Maintainability
MVC Architecture Goals View Controller Model
Applying MVC to WebApplications • View: • HTML form; native Java interface; client-side script; applet • Controller: • Java servlet; session Bean • Model: • Entity Bean or other business logic object
Interchangeable Elements • View: • HTML form becomes touch-screen • Controller: • JSP becomes session bean • Model: • Entity Bean
MVC and GUIs • Views and Controllers closely interact (HTML/JSP) • If HTML code is written out entirely through JSP, the Controller and View (conceptually) merge • A Controller-View pair works with one Model • One Model may have multiple Controller-View pairs
MVC Advantages • Single point of entry to Model object • Multiple-client support • Design clarity • Modularity • Controlled growth • Portable
Struts 2 and MVC • To support MVC, struts uses: • JSPs • Custom JSP Tags • Java Servlets • POJOs for Actions
Struts 2 and MVC request FilterDispatcher (Controller) View
Struts 2 and MVC • Controller - FilterDispatcher • Front Controller pattern • Maps Requests to Actions • Servlet Filter that inspects each incoming request to determine which Struts 2 action should handle the request.
Struts 2 and MVC FilterDispatcher (Controller) Action 1 Action 2 ActionInvocation Action 3 Action 4
Struts 2 and MVC Action 1 Action 2 Models Action 3 Action 4
Struts 2 and MVC Action 1 Action 2 ActionInvocation Action 3 Action 4
Struts 2 and MVC ActionInvocation View
Struts 2 and MVC • The Struts 2 solution to implementing MVC • View – JSP Page, Velocity, XSLT, RIA, AJAX • Controller – FilterDispatcher in conjunction with user-defined Action classes • Model – Action classes is a locus of data transfer, a single unit of work that conducts calls to the business logic
Designing Web Applications • High Level Architecture Presentation Layer Control Layer Application Logic Data Sources
Architectural Approaches • Page-centric Design • Model 1 • Control and application Logic handled by JSP • Servlet-centric Design • Model 2 • Intermediate servlet ( or servlets ) manage control and application logic
Page-Centric Design • Series of interrelated JSP pages • JSP page • Perform request processing • Communicate with back-end data sources • Generate dynamic content elements
Page-centric Program Flow • Role-based Pages Options.jsp Query.jsp Display.jsp Data Sources
Simple page-centric application • Password.htm <HTML> <BODY> <form action="PasswordGen.jsp" method="POST"> <H3>Welcome to the Password Generator</H3> First Name: <input type="text" name="firstName"><br> Last Name: <input type="text" name="lastName"><br> <p> <input type="submit" value="Generate Password"> </form> </BODY> </HTML>
Simple page-centric application • PasswordGen.jsp <html> <body> <% String firstName = request.getParameter("firstName"); String lastName = request. getParameter("lastName"); String password; if( (firstName.length()>=2) && (lastName.length()>=2)) password = lastName.substring(0,2)+firstName.substring(0,2); else password = "NoGo"; %> <h1> Password Generated! </h1> Your super secret password is <%= password %>. <br><a href="Password.htm">To generate another password.</a> </body> </html>
Page-centric Strategy • Page-centric approach Benefits • Very little abstraction • Few components • Minimum of layers • Page-centric approach Limitations • Maintainability • Flow Control
Servlet-centric Design • Servlet handles control and application logic • Requests are routed to the JSP pages via the servlet • Servlet can perform the following: • Execution of specific business actions on behalf of a JSP • Deliver data to a JSP • Control flow among JSP pages
Command Pattern • Encapsulate each command our servlet can handle into its own class String cmd = req.getParameter(“cmd”); if (cmd.equals(“buy”)) { BuyCmd bcmd = new BuyCmd(); bcmd.buy(); } if (cmd.equals(“sell”)) { SellCmd scmd = new SellCmd(); scmd.sell(); }
Servlet-centric Program Flow Data Sources Client Servlet JSP
Simple Servlet-centric application • Password.htm <HTML> <BODY> <form action="/webapp/passwordservlet" method="POST"> <H3>Welcome to the Password Generator</H3> First Name: <input type="text" name="firstName"><br> Last Name: <input type="text" name="lastName"><br> <p> <input type="submit" value="Generate Password"> </form> </BODY> </HTML>
Simple Servlet-centric application • passwordServlet.java public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { GenBean gb = new GenBean(); gb.setFirstName(request.getParameter("firstName")); gb.setLastName(request.getParameter("lastName")); gb.generate(); request.setAttribute("gen", gb); RequestDispatcher rd = getServletContext().getRequestDispatcher("/PasswordGen.jsp"); rd.forward(request, response); }
Simple Servlet-centric application • GenBean.java public class GenBean { private String firstName; private String lastName; private String password = "NoGo"; public String getFirstName(){return firstName;} public void setFirstName(String fn){ firstName = fn;} public String getLastName(){return lastName;} public void setLastName(String ln){ lastName = ln;} public String getPassword(){return password;} public String generate() { if( (firstName.length() >= 2) && (lastName.length() >= 2)) password = lastName.substring(0,2) + firstName.substring(0,2); return password; } }
Simple Servlet-centric application • PasswordGen.jsp <html> <body> <jsp:useBean id = "gen" class = “genpackage.GenBean" scope="request"/> <h1> Password Generated! </h1> Your super secret password is <jsp:getProperty name="gen" property="password"/> <br><a href="Password.htm">To generate another password.</a> </body> </html>
Interactive Interfaces using JSP • Creating Web-based applications that exhibit behavior of desktop programs • Must address the stateless nature of Web pages and Form elements • Sticky Widgets • Validation
Dynamically Generated HTML • Use HTML form elements in Web applications • State is encoded into the HTML typically as value attributes or the checked keyword • To maintain state • Cookies with JavaScript • Dynamically generated HTML with JSP • Create a JSP that combines the form and results on the same page • Use with Model 1 approach
Sticky Widget Example:Text Fields • Text Field state is defined in the value attribute <input type=“text” name=“desc” value=“<%= getParam(request, “desc”) %>”> public String getParam(HttpServletRequest req, String param) { if (req.getParameter(param) == null) return “”; else return req.getParameter(param); }
Sticky Widget Example:Radio Buttons • Radio Button state is defined by the checked keyword <input type=“radio” name=“binary” value=“yes” <%= isChecked(request,“binary”,“yes”) %>>Yes<br> <input type=“radio” name=“binary” value=“no” <%= isChecked(request,“binary”,“no”) %>>No<br> public String isChecked(HttpServletRequest req, String param, String testValue) { return testValue.equals(req.getParameter(param)) ? “checked” : “”; }
Validating Form Data • Client-Side • Performed with JavaScript • User is prohibited from submitting form until validated • Server-Side • Request data not guaranteed to come from browser • Use JSP sticky widgets to maintain state in case of input error • Performance not as good
Form Bean • More streamlined technique for communicating the state of form data within a specific request • Allows for Model 2 approach public class FormBean { private String name; public void setName(String nm) { name = nm; } public String getName() { return name; } … }
Review • Introduction to Struts • Model-View-Controller Architecture • Struts and MVC • Architecting Web Applications • Page-centric Design • Servlet-centric Design • JSP Interactive Interfaces • FormBean