meljun_cortes_jedi slides-web programming-chapter07-mvc i intro and struts
TRANSCRIPT
-
8/3/2019 MELJUN_CORTES_JEDI Slides-Web Programming-Chapter07-MVC I Intro and Struts
1/41
Introduction to MVC and theStruts Framework
Web Programming
-
8/3/2019 MELJUN_CORTES_JEDI Slides-Web Programming-Chapter07-MVC I Intro and Struts
2/41
Introduction to Model-View-
Controller Architecture
2Web Programming
An architectural pattern that has proven to be effective indevelopment projects.
Motivation In any application, the part of the code most likely to change is the
portion regarding the user interface. Having your business logictightly coupled with your user interface makes the process of makingchanges to the interface more complex and error-prone.
Solution The MVC pattern provides a solution to these problem by
partitioning the application into Model, View, and Controllercomponents, decoupling them from each other while providing a setof recommendations about their interactions.
-
8/3/2019 MELJUN_CORTES_JEDI Slides-Web Programming-Chapter07-MVC I Intro and Struts
3/41
Introduction to Model-View-
Controller Architecture
3Web Programming
- Renders the models- Requests updates from models
- Sends user gestures to controller- Allows controller to select view
- Encapsulates application state- Responds to state queries- Exposes application functionality- Notifies views of changes
- Defines application behavior- Maps user actions to model updates
- Selects view for response- One for each functionality
-
8/3/2019 MELJUN_CORTES_JEDI Slides-Web Programming-Chapter07-MVC I Intro and Struts
4/41
-
8/3/2019 MELJUN_CORTES_JEDI Slides-Web Programming-Chapter07-MVC I Intro and Struts
5/41
View
5Web Programming
Comprises all the details of user interface implementation.
Only this layer interacts with the user.
Advantages:
Easier to include the presence of a separate design group into thedevelopment team.
Makes it possible to provide for multiple interfaces to the application.
-
8/3/2019 MELJUN_CORTES_JEDI Slides-Web Programming-Chapter07-MVC I Intro and Struts
6/41
Controller
6Web Programming
Contains details about program flow/screen transition.
Also responsible for capturing events generated by the userfrom the View layer and possibly updating the Model
components using user-provided data. Advantages:
View components can be designed such that they do not need to beaware of each other.
Updates of th model components are removed from the presentation
layer.
-
8/3/2019 MELJUN_CORTES_JEDI Slides-Web Programming-Chapter07-MVC I Intro and Struts
7/41
Introduction to Model-View-
Controller Architecture
7Web Programming
It is not to say that the MVC pattern comes with all benefitswithout any side-effects. Partitioning the application into
three separate components results in an increase incomplexity. For small applications which do not benefit fromloose coupling of the Model, this may be a stumbling blockusing of this pattern. However, it is probably best to keep inmind that applications often start out small and grow intocomplex systems, so loose coupling should always beaimed for.
-
8/3/2019 MELJUN_CORTES_JEDI Slides-Web Programming-Chapter07-MVC I Intro and Struts
8/41
The Model 2 Architecture
8Web Programming
MVC Architecture for the Web
MVC Architecture slightly modified and adapted for the useof web applications
Model 2 applications typically have the following: Front Controller, a servlet controller that:
Provides a single point of access to the rest of the application.
Is responsible for providing central management of application flow.
Can also provide such services as security handling and user management.
Typically uses XML configurations to determine application flow and commandprocessing.
Commonly makes use of helper components that serve as Command objects.
-
8/3/2019 MELJUN_CORTES_JEDI Slides-Web Programming-Chapter07-MVC I Intro and Struts
9/41
The Model 2 Architecture
9Web Programming
Implementing such an architecture can be made easierthrough the use of existing third-party frameworks. Theseframeworks provide a lot of the plumbing details (requestforwarding, reading of configuration files, etc.) so that we
can concentrate on more important matters. They alsoprovide additional useful functionality.
-
8/3/2019 MELJUN_CORTES_JEDI Slides-Web Programming-Chapter07-MVC I Intro and Struts
10/41
Struts
10Web Programming
An open-sourceframework providedand managed by theApache Software
Foundation.
-
8/3/2019 MELJUN_CORTES_JEDI Slides-Web Programming-Chapter07-MVC I Intro and Struts
11/41
MVC and Struts
11Web Programming
Objects provided by Struts for:
Model
View
struts-html Controller
ActionServlet
Action
ActionForm
struts-config.xml
-
8/3/2019 MELJUN_CORTES_JEDI Slides-Web Programming-Chapter07-MVC I Intro and Struts
12/41
ActionServlet
12Web Programming
At the center of the controller implementation of the Strutsframework is the ActionServlet.
Serves as a Front Controller servlet and provides a singlepoint of access to the rest of the web application.
Contains the logic behind client request handling.
Knows all details by reading from an XML configuration file,named struts-config.xml.
Which Action to call to handle which request
Which view component should next be called
Provided to us ready-for-use by the Struts framework; onlyneeds to be configured properly.
-
8/3/2019 MELJUN_CORTES_JEDI Slides-Web Programming-Chapter07-MVC I Intro and Struts
13/41
13Web Programming
web.xml
actionorg.apache.struts.action.ActionServletapplication
ApplicationResourcesconfig/WEB-INF/struts-config.xml...
action*.do
-
8/3/2019 MELJUN_CORTES_JEDI Slides-Web Programming-Chapter07-MVC I Intro and Struts
14/41
Action
14Web Programming
All Action objects define a method called execute(), and it isthis method that is called by the ActionServlet to handleclient requests.
The Struts framework only provides developers with thebase Action class; to include Action objects as requesthandlers in their application developers must subclass thisbase class and provide an implementation for the executemethod.
-
8/3/2019 MELJUN_CORTES_JEDI Slides-Web Programming-Chapter07-MVC I Intro and Struts
15/41
15Web Programming
import org.apache.struts.action.*
public class LoginAction extends Action {public ActionForward execute(ActionMapping mapping,
ActionForm form,HttpServletRequest request,HttpServletResponse response)throws Exception {// cast the generic ActionForm object// to the specific ActionForm implementation// configured for this Action
LoginForm loginForm = (LoginForm)form;
// Retrieve the user -specified data.String loginName = form.getLoginName();String password = form.getPassword();
// Create the business object that will handle the request.UserService service = new UserService();
user = service.login(loginName, password);
// if user does not exist login failed forward// the user to an error pageif (user == null) {return mapping.findForward("failure");}
-
8/3/2019 MELJUN_CORTES_JEDI Slides-Web Programming-Chapter07-MVC I Intro and Struts
16/41
16Web Programming
// Store the result into session scope for use in the rest of the// application, using a predefined constant
HttpSession session = request.getSession();session.setAttribute(ApplicationConstants.USER_OBJECT, user);
// user has successfully logged in. Forward the user to the// rest of the application.
return mapping.findForward("success");}
}
-
8/3/2019 MELJUN_CORTES_JEDI Slides-Web Programming-Chapter07-MVC I Intro and Struts
17/41
Action
17Web Programming
The only activities that an Action should perform are:
Retrieval of user-provided information from the associatedActionForm bean.
Translating form data into parameters required by the business
objects that implement the functionality.
Retrieve the result from the operation of the business object andfrom there determine the next view the user should be forwarded to.
Optionally, store the data results of the business operation into thesession or request objects for use by the rest of the application.
-
8/3/2019 MELJUN_CORTES_JEDI Slides-Web Programming-Chapter07-MVC I Intro and Struts
18/41
Action
18Web Programming
The framework will only instantiate a single copy of theAction objects and use it to facilitate all requests. Thismeans that we must always:
Code the Action to be thread-safe.
Make sure that we always use local variables not instance variables.
-
8/3/2019 MELJUN_CORTES_JEDI Slides-Web Programming-Chapter07-MVC I Intro and Struts
19/41
Action
19Web Programming
Action instances are able to instruct the ActionServlet whichview component to delegate the response to by returninginstances of ActionForward objects. Actions have access tothese ActionForward objects through the use of an
ActionMapping object which encapsulates the data of logicalpath mappings for each Action. These mappings are readfrom the configuration file by the ActionServlet, which is thenresponsible for passing the necessary ActionMapping to theAction. So, to instruct the ActionServlet to pass control to a
logical mapping named success, our Action performed thefollowing statement:
return mapping.findForward("success");
-
8/3/2019 MELJUN_CORTES_JEDI Slides-Web Programming-Chapter07-MVC I Intro and Struts
20/41
ActionForm
20Web Programming
Instances of this class are used to facilitate the retrieval ofdata from user-populated forms to the Action instanceshandling those form events.
Each instance of an ActionForm represents a form or aseries of forms.
They define properties that correspond to the form elements of theform(s) they represent, and expose them using publicly accessiblesetters and getters. Actions which then need the data from the formssimply call on the ActionForm instance's getter methods.
Struts provides the base class definition; developers havethe responsibility of creating their own implementations.
-
8/3/2019 MELJUN_CORTES_JEDI Slides-Web Programming-Chapter07-MVC I Intro and Struts
21/41
21Web Programming
import org.apache.struts.action.*;
public class LoginForm extends ActionForm {private String loginName;private String password;
public String getLoginName() {return loginName;
}
public void setLoginName(String loginName) {this.loginName = loginName;}
public String getPassword() {return password;
}
public void setPassword(String password) {this.password = password;}
}
-
8/3/2019 MELJUN_CORTES_JEDI Slides-Web Programming-Chapter07-MVC I Intro and Struts
22/41
ActionForm
22Web Programming
Some things to remember when coding ActionForms:
Define properties (with associated get and set methods) for eachelement in the form it will represent.
Do NOT place any business logic in the ActionForm. They are
meant merely to transfer data between View and Controllercomponents and as such is not suited for business logic.
Optionally include a validate method to perform validation of databefore control even passes to the Action.
-
8/3/2019 MELJUN_CORTES_JEDI Slides-Web Programming-Chapter07-MVC I Intro and Struts
23/41
struts-config.xml
23Web Programming
Serves as the configuration file for the components of theStruts framework.
Here, we are able to define which action is called for whichrequest, which form component to use for each action, andthe mapping of logical names to actual paths, among otherthings.
-
8/3/2019 MELJUN_CORTES_JEDI Slides-Web Programming-Chapter07-MVC I Intro and Struts
24/41
struts-config.xml
24Web Programming
Example
-
8/3/2019 MELJUN_CORTES_JEDI Slides-Web Programming-Chapter07-MVC I Intro and Struts
25/41
struts-config.xml
25Web Programming
(Example continued)
Defines the XML file as a configuration file for use by the Struts framework.Excluding this line, or mistyping it, will result in errors when the application loads.
The root element of the configuration file.
Marks the start and end of definitions of ActionForm instances.
Defines an ActionForm instance that can be used by the application. It has twoattributes:
name: The logical name to be associated with the ActionForm class.
type: The fully qualified class name of the ActionForm class.
-
8/3/2019 MELJUN_CORTES_JEDI Slides-Web Programming-Chapter07-MVC I Intro and Struts
26/41
struts-config.xml
26Web Programming
(Example continued)
Marks the start and end definitions of actions and their mappings
Defines an instance of an Action object for use by the application. Most actionelements will implement the following attributes:
path: The context-relative path to be used by this Action. Any request to this path results in the definedAction being called.
type: The fully qualified class name of the Action class.
name: The name of the element to use with this action.
scope: The context scope where our ActionForm can be accessed. This dictates where the ActionServlet
will store the instance of the ActionForm.
-
8/3/2019 MELJUN_CORTES_JEDI Slides-Web Programming-Chapter07-MVC I Intro and Struts
27/41
struts-config.xml
27Web Programming
(Example continued)
Actions can have zero to many forward elements. This element defines a logicalmapping between a name and an actual path in our application. It has thefollowing attributes:
name: The logical name of the forward which can be used by the Action instance
path: The path to the view component associated with this forward
-
8/3/2019 MELJUN_CORTES_JEDI Slides-Web Programming-Chapter07-MVC I Intro and Struts
28/41
Controller
28Web Programming
Summary of things to do for the controller layer:
For one-time setup:
Configure the ActionServlet in your app's deployment descriptor
For each form handler to be added to the application:
Create an ActionForm object that will represent all data gathered from the form
Create an Action object which, in its execute method, defines how the form willbe handled
Create a configuration entry for the ActionForm object in struts-config.xml, insidethe section
Create a configuration entry for the Action object in struts-config.xml, inside the
-
8/3/2019 MELJUN_CORTES_JEDI Slides-Web Programming-Chapter07-MVC I Intro and Struts
29/41
View
29Web Programming
Struts can make use of any presentation layer technology,though in most cases JSPs and/or HTML is used.
Struts provide for this layer a set of tag libraries that allowsus to make use of Struts features for automatic form
population and validation.
-
8/3/2019 MELJUN_CORTES_JEDI Slides-Web Programming-Chapter07-MVC I Intro and Struts
30/41
struts-html
30Web Programming
Mimics a lot of functionality we have come to expect fromstandard HTML tags but provides extra features.
Most often used when creating forms to be used for theapplication.
Example:
Login Page
Login Page
User Name :
Password : -
8/3/2019 MELJUN_CORTES_JEDI Slides-Web Programming-Chapter07-MVC I Intro and Struts
31/41
struts-html
31Web Programming
(Example Continued)
This was the form used in our previous example.
Notice how standard HTML elements like , , , and
were replaced by tags from the struts-html library.
-
8/3/2019 MELJUN_CORTES_JEDI Slides-Web Programming-Chapter07-MVC I Intro and Struts
32/41
struts-html
32Web Programming
Renders an HTML form.
Each form tag is associated with an action mapping defined by theaction attribute. The value inside this action attribute specifies the
path of the action mapping.
Looking back at the configuration file that we used for the previousexample:
......
Note that the value in the path attribute matches that of the value in the actionattribute in the tag. This indicates that this form, when submitted,will be presented to the LoginAction for handling.
-
8/3/2019 MELJUN_CORTES_JEDI Slides-Web Programming-Chapter07-MVC I Intro and Struts
33/41
struts-html
33Web Programming
( continued)
One of the conditions for a valid html:form tag is that each of thefields it contains must be defined in the ActionForm specified for theparticular action mapping.
Other possible attributes: method: Can either be POST or GET. Defines the HTTP method to be used
when submitting the form.
-
8/3/2019 MELJUN_CORTES_JEDI Slides-Web Programming-Chapter07-MVC I Intro and Struts
34/41
struts-html
34Web Programming
Renders a standard HTML text input field.
Attributes:
property: Specifies which property in the associated ActionForm it is bound to.
size: Defines the size of the text field to be displayed.
maxlength: Defines the maximum length of the value user can input.
Renders a standard HTML password field.
Shares the attributes of .
-
8/3/2019 MELJUN_CORTES_JEDI Slides-Web Programming-Chapter07-MVC I Intro and Struts
35/41
struts-html
35Web Programming
html:text and html:password are bound to properties of theActionForm instance associated with the form. It means thatthe values entered by the user into these fields willautomatically be set into the bound properties in the
ActionForm object. If there are previous existing values inthe ActionForm object (the form has already been accessedbefore), the form fields will automatically be prepopulatedwith values from the ActionForm object.
-
8/3/2019 MELJUN_CORTES_JEDI Slides-Web Programming-Chapter07-MVC I Intro and Struts
36/41
struts-html
36Web Programming
Other tags in the struts-html tag library:
Renders an HTML hidden form field.
Sample usage:
Renders a HTML radio check box.
Sample usage:
-
8/3/2019 MELJUN_CORTES_JEDI Slides-Web Programming-Chapter07-MVC I Intro and Struts
37/41
struts-html
37Web Programming
(Other tags continued)
,
html:select is used to render a drop-down list box. The options for this list box arespecified using html:option tags.
Sample usage:0 Label1 Label2 Label
,
Are used to render checkbox field and textarea field, respectively.
-
8/3/2019 MELJUN_CORTES_JEDI Slides-Web Programming-Chapter07-MVC I Intro and Struts
38/41
View
38Web Programming
Summary of things to do for the View layer:
For one-time setup:
Configure the tag libraries for use in the application's deployment descriptor.
Place the JAR files containing the implementation for the tag libraries in the
appliaction's WEB-INF/lib directory .
-
8/3/2019 MELJUN_CORTES_JEDI Slides-Web Programming-Chapter07-MVC I Intro and Struts
39/41
View
39Web Programming
(Summary continued)
For each form to be created:
Add a taglib directive to the JSP page to enable use of the struts-html tag library.
In place of the standard tag, use . Specify in its action
attribute the path of the Action that will handle the form. In place of the HTML field tags (, etc), make use of the tags
included in the struts-html tag library that perform the same functionality(, etc).
Make sure that all input fields present in the form definition are present asproperties in the ActionForm object associated with this request. It is NOTnecessary that all properties in the object be displayed as fields, but it is required
that all fields are present as properties. Remember to close the tag.
-
8/3/2019 MELJUN_CORTES_JEDI Slides-Web Programming-Chapter07-MVC I Intro and Struts
40/41
Looking at Things as a Whole
40Web Programming
Example: A User Logging In
Before the user ever enters the site, the ActionServlet takes in theconfiguration file and reads the details. So, when the user accessesthe login form, the framework already knows the associatedActionForm that will store its details and the Action that will handleform submission.
When the login page loads, the struts-html tags that we have usedattempts to render the HTML fields. If the ActionForm for this formdoes not exist, the page will not display. If there are more fields inthe form than there are properties in the ActionForm to back them
up, the page will also not display. If the ActionForm does exist, thetags will see if there were any previous values stored in theActionForm. If there are, the form fields are prepopulated with data.If not, the form fields are left empty and the user will see a blankform.
-
8/3/2019 MELJUN_CORTES_JEDI Slides-Web Programming-Chapter07-MVC I Intro and Struts
41/41
Looking at Things as a Whole
41Web Programming
(Example continued)
When the form is submitted, the values in the form fields areautomatically set into the ActionForm object by the StrutsFramework. This object is then passed into the appropriate Actionhandler, along with the ActionMapping object that reflect mappingdetails as specified in the configuration file.
The Action object performs its handling, then tells the ActionServletwhere to go next by specifying one of the forwards configured in themapping. The ActionServlet then redirects the user to that page.