topicstopics ... that xxx
Post on 15-Apr-2020
37 Views
Preview:
TRANSCRIPT
© Copyright UTS Faculty of Information Technology 2008 – JSP JSP-1
Faculty of Information Technology
Faculty of Information Technology
31242/32549Advanced Internet Programming
Model-View-Controller & DAO
V2.0
© Copyright UTS Faculty of Information Technology 2008 – JSP JSP-2
Faculty of Information Technology
Faculty of Information Technology
Topics
• Design issues
– Design patterns
• Model View Controller
• MVC with RequestDispatcher
• Data Access Object Pattern
© Copyright UTS Faculty of Information Technology 2008 – JSP JSP-3
Faculty of Information Technology
Faculty of Information Technology
Design issues
• We have seen how to develop
– Static web pages
– Dynamic web pages
• Using servlets & JSP
– Accessing databases
• Using JDBC
How do we put these together to make a simple application??
Solution: Use Design Patterns
© Copyright UTS Faculty of Information Technology 2008 – JSP JSP-4
Faculty of Information Technology
Faculty of Information Technology
Design Patterns
• Based on years of experience in developing applications
• The pattern bible: Gamma, E., R. Helm, R. Johnson, and J. Vlissides. 1995. Design Patterns: Elements of Reusable Object-Oriented Software. Addison-Wesley.
• See also:
– TheServerSide.com. “Patterns Repository.” Available at: www.theserverside.com/patterns
© Copyright UTS Faculty of Information Technology 2008 – JSP JSP-5
Faculty of Information Technology
Faculty of Information Technology
Sun Design Patterns-1
• Sun have categorisedseveral design patterns.
http://java.sun.com/blueprints/patterns/catalog.html
© Copyright UTS Faculty of Information Technology 2008 – JSP JSP-6
Faculty of Information Technology
Faculty of Information Technology
Sun Design patterns-2
• Business Delegate
– Reduce coupling between Web and EJB tiers
• Composite Entity
– Model a network of related business entities
• Data Access Object (DAO)
– Abstract and encapsulate data access mechanisms
• Fast Lane Reader
– Improve read performance of tabular data
• Front Controller
– Centralize application request processing
• Intercepting Filter
– Pre- and post-process application requests
© Copyright UTS Faculty of Information Technology 2008 – JSP JSP-7
Faculty of Information Technology
Faculty of Information Technology
Sun Design patterns-3
• Model-View-Controller – Decouple data representation, application behaviour, and presentation
• Service Locator– Simplify client access to enterprise business services
• Session Facade – Coordinate operations between multiple business objects in a workflow
• Transfer Object– Transfer business data between tiers
• Value List Handler– Efficiently iterate a virtual list
• View Helper– Simplify access to model state and data access logic
© Copyright UTS Faculty of Information Technology 2008 – JSP JSP-8
Faculty of Information Technology
Faculty of Information Technology
Popular Design patterns
• Most popular design patterns are combination of:
– MVC + Data Transfer Object + Data Access Object + Session Façade
– Useful toolset to run is Apache Struts
• http://jakarta.apache.org/struts/
– Another standard is Java Server Faces (JSF)
– Yet another is Spring MVC
© Copyright UTS Faculty of Information Technology 2008 – JSP JSP-9
Faculty of Information Technology
Faculty of Information Technology
Model View Controller
• http://java.sun.com/blueprints/patterns/MVC-detailed.html
© Copyright UTS Faculty of Information Technology 2008 – JSP JSP-10
Faculty of Information Technology
Faculty of Information Technology
Session Facade
© Copyright UTS Faculty of Information Technology 2008 – JSP JSP-11
Faculty of Information Technology
Faculty of Information Technology
Data Transfer Object
• Also called the Value Object
• Design transfers related information/objects as one object
• This improves performance and provides logical grouping of objects
• Provides a façade that encapsulates other objects.
• Usually implemented as a JavaBean ie: serializable
© Copyright UTS Faculty of Information Technology 2008 – JSP JSP-12
Faculty of Information Technology
Faculty of Information Technology
Data Transfer Object
Variations:
• Data Transfer hash map – instead of getter/setter methods, use attributes keywords get/put data. Passes hash map to backend object(eg: Session EJB)
• Data Transfer rowset – like above, but pass a java.sql.Rowset object. Use only with BMP or JDBC backends.
© Copyright UTS Faculty of Information Technology 2008 – JSP JSP-13
Faculty of Information Technology
Faculty of Information Technology
Data Access Object
• Hide your database implementation from business logic
• Only expose interfaces that (usally) return a Data Transfer Object
• You can then update your DAO implementation as you change your technology
© Copyright UTS Faculty of Information Technology 2008 – JSP JSP-14
Faculty of Information Technology
Faculty of Information Technology
Topics
• Design issues
– Design patterns
• Model View Controller
• MVC with RequestDispatcher
• Data Access Object Pattern
© Copyright UTS Faculty of Information Technology 2008 – JSP JSP-15
Faculty of Information Technology
Faculty of Information Technology
Model-View-Controller
• Model-View-Controller (MVC)– a design pattern for building applications that interact with a user (not web-specific, not Java-specific)
• Model– code for internal representation of system state (data)
• View– code for displaying information to user (GUI)
• Controller– code for changing system state (logic)
© Copyright UTS Faculty of Information Technology 2008 – JSP JSP-16
Faculty of Information Technology
Faculty of Information Technology
MVC as a FSM
• MVC is often implemented as a ‘Finite State Machine’
• Each state usually represents
– user-interaction (eg: web page)
– system-state (eg: error)
• Each state transitions to another state using ‘command’ actions
© Copyright UTS Faculty of Information Technology 2008 – JSP JSP-17
Faculty of Information Technology
Faculty of Information Technology
Sample MVC FSM
Welcome
DeleteAddList
GET /list.jsp
GET /
error: “missing name”
confirm: Are you sure?
GET /add.jspGET /del.jsp
GET /
GET /
© Copyright UTS Faculty of Information Technology 2008 – JSP JSP-18
Faculty of Information Technology
Faculty of Information Technology
MVC Architecture
Browser
Servlet(Controller)
Web Server
HTTP
Client
6 - response
JSP(View)
4 - dispatch
JavaBeans(Model)
i n s t a n t i a t e
2
5 - invoke
Data Source(s)
• Model 2 = MVC for web applications
3 – r/wData
1 - request Action
© Copyright UTS Faculty of Information Technology 2008 – JSP JSP-19
Faculty of Information Technology
Faculty of Information Technology
MVC Arch (cont'd)
1. Browser makes HTTP request “Action” to controller
2. Controller performs any initialisation eg: instantiates javabeans
3. JavaBean may retrieve external data (parallel to step 4)
4. Controller forwards request to appropriate JSPJSP only contains presentation/view code
5. JSP accesses JavaBean data set up by controller
6. JSP returns response to browser (NOT controller)
7. Web page should have form action/links back to controller
© Copyright UTS Faculty of Information Technology 2008 – JSP JSP-20
Faculty of Information Technology
Faculty of Information Technology
When to use MVC
• When:
– A single request will result in multiple substantially different-looking results.
– You have a large development team with different team members doing the Web development and the business logic.
– You perform complicated data processing, but have a relatively fixed layout.
© Copyright UTS Faculty of Information Technology 2008 – JSP JSP-21
Faculty of Information Technology
Faculty of Information Technology
Where do I put functionality?
• Servlet:– controls workflow– handles request – no presentation logic– instantiates any
beans/objects used by JSP– may do processing logic– uses an action parameter to
forward request to appropriate JSP
– may have > 1 controller, best partitioned by logical functionality
• JSP:– provides presentation– no processing logic.– retrieves any beans/objects
created by servlet– uses beans to display
dynamic content
• Beans:– represents data– may have business methods– may read/write persistent
storage eg: database– no presentation logic
© Copyright UTS Faculty of Information Technology 2008 – JSP JSP-22
Faculty of Information Technology
Faculty of Information Technology
Topics
• Design issues
– Design patterns
• Model View Controller
• MVC with RequestDispatcher
• Data Access Object Pattern
© Copyright UTS Faculty of Information Technology 2008 – JSP JSP-23
Faculty of Information Technology
Faculty of Information Technology
MVC with RequestDispatcher
1. Use JavaBeans to represent data
2. Use a servlet to handle requests ..
– Reads parameters, does some checking
– Uses an ‘action’ parameter to decide what actions to take..
3. Servlet populate the beans ..
– invokes business logic & updates beans with results.
4. Servlet stores the bean..
– Can be in the request, session, or servletContext
– Use setAttribute() method to save bean
© Copyright UTS Faculty of Information Technology 2008 – JSP JSP-24
Faculty of Information Technology
Faculty of Information Technology
MVC with RequestDispatcher -2
5. Servlet forwards the request to a JSP.
– Decides which JSP to display next & uses RequestDispatcher.forward() to transfer control to that page.
6. JSP uses the data from the beans.
– JSP accesses beans with jsp:useBean and a scope matching the location of step 4. The page then uses jsp:getProperty to output the bean properties.
© Copyright UTS Faculty of Information Technology 2008 – JSP JSP-25
Faculty of Information Technology
Faculty of Information Technology
RequestDispatcher Example
public void doGetdoGetdoGetdoGet(... ) {String action = request.getParameter(“action");
if (action.equals("order")) {
address = “order.jsp";
} else if (action.equals("cancel")) {
address = “cancel.jsp";
} else { address = “error.jsp"; }
RequestDispatcher RequestDispatcher RequestDispatcher RequestDispatcher dispatcher ====
request.getRequestDispatcher(.getRequestDispatcher(.getRequestDispatcher(.getRequestDispatcher(address););););
dispatcher.forward.forward.forward.forward(request, response);
}
This “action”determines which page “state” to
display next
© Copyright UTS Faculty of Information Technology 2008 – JSP JSP-26
Faculty of Information Technology
Faculty of Information Technology
RequestDispatcher example -3
• JSP...<form action=“controller” method=“GET”>
Enter your details
Name: <input name=“name” type=text><br>
Address: <input name=“address” type=text><br>
<input name=“actionactionactionaction” type=hidden value=“order”>
<input name=“submit” type=“submit”>
</form>
© Copyright UTS Faculty of Information Technology 2008 – JSP JSP-27
Faculty of Information Technology
Faculty of Information Technology
jsp:useBean
• The JSP page should not create the beans
– The servlet, not the JSP page, should create all the data objects. So, to guarantee that the JSP page will not create objects, you should use
<jsp:useBean ... type="package.Class" />
instead of
<jsp:useBean ... class="package.Class" />
• The JSP page should not modify the beans
– So, you should use jsp:getProperty but not jsp:setProperty.
© Copyright UTS Faculty of Information Technology 2008 – JSP JSP-28
Faculty of Information Technology
Faculty of Information Technology
recall: jsp:useBean Scope
• request (within page & any forwarded pages)
– <jsp:useBean id="..." type="..." scope="request" />
• session (within particular user/browser session)
– <jsp:useBean id="..." type="..." scope="session" />
• application (to all users)
– <jsp:useBean id="..." type="..." scope="application" />
• page (within page only)– <jsp:useBean id="..." type="..." scope="page" /> or just<jsp:useBean id="..." type="..." />
– Don’t use this in MVC applications!!!
© Copyright UTS Faculty of Information Technology 2008 – JSP JSP-29
Faculty of Information Technology
Faculty of Information Technology
Session Data Sharing
• ServletPerson p = new Person();
p.setName(“Chris”);
HttpSession session = request.getSession();
session.setAttribute(“cwcwcwcw", p);
RequestDispatcher dispatcher =
request.getRequestDispatcher(“/SomePage.jsp");
dispatcher.forward(request, response);
• JSP 1.1<jsp:useBean id=“cwcwcwcw" type=“myApp.Person“
scope="session" />
<jsp:getProperty name=“cwcwcwcw" property=“name" />
only current user sees “Chris”
© Copyright UTS Faculty of Information Technology 2008 – JSP JSP-30
Faculty of Information Technology
Faculty of Information Technology
ServletContext Data Sharing
• ServletPerson p = new Person();
p.setName(“Chris”);getServletContext().setAttribute(“cwcwcwcw", p);RequestDispatcher dispatcher =
request.getRequestDispatcher(“/SomePage.jsp");dispatcher.forward(request, response);
• JSP 1.1<jsp:useBean id=“cwcwcwcw" type=“myApp.Person“
scope=“application" /><jsp:getProperty name=“cwcwcwcw" property=“name" />
all users see “Chris”
© Copyright UTS Faculty of Information Technology 2008 – JSP JSP-31
Faculty of Information Technology
Faculty of Information Technology
Topics
• Design issues
– Design patterns
• Model View Controller
• MVC with RequestDispatcher
• Data Access Object Pattern
© Copyright UTS Faculty of Information Technology 2008 – JSP JSP-32
Faculty of Information Technology
Faculty of Information Technology
Data Access Object
• Hide your implementation from the business logic!
• General tasks:
1. Create a DTO or Value Object (JavaBean!!)
2. Create an interface for your DAO.
3. Create implementation(s) for your DAO
© Copyright UTS Faculty of Information Technology 2008 – JSP JSP-33
Faculty of Information Technology
Faculty of Information Technology
JavaBean
• DTO, Value objects are implemented as JavaBeans
– As per JSP lecture/labs
– eg: Addressbook example
© Copyright UTS Faculty of Information Technology 2008 – JSP JSP-34
Faculty of Information Technology
Faculty of Information Technology
DAO Interface
• A java interface not a class
• Just declare public methods
• Usually:
– Declare CRUD (Create, Read, Update, Delete) methods
– Declare search/find methods
• Often simply named:
entityDAO
Eg: AddressbookDAO
© Copyright UTS Faculty of Information Technology 2008 – JSP JSP-35
Faculty of Information Technology
Faculty of Information Technology
Data Access Object
• Important Concept:Hide your implementation from the business logic
• Usual setup:
– Constructor: initialisation stuff
• Often drivermanager, connect to database, etc
• Can be implemented as static, private instance or use the ThreadLocalinterface (best)
– Implement CRUD (Create, Read, Update, Delete) methods
– Implement search/find methods
+ any helper/utility methods
• Do not expose JDBC etc. eg: don’t throw SQLExceptions!!
© Copyright UTS Faculty of Information Technology 2008 – JSP JSP-36
Faculty of Information Technology
Faculty of Information Technology
Simple Example:
Javabean:public class Person implements Serializable {
private String name;
private String favecolour;
public String getFavecolour() {return favecolour;}
public void setFavecolour(String favecolour) {
this.favecolour = favecolour; }
public String getName() {return name; }
public void setName(String name) {
this.name = name; }
}
© Copyright UTS Faculty of Information Technology 2008 – JSP JSP-37
Faculty of Information Technology
Faculty of Information Technology
Simple Example:
Interface:public interface PersonDAO {
public void createPerson(Person p);
public Person findPerson(String name);
public void updatePerson(Person p);
public void deletePerson(String name);
public List<Person> searchPerson(String name);
}
© Copyright UTS Faculty of Information Technology 2008 – JSP JSP-38
Faculty of Information Technology
Faculty of Information Technology
Simple Example:
Implementation:public class PersonDAO_Impl {
private Connection conn;
public PersonDAO_Impl() { // constructor
// set up JDBC here, connection etc
}
public void createPerson(Person p) {
// implement INSERT into PERSON
// VALUES(p.getName,p.getFavecolour) etc
}
public Person findPerson(String name) {
// implement SELECT from PERSON where name = name
}
// & so on
}
© Copyright UTS Faculty of Information Technology 2008 – JSP JSP-39
Faculty of Information Technology
Faculty of Information Technology
Simple Example
Using it:(in your business logic)
PersonDAO dao = new PersonDAO_Impl();
Person p = dao.findPerson(“chris”);
session.setAttribute(“p", p);
(in your JSP)
<jsp:useBean id=“p” type=“Person”>
You found: ${p.name}
With favecolor: ${p.faveColour}
© Copyright UTS Faculty of Information Technology 2008 – JSP JSP-40
Faculty of Information Technology
Faculty of Information Technology
Questions?
© Copyright UTS Faculty of Information Technology 2008 – JSP JSP-41
Faculty of Information Technology
Faculty of Information Technology
Simple Example
• Notes:
• If following an MVC pattern, you
© Copyright UTS Faculty of Information Technology 2008 – JSP JSP-42
Faculty of Information Technology
Faculty of Information Technology
Appendix
• Struts
© Copyright UTS Faculty of Information Technology 2008 – JSP JSP-43
Faculty of Information Technology
Faculty of Information Technology
Topics
• Model View Controller
• MVC with RequestDispatcher
• Apache Struts
• Struts components
• Struts flow of control
• 6 steps in using struts
• Other tricks
• customisable messages
• Error handling
• automatic validations
• Quick reference© Copyright UTS Faculty of Information Technology 2008 – JSP JSP-44
Faculty of Information Technology
Faculty of Information Technology
MVC & Apache Struts
• Writing MVC applications using RequestDispatcher can be tedious and error prone
• Most MVC applications follow a common pattern
• Apache Struts is an open-source product that can automate most of the work involved with writing MVC J2EE applications.
• Main Website: http://struts.apache.org
• See also: – http://courses.coreservlets.com/Course-Materials/struts.html
– http://www.husted.com/struts/
– http://www.onjava.com/topics/java/JSP_Servlets
© Copyright UTS Faculty of Information Technology 2008 – JSP JSP-45
Faculty of Information Technology
Faculty of Information Technology
What is Apache Struts?
• An MVC Framework
– Provides an unified framework for deploying MVC web applications.
• A Collection of Utilities
– Provides utility classes to handle common tasks in web application development
• A Set of JSP Custom Tag Libraries
– Provides custom tag libraries for outputting bean properties, generating HTML forms, logic functions, validations
– Note that Java Standard Tag Libraries (JSTL) replace many Struts custom tags now
© Copyright UTS Faculty of Information Technology 2008 – JSP JSP-46
Faculty of Information Technology
Faculty of Information Technology
Advantages of Struts
• Dynamic file-based configuration
– Uses deployment descriptors – no hardcoding into Java, uses XML & .properties files
• Provides controller servlet
– Java and Web developers only focus on their specific tasks (implementing business logic, presenting certain values to clients, etc.)
• Provides Form beans
– Automatically populate a JavaBean component. You can use dynamically generated form beans or write your own.
• Provides Bean tags
– provides custom JSP tags which extend jsp:useBean and jsp:getProperty tags.
© Copyright UTS Faculty of Information Technology 2008 – JSP JSP-47
Faculty of Information Technology
Faculty of Information Technology
Advantages of Struts -2
• Provides HTML tags
– provides JSP tags to create HTML forms automatically associated with JavaBeans.
• Provides Logic tags
– Able to do conditionals, iterations etc
• Provides Form field validation
– Able to validate input fields on the server side.
– Can even auto-generate client side Javascript
• Consistent approach
– Struts forces consistent use of MVC throughout your application.
© Copyright UTS Faculty of Information Technology 2008 – JSP JSP-48
Faculty of Information Technology
Faculty of Information Technology
Struts MVC Architecture
Bro
wse
r
ActionServlet(Controller)
Web Server
HTTP
Client
1 - request
8 - response
JSP(View)
5 - forward
2 - map
3 – r/w
struts-config.xml
Data
.properties
ActionForm[form beans]
(model)
taglib(view)
Action(logic)
6 – <tag>
4 - forward
7 – read
© Copyright UTS Faculty of Information Technology 2008 – JSP JSP-49
Faculty of Information Technology
Faculty of Information Technology
Controller – ActionServlet
• Struts includes a controller servlet, called org.apache.struts.action.ActionServlet
• ActionServlet is responsible for mapping a logical request URI to an Action class
• This URI defaults to /*.do if you use the default web.xml file
• ActionServlet uses WEB-INF/struts-config.xml to determine which Action (business logic) class to invoke for a given action
© Copyright UTS Faculty of Information Technology 2008 – JSP JSP-50
Faculty of Information Technology
Faculty of Information Technology
Business Logic - Action
• Action class wraps the business logic of your application.
• You must extend org.apache.struts.Action and override the execute() method
• You should write one Action class per logical request
• Your Action class then returns control via a ActionMapping.findForward() method
• Best practices: Action should control the flow only and you should keep business logic in a seperateclass
© Copyright UTS Faculty of Information Technology 2008 – JSP JSP-51
Faculty of Information Technology
Faculty of Information Technology
Model - ActionForm
• You create a JavaBean for each Struts input form
• These “Form beans” extend the org.apache.struts.ActionForm class
• They basically only contain getter/setter methods
• Usually maps 1:1 to each input field in the form (and thus each request parameter)
• Struts can perform validations on these fields
• Struts can dynamically generate a bean for you
– use DynaValidatorForm class in struts-config.xml
© Copyright UTS Faculty of Information Technology 2008 – JSP JSP-52
Faculty of Information Technology
Faculty of Information Technology
Model – other classes
• You should also implement other classes to represent the model
– eg: system state beans, business logic beans, Enterprise Java beans
• These can be called by the various Struts components
– Not required by Struts but just good coding practice
• Struts can also provide SQL DataSources
– Use with JDBC
© Copyright UTS Faculty of Information Technology 2008 – JSP JSP-53
Faculty of Information Technology
Faculty of Information Technology
View – JSP/Taglibs
• Struts extends the JSP model by adding extra tags
• Use the <%@ taglib uri=“/WEB-INF/struts-*.tld” JSP directive
• Many of these tags are optional – you can still use standard JSP scriptlets, tags & expressions
– However, Struts provides lots of useful tags which assist the developer, especially when using forms!
– More tags later...
• Struts makes it easy to have a centralised database of messages – good for internationalisation!
– usually defined in ApplicationResources.properties and ApplicationResources_xx.properties
– where xx is the ISO language code eg: fr de es cn
© Copyright UTS Faculty of Information Technology 2008 – JSP JSP-54
Faculty of Information Technology
Faculty of Information Technology
Topics
• Model View Controller
• MVC with RequestDispatcher
• Apache Struts
• Struts components
• Struts flow of control
• 6 steps in using struts
• Other tricks
• customisable messages
• Error handling
• automatic validations
• Quick reference
© Copyright UTS Faculty of Information Technology 2008 – JSP JSP-55
Faculty of Information Technology
Faculty of Information Technology
Struts Flow of control
Bro
wse
r
JSP form<html:form> etc
submit to /xxx.do
Web Server
HTTP
Client
JSP resultdisplay <bean>
struts-config.xml
Data
Java Beans
Action objectinvokes logic
1. /form.html
3. get/set bean
2. /xxx.do
6. generated html
4. forward()
5. use bean
sql?
© Copyright UTS Faculty of Information Technology 2008 – JSP JSP-56
Faculty of Information Technology
Faculty of Information Technology
Struts Flow of Control
1. The user requests a form– This form is built with html:form, html:text, html:link and similar
elements• Keeps input field names in synch with bean property names
2. The form is submitted to /xxx.do• where xxx is the name of the action in html:form
• That xxx is mapped by struts-config.xml to an Action object
3. The execute method of the Action object is invoked • with Servlet details + form bean as parameters
• form bean is automatically populated with request parameters
• invokes business & data-access logic
• stores results in javabeans• in request, session, or application scope.
• returns mapping.findForward() with appropriate condition
• these conditions are mapped by struts-config.xml to various JSP pages.
© Copyright UTS Faculty of Information Technology 2008 – JSP JSP-57
Faculty of Information Technology
Faculty of Information Technology
Struts Flow of Control - 2
4. Struts forwards request to the appropriate JSP page
• (also mapped in struts-config.xml)
5. resulting JSP page displays results
• The page can use bean:write to output bean properties
• The page can use bean:message to output fixed strings
© Copyright UTS Faculty of Information Technology 2008 – JSP JSP-58
Faculty of Information Technology
Faculty of Information Technology
Topics
• Model View Controller
• MVC with RequestDispatcher
• Apache Struts
• Struts components
• Struts flow of control
• 6 steps in using struts
• Other tricks
• customisable messages
• Error handling
• automatic validations
• Quick reference
© Copyright UTS Faculty of Information Technology 2008 – JSP JSP-59
Faculty of Information Technology
Faculty of Information Technology
The Six Basic Steps in Using Struts
1. Modify struts-config.xml.
Use WEB-INF/struts-config.xml to: – Map incoming .do addresses to Action objects – Map return conditions to JSP pages
• If a mapping appears in two places, it goes in global-forwards
– Declare any form beans that are being used. – You may need to redeploy webapp after modifying struts-
config.xml.
2. Define a form bean.
– extends ActionForm and has a bean property for each incoming request parameter
– The bean will also pre-populate the initial input form
– You can also use DynaValidateForm to dynamically generate a form bean
© Copyright UTS Faculty of Information Technology 2008 – JSP JSP-60
Faculty of Information Technology
Faculty of Information Technology
The Six Basic Steps in Using Struts:
3. Create results beans.
– These are normal javabeans, use as Data Transfer Objects (ie: just to pass data between classes)
4. Define an Action class to handle requests.
– You don’t need to use request.getParameter(), a form bean is passed as argument to execute()
– Use getter methods to access the properties of the form bean.
© Copyright UTS Faculty of Information Technology 2008 – JSP JSP-61
Faculty of Information Technology
Faculty of Information Technology
The Six Basic Steps in Using Struts
5. Create form that invokes /xxx.do.– Don’t use HTML <FORM> and <INPUT> tags, instead use
<html:form> and <html:text> (and related tags).
– <html:form> tag associates a bean with the form
– < html:text> uses bean property names for each input field NAME and bean property values for each input field VALUE.
– Optionally use <bean:message> tag to output standard messages and text labels.
6. Display results in JSP.
– Use <bean:write> to output properties of the form and result beans.
– Optionally use <bean:message> to output standard messages and text labels
– Use <logic:*> tags to reduce need to Java scriptlets
Can also use EL expressions eg: ${ x}
© Copyright UTS Faculty of Information Technology 2008 – JSP JSP-62
Faculty of Information Technology
Faculty of Information Technology
Step 1: struts-config.xml
• Located in /WEB-INF
• Main entities:– <form-beans>
• Defines javabeans which represent the model
– <action-mappings>• this maps a virtual path (eg: /submit.do ) to a specific class (eg: myapp.Submit)
– <global-forwards>• like action-mappings, but handles default actions
– <global-exceptions>• generic error catching
– <message-resources>• allows you to define messages (eg: prompts) in a flat file
– <plug-in>• extends struts with extra features such as a validator, dynamic beans etc
© Copyright UTS Faculty of Information Technology 2008 – JSP JSP-63
Faculty of Information Technology
Faculty of Information Technology
<form-beans>
• For each input form, you create a bean which holds each input field
<form<form<form<form----beans>beans>beans>beans>
<form<form<form<form----bean name=bean name=bean name=bean name=““““loginFormloginFormloginFormloginForm" " " " type=type=type=type=““““myapp.loginFormmyapp.loginFormmyapp.loginFormmyapp.loginForm””””> </form> </form> </form> </form----bean>bean>bean>bean>
<form<form<form<form----bean name=bean name=bean name=bean name=““““colorFormcolorFormcolorFormcolorForm" " " " type="type="type="type="org.apache.struts.validator.DynaValidatorFormorg.apache.struts.validator.DynaValidatorFormorg.apache.struts.validator.DynaValidatorFormorg.apache.struts.validator.DynaValidatorForm">">">">
<form<form<form<form----property name="property name="property name="property name="namenamenamename" " " " type="type="type="type="java.lang.Stringjava.lang.Stringjava.lang.Stringjava.lang.String"/> "/> "/> "/>
<form<form<form<form----property name="property name="property name="property name="favecolourfavecolourfavecolourfavecolour" " " " type="type="type="type="java.lang.Stringjava.lang.Stringjava.lang.Stringjava.lang.String"/> "/> "/> "/>
</form</form</form</form----bean>bean>bean>bean>
dynamically generated
bean..
© Copyright UTS Faculty of Information Technology 2008 – JSP JSP-64
Faculty of Information Technology
Faculty of Information Technology
<action-mappings>
• You create a <action> for each logical request
<action<action<action<action----mappings>mappings>mappings>mappings>
<action path="/login" scope="request"
type="myapp.LoginAction"
name=“loginForm"
input="/loginForm.jsp">
<forward name="success“ path="/confirmation.jsp"/>
<forward name=“failure“ path="/failure.jsp"/>
</action>
•
this maps to /login.do
this is the class to execute...
these are the next screens to show, depending on what forward-request AddPersonAction returns.
Can also be action=“/xxx”
© Copyright UTS Faculty of Information Technology 2008 – JSP JSP-65
Faculty of Information Technology
Faculty of Information Technology
global struts-config tags
• <global-forwards><forward name=<forward name=<forward name=<forward name=““““indexindexindexindex““““ path="path="path="path="////index.jspindex.jspindex.jspindex.jsp"/>"/>"/>"/>
• <global-exceptions><exception handler=<exception handler=<exception handler=<exception handler=““““myapp.myExceptionHandlermyapp.myExceptionHandlermyapp.myExceptionHandlermyapp.myExceptionHandler""""
key="global.error.message"key="global.error.message"key="global.error.message"key="global.error.message"
path="path="path="path="////error.jsperror.jsperror.jsperror.jsp""""
type="java.lang.Exception"/>type="java.lang.Exception"/>type="java.lang.Exception"/>type="java.lang.Exception"/>
this is shared amongst all actions...
this is a customised Exception handler
© Copyright UTS Faculty of Information Technology 2008 – JSP JSP-66
Faculty of Information Technology
Faculty of Information Technology
misc struts-config tags
• <message-resources
parameter="parameter="parameter="parameter="ApplicationResourcesApplicationResourcesApplicationResourcesApplicationResources"/>"/>"/>"/>
• <plug-inclassNameclassNameclassNameclassName====““““myapp.ValidatorPlugInmyapp.ValidatorPlugInmyapp.ValidatorPlugInmyapp.ValidatorPlugIn">">">">
<set<set<set<set----property property=property property=property property=property property=““““varvarvarvar" value=" value=" value=" value=““““1111””””</></></></>
you can extend struts by adding plug-in
classes
customisable messages are stored in this file ie: /WEB-INF/classes/ApplicationResources.properties
© Copyright UTS Faculty of Information Technology 2008 – JSP JSP-67
Faculty of Information Technology
Faculty of Information Technology
Step 2: Form beans
public class LoginFormLoginFormLoginFormLoginForm extends ActionFormActionFormActionFormActionForm {
private String password;
private String customerNo;
public String getPasswordgetPasswordgetPasswordgetPassword() {
return this.password; }
public void setPasswordsetPasswordsetPasswordsetPassword(String p){ this.password = p; }
public String getCustomerNogetCustomerNogetCustomerNogetCustomerNo(){
return this.customerNo; }
public void setCustomerNosetCustomerNosetCustomerNosetCustomerNo(String c){ this.customerNo = c;
© Copyright UTS Faculty of Information Technology 2008 – JSP JSP-68
Faculty of Information Technology
Faculty of Information Technology
DynaActionForm
• Alternatively: in Struts-config.xml:
<form<form<form<form----bean name=bean name=bean name=bean name=““““loginFormloginFormloginFormloginForm" " " " type="type="type="type="org.apache.struts.validator.DynaActoinFormorg.apache.struts.validator.DynaActoinFormorg.apache.struts.validator.DynaActoinFormorg.apache.struts.validator.DynaActoinForm">">">">
<form<form<form<form----property name=property name=property name=property name=““““passwordpasswordpasswordpassword" " " " type="java.lang.String"/> type="java.lang.String"/> type="java.lang.String"/> type="java.lang.String"/>
<form<form<form<form----property name=property name=property name=property name=““““customerNocustomerNocustomerNocustomerNo" " " " type="java.lang.String"/>type="java.lang.String"/>type="java.lang.String"/>type="java.lang.String"/>
© Copyright UTS Faculty of Information Technology 2008 – JSP JSP-69
Faculty of Information Technology
Faculty of Information Technology
Step 3: result beans
• Just any old java bean
• You can also create business logic beans or POJO*
* Plain Old Java Objects
© Copyright UTS Faculty of Information Technology 2008 – JSP JSP-70
Faculty of Information Technology
Faculty of Information Technology
Step 4: define Action class
public class loginAction extends ActionActionActionAction {
public ActionForward execute ( ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws Exception {
// do some control & business logic here
// maybe save form beans in the request, session or application
if (ok) {
return mapping.findForward("success");
} else
return mapping.findForward(“failure");
© Copyright UTS Faculty of Information Technology 2008 – JSP JSP-71
Faculty of Information Technology
Faculty of Information Technology
Step 5: Create invoking JSP
<%@ page language="java" %>
<%@ include file="style.css" %>
<%@ taglib uri=“/WEB-INF/struts-bean.tld" prefix="bean" %>
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
<%@ taglib uri="/WEB-INF/struts-logic.tld" prefix="logic" %>
<<<<html:htmlhtml:htmlhtml:htmlhtml:html>>>>
<body><body><body><body>
<<<<html:formhtml:formhtml:formhtml:form action="action="action="action="login.dologin.dologin.dologin.do““““ method="method="method="method="postpostpostpost">">">">
<p><<p><<p><<p><html:texthtml:texthtml:texthtml:text property="property="property="property="customerNocustomerNocustomerNocustomerNo““““ size="16size="16size="16size="16““““maxlengthmaxlengthmaxlengthmaxlength="18"/>="18"/>="18"/>="18"/>
<p><<p><<p><<p><html:texthtml:texthtml:texthtml:text property=property=property=property=““““passwordpasswordpasswordpassword““““ size=size=size=size=““““8888““““ maxlengthmaxlengthmaxlengthmaxlength="10"/>="10"/>="10"/>="10"/>
<<<<html:submithtml:submithtml:submithtml:submit>>>>
<bean:message key="button.login"/><bean:message key="button.login"/><bean:message key="button.login"/><bean:message key="button.login"/>
</html:submit></html:submit></html:submit></html:submit>
© Copyright UTS Faculty of Information Technology 2008 – JSP JSP-72
Faculty of Information Technology
Faculty of Information Technology
Step 6: Display results JSP
• Use <bean:write name=“beanName”property=“beanProperty” scope=“session”> to display stored beans
<html:html><html:html><html:html><html:html>
<body><body><body><body>
<h1>Welcome<h1>Welcome<h1>Welcome<h1>Welcome
<<<<bean:writebean:writebean:writebean:write name="name="name="name="loginFormloginFormloginFormloginForm““““ property=property=property=property=““““customerNocustomerNocustomerNocustomerNo"></h1>"></h1>"></h1>"></h1>
<bean:message key=<bean:message key=<bean:message key=<bean:message key=““““welcome.message"/>welcome.message"/>welcome.message"/>welcome.message"/>
<<<<olololol>>>>
<li><<li><<li><<li><html:linkhtml:linkhtml:linkhtml:link page="page="page="page="////addPerson.doaddPerson.doaddPerson.doaddPerson.do">Add Person</html:link>>">Add Person</html:link>>">Add Person</html:link>>">Add Person</html:link>>
<li><<li><<li><<li><html:linkhtml:linkhtml:linkhtml:link page="page="page="page="/logout.do/logout.do/logout.do/logout.do">Log Out</html:link>>">Log Out</html:link>>">Log Out</html:link>>">Log Out</html:link>>
</</</</olololol>>>>
© Copyright UTS Faculty of Information Technology 2008 – JSP JSP-73
Faculty of Information Technology
Faculty of Information Technology
Topics
• Model View Controller
• MVC with RequestDispatcher
• Apache Struts
• Struts components
• Struts flow of control
• 6 steps in using struts
• Other tricks
• customisable messages
• Error handling
• automatic validations
• Quick reference© Copyright UTS Faculty of Information Technology 2008 – JSP JSP-74
Faculty of Information Technology
Faculty of Information Technology
Other tricks
• You can have customisable messages stored in a properties file
• You can program struts errors and display with a simple tag
• You can perform manual or automatic validation of input forms
© Copyright UTS Faculty of Information Technology 2008 – JSP JSP-75
Faculty of Information Technology
Faculty of Information Technology
Customisable messages
1. Create a .properties file in WEB-INF/classes
– e.g., WEB-INF/classes/ApplicationResources.properties
2. Define key/string pairs in the properties file
some.key1=my first message
some.key2=mysecond message
some.key3=some parameterized message: {0}
3. Load the properties file in struts-config.xml
– <message-resources parameter=“ApplicationResources"/>
© Copyright UTS Faculty of Information Technology 2008 – JSP JSP-76
Faculty of Information Technology
Faculty of Information Technology
Customisable messages 2
4. Output the messages in JSP pages
– Load the tag library<%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean" %>
– Output the messages using bean:message
• First message is <bean:message key="some.key1"/>
• Second: <bean:message key="some.key2"/>
• Third: <bean:message key="some.key3"
arg0="replacement"/>
“my first message”
© Copyright UTS Faculty of Information Technology 2008 – JSP JSP-77
Faculty of Information Technology
Faculty of Information Technology
Advantages of Properties Files
• Centralized updates
– If a message is used in several places� can be updated with a single change!
– Struts philosophy: “make changes in config files, not in code”
• I18N
– You can internationalize your application
– Use multiple properties files based on locale.
• ApplicationResources.properties default
• ApplicationResources_fr.properties
• ApplicationResources_es.properties
• ApplicationResources_cn.properties
© Copyright UTS Faculty of Information Technology 2008 – JSP JSP-78
Faculty of Information Technology
Faculty of Information Technology
Loading Alternate Properties Files
• More specific properties file
– Struts automatically looks for additional Locale files
• xxx_es.properties, xxx_fr.properties, etc.
• Entries from more specific file override entries from default file
– Locale is automatically determined by browser language settings
– Locale can also be set explicitly (e.g., based on incoming checkbox value) in an Action with setLocale()
© Copyright UTS Faculty of Information Technology 2008 – JSP JSP-79
Faculty of Information Technology
Faculty of Information Technology
Topics
• Model View Controller
• MVC with RequestDispatcher
• Apache Struts
• Struts components
• Struts flow of control
• 6 steps in using struts
• Other tricks
• customisable messages
• Error handling
• automatic validations
• Quick reference© Copyright UTS Faculty of Information Technology 2008 – JSP JSP-80
Faculty of Information Technology
Faculty of Information Technology
Programming struts errors
• You can collect one or more error messages to be displayed
ActionErrorsActionErrorsActionErrorsActionErrors errors = errors = errors = errors = newnewnewnew ActionErrorsActionErrorsActionErrorsActionErrors();();();();
errors.add("errors.add("errors.add("errors.add("loginerrorloginerrorloginerrorloginerror", ", ", ", newnewnewnewActionError("ActionError("ActionError("ActionError("error.invalid.loginerror.invalid.loginerror.invalid.loginerror.invalid.login", ", ", ", request.getParameter("request.getParameter("request.getParameter("request.getParameter("customerNocustomerNocustomerNocustomerNo")));")));")));")));
saveErrors(requestsaveErrors(requestsaveErrors(requestsaveErrors(request, errors);, errors);, errors);, errors);
• display this in JSP via
<html:errors/><html:errors/><html:errors/><html:errors/>
or <html:errors property=<html:errors property=<html:errors property=<html:errors property=““““loginerrorloginerrorloginerrorloginerror””””>>>>
this is a key in the .properties file, not a displayable text string!
only loginerrormsgs will be
displayed
© Copyright UTS Faculty of Information Technology 2008 – JSP JSP-81
Faculty of Information Technology
Faculty of Information Technology
Struts errors -2
• You also need to define the text string in the .properties file
error.invalid.login = {0} is an invalid loginerror.invalid.login = {0} is an invalid loginerror.invalid.login = {0} is an invalid loginerror.invalid.login = {0} is an invalid login
• Note: {0} represents a parameter.
– You can have up to 4 parameters {0} .. {3}
• You should have error headers and footers defined in the .properties file eg:errors.headererrors.headererrors.headererrors.header=<font =<font =<font =<font colorcolorcolorcolor="red">Error!</font><="red">Error!</font><="red">Error!</font><="red">Error!</font><ulululul>>>>
errors.prefixerrors.prefixerrors.prefixerrors.prefix=<li>=<li>=<li>=<li>
errors.suffixerrors.suffixerrors.suffixerrors.suffix=</li>=</li>=</li>=</li>
errors.footererrors.footererrors.footererrors.footer=</=</=</=</ulululul>>>>
© Copyright UTS Faculty of Information Technology 2008 – JSP JSP-82
Faculty of Information Technology
Faculty of Information Technology
Topics
• Model View Controller
• MVC with RequestDispatcher
• Apache Struts
• Struts components
• Struts flow of control
• 6 steps in using struts
• Other tricks
• customisable messages
• Error handling
• automatic validations
• Quick reference
© Copyright UTS Faculty of Information Technology 2008 – JSP JSP-83
Faculty of Information Technology
Faculty of Information Technology
Validation
• Manual validation:
– put validation code in Action – just usual Java code
– put validation code in ActionForm
• override ActionErrors validate()
– Client side validation – using JavaScript
• Automatic validation:
– Struts has validator plugin
– This does server-side and optionally client-side validations
– uses validation.xml and validation-rules.xml files to decide on the rules
– Nice when it works.... can be very hard to debug...
© Copyright UTS Faculty of Information Technology 2008 – JSP JSP-84
Faculty of Information Technology
Faculty of Information Technology
Automatic validation
• Update struts-config.xml
<plug-in className="org.apache.struts.validator.ValidatorPlugIn"><set-propertyproperty="pathnames"value="/WEB-INF/validator-rules.xml, /WEB-INF/validation.xml"/>
</plug-in>
• Update ApplicationResources.properties file with error messages errors.invalid={0} is invalid.errors.maxlength={0} cannot be greater than {1} characters.errors.minlength={0} cannot be less than {1} characters.errors.range={0} is not in the range {1} through {2}.errors.required={0} is required.#-- custom prompt messagesloginForm.password=PasswordloginForm.customerNo=Customer Number
© Copyright UTS Faculty of Information Technology 2008 – JSP JSP-85
Faculty of Information Technology
Faculty of Information Technology
Update validation.xml
• for each field in each form, add the following
<formset><form name=“loginForm">
<field property=“password"depends="required">
<arg0 key=“loginForm.password"/> </field>…<field property=“customerNo"
depends="required,integer"><arg0 key=“loginForm.customerNo"/>
</field>… </form></formset>
• (optional) You can edit the validation-rules.xml file with custom validations
© Copyright UTS Faculty of Information Technology 2008 – JSP JSP-86
Faculty of Information Technology
Faculty of Information Technology
Final validation steps:
• Form bean:– should extend ValidatorForm instead of ActionForm– need to import org.apache.struts.validator.*– OR use the DynaValidationForm for struts-config.xml instead of
DynaActionForm
• Put <html:errors/> in input page– locate it where you want error messages to appear– You can also show field specific errors by using the property attribute
<html:errors property=“password"/>
• (optional) Enable Javascript Validation– Put <html:javascript formName=“ loginForm” /> after <body> – Add onsubmit=“return validate BeanName (this);” to <html:form>
© Copyright UTS Faculty of Information Technology 2008 – JSP JSP-87
Faculty of Information Technology
Faculty of Information Technology
Topics
• Model View Controller
• MVC with RequestDispatcher
• Apache Struts
• Struts components
• Struts flow of control
• 6 steps in using struts
• Other tricks
• customisable messages
• Error handling
• automatic validations
• Quick reference© Copyright UTS Faculty of Information Technology 2008 – JSP JSP-88
Faculty of Information Technology
Faculty of Information Technology
Allows the link to be loaded from the request or other bean
<html:link></html:link>
<a> </a>
Automatically inserts the Web application base
<html:base><base></base>
Adds capability to load from alt text and image from message resources file
<html:img><img>
Adds locale support for internationalization
<html:html> </html:html>
<html> </html>
Struts Added BenefitStruts Equivalent
HTML Tag
Struts tag quick reference
from BEA Weblogic 8.1 Unleashed
© Copyright UTS Faculty of Information Technology 2008 – JSP JSP-89
Faculty of Information Technology
Faculty of Information Technology
<html:checkboxproperty = " chk1"value = "sel1">
<input type = "checkbox"name = "chk1"value = " sel1">
Check box
<html:radioproperty = "rad1"value = "sel1">
<input type = "radio"name = "rad1"value = "sel1">
Radio button
<html:textareaproperty = "mytarea“>
<input type = "textarea"name = "mytarea" >
Text area
<html:textproperty = "myname"size = "20" />
<input type = "text"name = "myname“> size = "20">
Text field
Struts EquivalentHTML Function
Struts tag quick reference
from BEA Weblogic 8.1 Unleashed
© Copyright UTS Faculty of Information Technology 2008 – JSP JSP-90
Faculty of Information Technology
Faculty of Information Technology
<html:multibox property="site"><input type="checkbox" name="site" value=“1"><input type="checkbox" name="site" value=“2">
List of checkboxes
<html:select property ="item"><html:option value="1">Item 1</html:option></html:select>
<select name= "item"><option value = "1">Item 1</option></select>
Selection box and options
<html:reset/><input type = "reset">Reset button
<html:submit>Submit</html:submit>
<input type = "submit"value = "Submit"property = "Submit">
Submit Button
Struts EquivalentHTML Function
Struts tag quick reference
from BEA Weblogic 8.1 Unleashed
© Copyright UTS Faculty of Information Technology 2008 – JSP JSP-91
Faculty of Information Technology
Faculty of Information Technology
Struts Logic tags
• You can check conditions on beans, values, cookies, HTTP headers and parameters<logic:equal parameter=“password” value=“secret”>
some JSP here </logic:equal>
• Boolean Conditions you can check
– equal, notEqual, greaterEqual, lessEqual, greaterThan, lessThan
• Substring matching
– Match, notMatch – these have extra parameter location to match start or end of substring
• Parameter matching
– present, notPresent – if the parameter exists...
© Copyright UTS Faculty of Information Technology 2008 – JSP JSP-92
Faculty of Information Technology
Faculty of Information Technology
Struts logic tag
• One of the most useful tags is the <logic:iterate> tag
• Can display lists of information on dynamic Web pages.
• Attributes can be:– id - name of bean that contains the value for each element of the collection.
– scope - The place to look for the attribute. page, request, session, application, or anyscope is allowed. If scope isn't present, the default value is page.
– name - name of bean (collection) to iterate on.
– type - class of object in each row of collection
– length - maximum number of iterations.
• eg:<logic:iterate<logic:iterate<logic:iterate<logic:iterate id="id="id="id="mydatamydatamydatamydata" name="" name="" name="" name="orderorderorderorder" type="" type="" type="" type="myApp.dataBeanmyApp.dataBeanmyApp.dataBeanmyApp.dataBean" scope="" scope="" scope="" scope="sessionsessionsessionsession" " " "
> > > > <<<<dtdtdtdt><><><><bean:writebean:writebean:writebean:write name="name="name="name="mydatamydatamydatamydata" property="" property="" property="" property="itemitemitemitem"/></"/></"/></"/></dtdtdtdt>>>><<<<dddddddd><><><><bean:writebean:writebean:writebean:write name="name="name="name="mydatamydatamydatamydata" property="" property="" property="" property="qtyqtyqtyqty"/></"/></"/></"/></dddddddd>>>>
</logic:iterate></logic:iterate></logic:iterate></logic:iterate>
© Copyright UTS Faculty of Information Technology 2008 – JSP JSP-93
Faculty of Information Technology
Faculty of Information Technology
Summary
• A lot to learn. Most struts courses run over several days!
• We have not covered struts features such as
– Tiles – you can re-use presentation
– Datasources - Struts has a limited ability to define datasources independently of the web application server custom validations
– More specialised Action classes you can extend
• DownloadAction (file uploads), ForwardAction, IncludeAction, LocaleAction, SwitchAction, DispatchAction
– sub-applications
© Copyright UTS Faculty of Information Technology 2008 – JSP JSP-94
Faculty of Information Technology
Faculty of Information Technology
References
• http://www.coreservlets.com
• http://struts.apache.org
• http://www.onjava.com/topics/java/JSP_Servlets
• http://javaboutique.internet.com/tutorials
– (especially ../strutsform/index.html which has a great tutorial on how to use multivalued forms)
• http://www.ibm.com/developerworks/java/
• Also read up on Java Server Faces, which may replace Struts eventually...
– http://java.sun.com/j2ee/javaserverfaces/
top related