Вы находитесь на странице: 1из 50

AWAJS - Session 2

Module 3: Controller Components


Module 4: Model and View Components
Module 3

CONTROLLER COMPONENTS

ACCPi7.1, AWAJS- Architecting Web Applications using JSF and Struts 2


Objectives

• Controller Mechanism
• ActionServlet class
• RequestProcessor class
• Action class
• Action Forward class
• Plugin

ACCPi7.1, AWAJS- Architecting Web Applications using JSF and Struts 3


Functions of Controller

• A Controller is a Browser

Java Servlet and a


central point of ActionServlet
access in an
application. All RequestProcessor
requests for an
MVC-based web
Action
application pass
through the
Model View
controller… Layer Layer

ACCPi7.1, AWAJS- Architecting Web Applications using JSF and Struts 4


Components of Struts Controller

• ActionServlet
– Main controller and responsible for receiving all Http requests and
initializing Struts framework for a web application
• RequestProcessor
– Used to process the requests received by the ActionServlet
• Action
– Implements each type of request received. Actually creates a wrapper
around the business logic
• ActionForward
– Responsible for identifying where the control should be forwarded to
provide an appropriate response
• Plugin
– Used to provide same specific functionality at startup and shutdown of
the web application.

ACCPi7.1, AWAJS- Architecting Web Applications using JSF and Struts


5
ActionServlet & RequestProcessor
(What Do They Really Do?)

• Receive the HttpServletRequest


• Automatically populate a JavaBean from the
request parameters
• Handle Locale and Content Type Issues
• Determine which Action to invoke based on URI
• Provide extension points

ACCPi7.1, AWAJS- Architecting Web Applications using JSF and Struts


6
ActionServlet & RequestProcessor
Diagram

ACCPi7.1, AWAJS- Architecting Web Applications using JSF and Struts


7
ActionServlet class

org.apache.struts.action.ActionServlet
extends javax.servlet.http.HttpServlet
• public void init()
– Called by Servlet Container for the first time when
the servlet is invoked and before any other request is
processed
• public void doGet (request, response)
– Process an HTTP ‘GET’ request
• public void doPost (request, response)
– Process an HTTP ‘POST’ request

ACCPi7.1, AWAJS- Architecting Web Applications using JSF and Struts


8
ActionServlet class

• protected void process (request, response)


– Executes the standard process for the request and
produces the response
• public void destroy()
– Shutdown the controller servlet systematically after
releasing all the resources that were allocated during
initialization
• protected RequestProcessor
getRequestProcessor (ModuleConfig config)
– Looks up and returns the RequestProcessor object
responsible for the specific modules

ACCPi7.1, AWAJS- Architecting Web Applications using JSF and Struts


9
ActionServlet class

ACCPi7.1, AWAJS- Architecting Web Applications using JSF and Struts


10
ActionServlet Mapping
<servlet-name>
<servlet>
</servlet-
</servlet>
name>

ActionServlet
Mapping

<url-pattern> <servlet-class>
</url-pattern> </servlet-class>

ACCPi7.1, AWAJS- Architecting Web Applications using JSF and Struts


11
RequestProcessor

• Handles all HTTP request received by


ActionServlet class
• Main purpose of this class is to break down each
request into small tasks.
• Each of these small tasks is executed by a different
method
• Request processing methods are prefixed with
“process”

ACCPi7.1, AWAJS- Architecting Web Applications using JSF and Struts


12
What’s an Action Class?

• Extends org.apache.struts.action.Action
• Overrides the execute()method
• Acts as a bridge between user-invoked URI and a
business method (Command pattern)
• Returns information about which view should be
rendered next
• Part of the Controller, not the Model

ACCPi7.1, AWAJS- Architecting Web Applications using JSF and Struts


13
Action Class Diagram

ACCPi7.1, AWAJS- Architecting Web Applications using JSF and Struts


14
Struts Includes built -in Action Classes

• ForwardAction
• DispatchAction
• LookupDispatchAction
• MappingDispatchAction
• IncludeAction
• SwitchAction
• LocaleAction

ACCPi7.1, AWAJS- Architecting Web Applications using JSF and Struts


15
“execute()” method

• Functionality of “execute()” method


– Performs the business logic for the application
– Helps Framework to determine where it should next route the
request

public ActionForward execute (ActionMapping mapping, ActionForm form,


HttpServletRequest request, HttpServletResponse response)

ACCPi7.1, AWAJS- Architecting Web Applications using JSF and Struts


16
The Parameters of the Action.execute()
Method
Component Description
ActionMapping Contains all of the deployment information for a
particular Action bean. This class will be used to
determine where the results of the LoginAction will
be sent after its processing is complete.

ActionForm Represents the Form inputs containing the request


