strut framework basics
TRANSCRIPT
25/01/54 1
Strut FrameworkBasics
225/01/54
Agenda
Introduction of MVC pattern Evolution of Web Application design
architectureModel 1Model 2Application frameworks
Apache Struts
325/01/54
MVC Pattern
425/01/54
Three Logical Layers in a WebApplication: Model Model (Business process layer)
Models the data and behavior behind the business process
Responsible for actually doing Performing DB queries Calculating the business process Processing orders
Encapsulate of data and behavior which are independent of presentation
525/01/54
Three Logical Layers in a WebApplication: View View (Presentation layer)Display information according to client
typesDisplay result of business logic (Model)Not concerned with how the information
was obtained, or from where (since that is the responsibility of Model)
625/01/54
Three Logical Layers in a WebApplication: Controller Controller (Control layer)
Serves as the logical connection between the user's interaction and the business services on the back
Responsible for making decisions among multiple presentations e.g. User's language, locale or access level dictates a
different presentation. A request enters the application through the control
layer it will decide how the request should be handled and what information should be returned
725/01/54
Evolution of MVC Architecture
No MVC MVC Model 1 (Page-centric) MVC Model 2 (Servlet-centric) Web application frameworks
Struts Standard-based Web application framework
JavaServer Faces (JSR-127)
825/01/54
Model 1 Architecture (Page-centric)
925/01/54
Page-centric Architecture
Composed of a series of interrelated JSP pages JSP pages handle all aspects of the application
presentation, control, and business process
Business process logic and control decisions are hard coded inside JSP pages in the form of JavaBeans, scriptlets, expression
Next page selection is determined by A user clicking on a hyper link, e.g. <A HERF="find.jsp> Through the action of submitting a form, e.g. <FORM ACTION="search.jsp">
1025/01/54
Page-centric Architecture
1125/01/54
Page-centric Scenario
1225/01/54
Model 2 Architecture (Servlet-centric)
1325/01/54
Why Model 2 Architecture?
What if you want to present different JSP pages depending on the data you receive? JSP technology alone even with JavaBeans and
custom tags (Model 1) cannot handle it well Solution
Use Servlet and JSP together (Model 2) Servlet handles initial request, partially process the
data, set up beans, then forward the results to one of a number of different JSP pages
1425/01/54
Servlet-centric Architecture
JSP pages are used only for presentation Control and application logic handled by a servlet (or set of
servlets) Servlet serves as a gatekeeper
Provides common services, such as authentication, authorization, login, error handling, and etc
Servlet serves as a central controller Act as a state machine or an event dispatcher to decide upon the
appropriate logic to handle the request Performs redirecting
1525/01/54
Servlet-centric Scenario
1625/01/54
Web Application Frameworks
Based on MVC Model 2 architecture Web-tier applications share common set of
functionalityDispatching HTTP requests Invoking model methodsSelecting and assembling views
Provide classes and interfaces that can be used/extended by developers
1725/01/54
Why Web Application Framework?
Built-in de-coupling of presentation tier and business logic into separate components
Provides a central point of control Provides rich set of features Facilitates unit-testing and maintenance Availability of compatible tools Provides stability Enjoys community-supports Simplifies internationalization Simplifies input validation
1825/01/54
Why Web Application Framework?
Frameworks have evolved with Java Server technologyJSP/Servlets are still hard to use
Frameworks define re-usable components to make this job easier.
A good framework defines how components work to create a usable application.
1925/01/54
Web Application Frameworks
Apache Struts JavaServer Faces (JSR-127)A server side user interface component
framework for JavaTM technology-based web applications
Echo Tapestry
2025/01/54
Apache Struts
Struts is an open source Web application framework developed as Apache Jakarta project http://jakarta.apache.org/struts/
Model-View-Controller (MVC) framework Used for constructing web applications based
Servlets and JSP technologies Struts application is a genuine Web application that
should be able to run on any Sevlet container including all JavaEE compliant App servers
2125/01/54
How Struts Works
2225/01/54
The controller components
2325/01/54
Sample Application Things to doCreating ActionForm object
Input validationCreating Action object
Forwarding at either success or failure through configuration set in struts-config.xml file
You can also build it using NetBeans
2425/01/54
Step by Step1. Create development directory structure2. Write web.xml3. Write struts-config.xml4. Write ActionForm classes5. Write Action classes6. Create ApplicationResource.properties7. Write JSP pages8. Build, deploy, and test the application
2525/01/54
Step 1: Create DevelopmentDirectory Structure Same development directory structure for
any typical Web application Ant build script should be written
accordingly If you are using NetBeans, the
development directory structure is automatically created
2625/01/54
Step 2: Write web.xmlDeployment Descriptor Same structure as any other Web application
ActionServlet is like any other servlet Servlet definition and mapping of ActionServlet
needs to be specified in the web.xml There are several Struts specific
<init-param> elements Location of Struts configuration file
Struts tag libraries could be defined
2725/01/54
Example: web.xml1.<?xml version="1.0" encoding="UTF-8"?>2.<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://java.sun.com/xml/ns/j2eehttp://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">3. <servlet>4. <servlet-name>action</servlet-name>5. <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>6. <init-param>7. <param-name>config</param-name>8. <param-value>/WEB-INF/struts-config.xml</param-value>9. </init-param>10. ...11. </servlet>12. <servlet-mapping>13. <servlet-name>action</servlet-name>14. <url-pattern>*.do</url-pattern>15. </servlet-mapping>
2825/01/54
Step 3: Writestruts-config.xml Identify required input forms and then define
them as <form-bean> elements Identify required Action's and then define them
as <action> elements within <action-mappings>elementmake sure same value of name attribute of <form-
bean> is used as the value of name attribute of <action> element
define if you want input validation Decide view selection logic and specify them as
<forward> element within <action> element
2925/01/54
struts-config.xml: <form-beans>1.<?xml version="1.0" encoding="UTF-8" ?>2.<!DOCTYPE struts-config PUBLIC3."-//Apache Software Foundation//DTD Struts Configuration
1.2//EN"4."http://jakarta.apache.org/struts/dtds/struts-
config_1_2.dtd">
5.<struts-config>6. <form-beans>7. <form-bean name="submitForm"8. type="submit.SubmitForm"/>9. </form-beans>
3025/01/54
struts-config.xml: <action mappings>
10. <!-- ==== Action Mapping Definitions ==============-->11. <action-mappings>12. <action path="/submit"13. type="submit.SubmitAction"14. name="submitForm"15. input="/submit.jsp"16. scope="request"17. validate="true">18. <forward name="success" path="/submit.jsp"/>19. <forward name="failure" path="/submit.jsp"/>20. </action>21. </action-mappings>s
3125/01/54
Step 4: Write ActionForm classes Extend org.apache.struts.action.ActionForm
class Decide set of properties that reflect the input
form Write getter and setter methods for each
property Write validate() method if input validation is
desired
3225/01/54
Write ActionForm class1.package submit;2.import javax.servlet.http.HttpServletRequest;3.import org.apache.struts.action.*;4.public final class SubmitForm extends ActionForm {5. /* Last Name */6. private String lastName = "Hansen"; // default value7. public String getLastName() {8. return (this.lastName);9. }10. public void setLastName(String lastName) {11. this.lastName = lastName;12. }13. /* Address */14. private String address = null;15. public String getAddress() {16. return (this.address);17. }18. public void setAddress(String address) {19. this.address = address;20. }21....
3325/01/54
Write validate() method22. public ActionErrors validate(ActionMapping mapping,23. HttpServletRequest request) {24. // Check for mandatory data25. ActionErrors errors = new ActionErrors();26. if (lastName == null || lastName.equals("")) {27. errors.add("Last Name", new 28. ActionError("error.lastName"));29. }30. if (address == null || address.equals("")) {31. errors.add("Address", new ActionError("error.address"));32. }33. if (sex == null || sex.equals("")) {34. errors.add("Sex", new ActionError("error.sex"));35. }36. if (age == null || age.equals("")) {37. errors.add("Age", new ActionError("error.age"));38. }39. return errors;40. }41. ...
3425/01/54
Step 5: Write Action classes
Extend org.apache.struts.action.Actionclass
Handle the requestDecide what kind of server-side Model objects
(EJB, JDO, etc.) can be invoked
Based on the outcome, select the next view
3525/01/54
Example: Action Class1.package submit;2.import javax.servlet.http.*;3.import org.apache.struts.action.*;4.public final class SubmitAction extends Action {5. public ActionForward execute(ActionMapping mapping,6. ActionForm form,7. HttpServletRequest request,8. HttpServletResponse response) {9. SubmitForm f = (SubmitForm) form; // get the form bean10. // and take the last name value11. String lastName = f.getLastName();12. // Translate the name to upper case13. //and save it in the request object14. request.setAttribute("lastName", lastName.toUpperCase());15.16. // Forward control to the specified success target17. return (mapping.findForward("success"));18. }19.}
3625/01/54
Step 6: CreateApplicationResource.properties and Configure web.xml accordingly
1.errors.header=<h4>Validation Error(s)</h4><ul>2.errors.footer=</ul><hr>3.error.lastName=<li>Enter your last name4.error.address=<li>Enter your address5.error.sex=<li>Enter your sex6.error.age=<li>Enter your age
Example: ApplicationResource.properties
3725/01/54
Step 7: Write JSP pages
Write one JSP page for each view Use Struts tags forHanding HTML input formsWriting out messages
3825/01/54
Example:submit.jsp1. <%@ page language="java" %>2. <%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>3. <%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>4. <%@ taglib uri="/WEB-INF/struts-logic.tld" prefix="logic" %>5. <html>6. <head><title>Submit example</title></head>7. <body>8. <h3>Example Submit Page</h3>9. <html:errors/>10. <html:form action="submit.do">11. Last Name: <html:text property="lastName"/><br>12. Address: <html:textarea property="address"/><br>13. Sex: <html:radio property="sex" value="M"/>Male14. <html:radio property="sex" value="F"/>Female<br>15. Married: <html:checkbox property="married"/><br>16. Age: <html:select property="age">17. <html:option value="a">0-19</html:option>18. <html:option value="b">20-49</html:option>19. <html:option value="c">50-</html:option>20. </html:select><br>21. <html:submit/>22.</html:form>
3925/01/54
Example: submit.jsp (cont.)...
23. <logic:present name="lastName" scope="request">24. Hello25. <logic:equal name="submitForm" property="age" value="a">26. young27. </logic:equal>28. <logic:equal name="submitForm" property="age" value="c">29. old30. </logic:equal>31. <bean:write name="lastName" scope="request"/>32.</logic:present>33.</body>34.</html>
4025/01/54
Step 8: Build, Deploy,and Test Application
4125/01/54
Accessing Web Application
4225/01/54
Acknowledgement
Most contents are borrowed from thepresentation slides of Sang Shin, Java™Technology Evangelist, Sun Microsystems,Inc.