parameters from the View referencing this Action
bean. The reference being passed to our LoginAction
points to an instance of our LoginForm.

HttpServletRequest Is a reference to the current HTTP request object.

ACCPi7.1, AWAJS- Architecting Web Applications using JSF and Struts


17
ActionForward

• Represents a destination where the controller


(RequestProcessor) can process the forward request
• Return type of execute() method
• Object of this class has been mapped to the name of
the forward from struts configuration file

• Following are properties supported by ActionForward


– contextRelative :URL value of the path is absolute or relative
– name : Logical name for Action Mapping
– path :URL value to which control should be redirected
– redirect :If true, controller should call
HttpServletResponse.sendRedirect(), otherwise false

ACCPi7.1, AWAJS- Architecting Web Applications using JSF and Struts


18
“Action Forward" and "struts-
config.xml
• global-forward Tag
– The code declares global forwards in struts configuration file
< global-forwards>
<forward name = "Success" path = "/display.jsp"/>
</global-forwards>
– The <global-forwards> tag defines forward with global scope. The value of name attribute
specifies the name of forward by which it will be identified.

• forward Tag
– The code declares forward in struts configuration file.
< action-mappings>
<action path = "/updateCustomer" Type = "com. Struts
example.customer. UpdateCustomer ">
forward name = "Success" path = "/updateCustomer.jsp"/>
</action>
< /action-mapping>

ACCPi7.1, AWAJS- Architecting Web Applications using JSF and Struts


19
"ActionForward" and "struts-config.xml"

• The code in the code snippet defines a URL to be used as forward with
local scope. Here, the action will be forwarded to the updateCustomer
page whenever the forward named "Success" is found.

The code snippet illustrates how to use ActionForraard class:


public class UpdateCustomer extends Action {
public ActionForward execute(ActionMapping mapping,ActionForm form,
HttpServletReguest request, HttpServletResponse response)throws
Exception {
//process action
CustomerForm customerForm =(CustomerForm) form;
Customer customer = nera Customer();
customer.setCustomerName(customerForm.getCustomerName());
customer.setCustomerAdddress(customerForm.getCustomerAddress())
request.setAttribute("customer", customer);
return nera ActionForraard("Success"); }//end of execute
}//end of UpdateCustomer

ACCPi7.1, AWAJS- Architecting Web Applications using JSF and Struts


20
Plug-In

• New features added to struts 1.1


• Java class that is initialized when the application
starts
• Allows struts application to discover resources
dynamically when the web application starts up
• It can be used to allocate resources or prepare a
connection to a database

ACCPi7.1, AWAJS- Architecting Web Applications using JSF and Struts


21
Plug-in component

• Create own user defined class that implements the


org.apache.struts.action.PlugIn interface
• Add a default constructor to the implemented class
• Implements the init() and destroy() methods
• Add a <plug-in> element to the struts-config.xml
file

ACCPi7.1, AWAJS- Architecting Web Applications using JSF and Struts


22
Module 4

MODEL AND VIEW COMPONENTS

ACCPi7.1, AWAJS- Architecting Web Applications using JSF and Struts 23


Objectives

• Model Components
• View Components
• Struts Tag Library
• Struts and
Internationalization

ACCPi7.1, AWAJS- Architecting Web Applications using JSF and Struts 24


The Model Components
• Business objects stores
business specific data and
the rules that are used to
access or modify it to
implement the business
logic. These objects
represent the real life
entities such as places,
persons, and events from a
business domain.

ACCPi7.1, AWAJS- Architecting Web Applications using JSF and Struts 25


Model Components

ACCPi7.1, AWAJS- Architecting Web Applications using JSF and Struts


26
Struts Model Components

• No built-in support for the model


• No model components provided
• Framework supports any component model
(JavaBeans, EJB,Corba, JDO, etc.)
• Should always decouple the application from a
specific model implementation.

ACCPi7.1, AWAJS- Architecting Web Applications using JSF and Struts


27
Model Structure

• The Model classes are classified as either "Transaction classes" or "Persistent"


business classes. It is the transaction class that will have most of the business rules
built into it. The persistent classes will be the business data objects.
• In the example class diagram for a Course Administration system, shown in the
graphics, "CourseAdmin" class performs most of the activities in the system hence
it is the Transaction class of the model where as the "Student", "CourseTopic",
"ResourcePerson", "Course", "CourseSchedule" are the persistent classes of the
model.

ACCPi7.1, AWAJS- Architecting Web Applications using JSF and Struts


28
View Components Overview
• Struts View Layer display the domain model in a user interface. Separating the view and the
model layer allows an application's interface to change independently. It also allows an
application to support multiple views. For example, a shopping cart application may have a
web interface as well as an interface to be used on mobile phones.
• The typical view technology used for web applications is HTML/JSP. Struts mainly use JSP as a
view component implementation technology. It provides powerful functionality and feature
set for creating internationalized applications using the same.

ACCPi7.1, AWAJS- Architecting Web Applications using JSF and Struts


29
The View Components

ACCPi7.1, AWAJS- Architecting Web Applications using JSF and Struts


30
View Components

• JavaServer Pages
• HTML
• JavaScript and Stylesheets
• Multimedia Files
• Resource Bundles
• JavaBeans (Part of model used by views)
• JSP Custom Tags
• ActionForms

ACCPi7.1, AWAJS- Architecting Web Applications using JSF and Struts


31
Struts Error Management

• Struts framework is packaged with two main


classes that are intended for error management
– ActionError
• Available in org.apache.struts.action package
• extends from org.apache.struts.action.ActionMessage
• Represents encapsulation of a single error message
– ActionErrors
• Available in org.apache.struts.action package
• extends from org.apache.struts.action.ActionMessages
• Acts as a container for a collection of ActionError instances

ACCPi7.1, AWAJS- Architecting Web Applications using JSF and Struts


32
Input Validation

• Input validation is an important activity to be


performed in any web based application
• Two ways of input validation
– Programmatically
• Override the validate() method of ActionForm class
• Validation logic to be coded
• Leads to adding a lot of redundant code
• Source code must be recompiled and redeployed
– Validator Framework

ACCPi7.1, AWAJS- Architecting Web Applications using JSF and Struts


33
ActionForm
Acts as Firewall for
application by
validating input-
entries

USER Action Class


!
Validated

ActionForm
validate() ActionForm Class
reset() acts as buffer and
holds state of data

ACCPi7.1, AWAJS- Architecting Web Applications using JSF and Struts


34
ActionForm.validate() method

public ActionErrors validate(ActionMapping mapping,


HttpServletRequest request)
{
ActionErrors errors = new ActionErrors();
if((symbol == null) || symbol.length() == 0)
{
errors.add("symbol",new
ActionMessage("errors.lookup.symbol.required"));

}
return errors;
}

ACCPi7.1, AWAJS- Architecting Web Applications using JSF and Struts


35
Validator Framework

• Sub framework of Struts


• Used by Plug-in
• Proposed by “David Winterfeldt”
• Very extensive and provides most of standards rules
• User two xml configuration file
– Validator-rules.xml
• Defines the standards reusable validation rules that are used
in validation.xml file
• Contains logical name for the validation routines which are
java methods and client-side java script code
– Validation.xml
• Defines the specific validations applied to a form beans

ACCPi7.1, AWAJS- Architecting Web Applications using JSF and Struts


36
validation.xml
<form-validation>
<formset>
<form name="emailActionForm">
<field property="emailid" depends="required, email">
<arg0 key="email.emailid"/>
</field>
<field property="password" depends="required, minlength">
<arg0 key="email.password"/>
<arg1 key="${var:minlength}" name="minlength"
resource="false"/>
<var><var-name>minlength</var-name><var-value>4</var-
value></var>
</field>
</form>
</formset></form-validation>

ACCPi7.1, AWAJS- Architecting Web Applications using JSF and Struts


37
validator-rules.xml

<validator name="email"
classname="org.apache.struts.validator.FieldChecks"
method="validateEmail"
methodParams="java.lang.Object,
org.apache.commons.validator.ValidatorAction,
org.apache.commons.validator.Field,
org.apache.struts.action.ActionMessages,
org.apache.commons.validator.Validator,
javax.servlet.http.HttpServletRequest"
depends=""
msg="errors.email"/>

ACCPi7.1, AWAJS- Architecting Web Applications using JSF and Struts


38
Tag Library

Include
Tag Tag Application directives
Handler Library deloyment For Tag
descriptor descriptor Libraries

TAG LIBRARY

ACCPi7.1, AWAJS- Architecting Web Applications using JSF and Struts 39


Struts Tag Library

• Struts framework provides a set of framework


components
• It includes a set of tag libraries, which closely
interact with others

• Tag library
– HTML Tag Library
– Bean Tag Library
– Logic Tag Library

ACCPi7.1, AWAJS- Architecting Web Applications using JSF and Struts


40
Html Tag Library

• Provides a set of tags that is similar to HTML’s set of


tags for creating a form
• Can be used to create forms bound in the Struts
framework instead of using HTML tags
• The tags in the library are designed to work closely
with the components of the Struts framework
• The data from the beans can be put onto the form
using this library
<taglib>
<taglib-url>/WEB-INF/tlds/struts-html.tld</taglib-url>
<taglib-location>/WEB-INF/tlds/struts-html.tld
</taglib-location>
</taglib>

ACCPi7.1, AWAJS- Architecting Web Applications using JSF and Struts


41
HTML Tag Library

Tag Name Description


html Renders an HTML <html> element.
text Renders an HTML <input> element with an input type of textfield.
textarea Renders an HTML <input> element with input type of textarea.
radio Renders a radio button.
form Defines HTML <form> element.
button Defines a button input field.
cancel Renders a cancel button.
checkbox Defines a checkbox input field .
frame Renders an HTML <frame> element .
rewrite Defines a URL.
select Renders an HTML <input> element with an input type of select.

ACCPi7.1, AWAJS- Architecting Web Applications using JSF and Struts


42
Logic Tag Library

• Provides a rich set of tags for executing conditional


logic in JSP pages
• These tags wrap content, which will be processed
only when a particular condition is true
<logic:equal name="age" value="15">
George is a Minor
</logic:equal>

<taglib>
<taglib-url>/WEB-INF/tlds/struts-logic.tld</taglib-url>
<taglib-location>/WEB-INF/tlds/struts-logic.tld
</taglib-location>
</taglib>

ACCPi7.1, AWAJS- Architecting Web Applications using JSF and Struts


43
Logic Tag Library
Tag Name Description
empty Checks if the scripting variable identified by name/property attribute is empty.
notEmpty Checks if the scripting variable identified by name/property attribute is not empty.
equal Checks if the variable specified by any one of attributes cookie, header, name, parameter, or
property equals the constant value specified by value attribute.
notEqual Checks if the variable specified by any one of attributes cookie, header, name, parameter, or
property does not equal to constant value specified by value attribute.
redirect Renders HTTP redirect.
forward Forwards control to the page specified the ActionForward entry.

iterate Repeats the nested body content of this tag over a specified collection.
greaterEqual Checks if the variable specified by any one of attributes cookie, header, name, parameter, or
property is greater than or equal to constant value specified by value attribute.
match Checks if the variable specified by any one of the attributes cookie, header, name, parameter,
or property contains specified constant value.
messagesPrese Generates the nested body content of this tag if specified message is present in this request.
nt
present Checks if the variable specified by any one of attributes cookie, header, name, parameter, or
property is present in the applied scope.
ACCPi7.1, AWAJS- Architecting Web Applications using JSF and Struts
44
Bean Tag Library

• Contains tags to access Java Beans and resource bundles

<bean:write name="user" property="name"/>


<bean:message key=“strutsdemo.title” />

<taglib>
<taglib-url>/WEB-INF/tlds/struts-logic.tld</taglib-url>
<taglib-location>/WEB-INF/tlds/struts-bean.tld
</taglib-location>
</taglib>

ACCPi7.1, AWAJS- Architecting Web Applications using JSF and Struts


45
Bean Tag Library
Tag Name Description
cookie Retrieves the value of an HTTP cookie.
define Defines a scripting variable based on the value of the bean
property.
Header Retrieves its values from the named request header.
include Retrieves results of a web application resource.
message Retrieves keyed values from an already defined resource bundle.
page Retrieves value of JSP object which is stored in the page context.
parameter Retrieves value of a request parameter identified by the name
attribute.
resource Retrieves the value of Web application resource.
size Retrieves the number of elements contained in a collection or a map.
struts Copies a Struts internal component into a scripting variable.
write Retrieves and prints the value of a named bean property
ACCPi7.1, AWAJS- Architecting Web Applications using JSF and Struts
46
Internationalization Support

• Much of the framework’s functionality based on


java.util.Locale
• Struts Uses Java Resource Bundles

ACCPi7.1, AWAJS- Architecting Web Applications using JSF and Struts


47
Using Java Resource Bundles
 global.title=Beer For All
 label.featuredcatalogs=Featured Catalogs
 label.featuredbeers=Featured Beers
 label.username=Username
 label.password=Password
 errors.required={0} is required.
 errors.minlength={0} can not be less than {1} characters.
 errors.maxlength={0} can not be greater than {1} characters.
 errors.invalid={0} is invalid.
 errors.byte={0} must be an byte.
 errors.short={0} must be an short.
 errors.integer={0} must be an integer.
 errors.long={0} must be an long.
 errors.float={0} must be an float.
 errors.double={0} must be an double.
 errors.date={0} is not a date.

ACCPi7.1, AWAJS- Architecting Web Applications using JSF and Struts


48
I18N is more than Resource Bundles

• Date and Time Formatting


• Currency Formatting
• Currency Conversion
• Text direction
• Proper Input Controllers
• Color Conventions
• …

ACCPi7.1, AWAJS- Architecting Web Applications using JSF and Struts


49
Summary

ACCPi7.1, AWAJS- Architecting Web Applications using JSF and Struts


50

Вам также может понравиться