Академический Документы
Профессиональный Документы
Культура Документы
Designed By:
Design Pattern –Model 1
On the other hand, you would need to provide the classes which enable
the framework to persist the shopping cart to the database of your
choice, to connect to a credit-card processor, to send orders to a
warehouse, among other things
Api
An API is really no more than a set of method signatures and
other information necessary to use a class or set of classes.
The API is totally distinct from the implementation.
For example, a number of vendors have implemented the
servlet API, each in a different way.
The API by itself has no implementation.
A class library would have an API, as would a framework.
High-level architecture view for
a Struts application.
What is a container
There are many different types of containers. There are EJB
Containers, Web Containers, servlet containers, and so on.
In general, containers provide a hosting environment for
software components to run in.
Containers provide general services that can be used by the
components within the environment, without the need or
worry of being required by the component developer.
A web container
A Web Container allows servlets, JSP components,
and other Java classes to be deployed and executed
within the container.
Services like JNDI, connection pooling, and
transaction services, can be configured at the
container level, and the component developers don’t
have to worry about the management of these
resources.
similar to the way in which EJB containers manages
security, transactions, and bean pooling.
The container architecture
a container is
a runtime
environment
for
application
components
The container architecture
The architecture contains two elements, the container itself and
the components that someone put in.
The glue between the two is the so called "deployment
descriptor".
The deployment descriptor is application dependent and
therefore the responsibility of the people that create and deploy
the application component
The client tier
The Client tier provides a means for a user to interact with the
application. This interaction may be through a web browser, or
it could also be programmatic through a web services
interface.
Regardless of the type of client, the interaction includes
submitting a request and receiving some type of response from
the Middle tier
In the case of the Struts framework, the most common type of
client is a web browser.
However, it is also possible to have clients like wireless
devices and Java Applets.
The web-tier
The Web tier provides the ability for the client tier to
communicate and interact with application logic that
resides in other tiers.
In more traditional web applications, it’s not
uncommon for some or all of the application logic to
reside in this tier.
In larger,enterprise-scale applications, the Web tier
acts as a translator and maps HTTP requests into
service invocations on the Middle tier
The web-tier..
The Web tier communicates with either a database, or
in the case of an enterprise application, an application
server.
The Web Tier is the glue that binds client applications
to the core backend business systems.
The components that reside in the Web tier allow
developers to extend the basic functionality of a web
service.
In the case of Struts, it does this by utilizing
framework components that run in a servlet container.
The middle-tier
The Middle tier is often referred as the
“application tier” or “server”. This is due in
part to the fact that there is often an application
server within this tier.
Not all Struts applications have an application
tier.
Main purpose of an application
server
One of the main purposes of using an application tier is to
separate the responsibilities of presentation from that of the
model and the business rules for the application.
Today, many web applications are using EJB servers for their
application tier.
They may not be utilizing all aspects of the J2EE architecture,
like EJBs, but there are other benefits that can be leveraged
from a J2EE server.
The J2EE application server
Struts
What is Struts
Classes and the MVC paradigm
Configuring Struts
Features
What is struts?
Struts applications are hosted by a web container and can make use of services provided
by the container, like handling requests via the HTTP and HTTPS protocol.
This frees developers up to focus on building applications that solve a business problem.
A framework written in Java
Some of the classes in the frame work are
ActionServlet
RequestProcessor
ActionMapping
Action
ActionForm
ActionForward
ActionServlet
RequestProcessor
Action Classes
Struts Controller Components
Extends <org.apache.struts.action.Action>
In Struts 1.0 overrides the perform() method
In Struts 1.1 overrides the execute() method
Acts as a bridge between user-invoked URI and a
business method
Provides information about which view should be
rendered and returned
Signature of execute
The Struts Action class contains several methods, but the most important
is the execute() method. Here is the method signature:
public ActionForward execute(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException;
Example of Action Class
public class NewReqAction
extends Action {
if (!loginModel.isLoggedIn(session)) {
ActionForward login = mapping.findForward("login");
login.setRedirect(true);
return login;
}…
Example of Action Class (cont.)
…
// Get User’s information
String userID = (String) session.getAttribute("userID");
request.setAttribute("reqBean", reqBean);
return (mapping.findForward("success"));
} // perform()
} // eof: NewReqAction
An action class-more of a controller
An org.apache.struts.action.Action class in the
Struts framework is an extension of the controller component.
It acts as an Adaptor between a user action and a business
operation.
The Action class decouples the client request from the
business model.
This decoupling allows for more than a one-to-one mapping
between the user request and an Action class.
The Action class can perform other functions, such as
authorization, logging, and session validation, before invoking
the business operation.
The action class
The action class is the heart of the framework.
It’s the bridge between client request and a business operation
Each Action class typically is designed to perform a single
business operation on behalf of a client.
A single business operation ideally is related to one business
operation.
For instance, you shouldn’t create an Action that performs
shopping-cart functionality as well as handling login and
logout responsibilities.
These areas of the applications are not closely related and
shouldn’t be combined.
execute() method
The execute() method is called on an instance of an
Action class by the controller when a request is received
from a client.
The controller will create an instance of the Action class if
one doesn’t already exist.
The Struts framework will only create a single instance of each
Action class in your application.
Since there is only one instance for all users, you must ensure
that all of your Action classes operate properly in a multi-
threaded environment.
example
Login
Logout
getAccountInformation…
Mapping the actions
“How does the controller know which Action instance to
invoke when it receives a request?”
The answer is by inspecting the request information and
utilizing a set of action mappings.
Action Mapping
Action Mapping Configuration
For mapping a request URL to a particular Action
class, the ActionServlet class is to be provided with
suitable information using ActionMapping interface.
Struts provides a declarative way in the form of XML
configuration file to pass this information to the
controller servlet.
The controller servlet parses this file and gets the
required information to handle the incoming request.
Config.xml
The configuration file usually named as struts-
config.xml file should be defined and placed in the
WEB-INF folder of the application Web Archive
(WAR file).
The controller servlet knows the configuration file
from the web.xml where it is declared as follows :
Example of ActionMapping
try {
conn =
DriverManager.getConnection(
PropertiesLoader.getProperty("oracle.datasource"));
stmt = conn.createStatement();
Example of Model Class (cont.)
// SQL Statement
String colNames =
"dept, deliv_addr_1, deliv_addr_2, deliv_addr_3, " +
“deliv_addr_4, deliv_city, deliv_st, deliv_zip, …”;
String tableName = "fmis_user ";
String sqlStmt = "select " + colNames + "from " + tableName +
"where user_id = '" + userID + "'";
rs = stmt.executeQuery(sqlStmt);
Struts ActionForms
JavaServer pages
Custom tags
Struts provides the controller in the form of an ActionServlet class. The framework uses this
class for handling all the requests. To enable your application to use this controller servlet,
include the following in the deployment descriptor i.e. web.xml
<servlet>
<servlet-name>action</servlet-name>
<servlet-
class>org.apache.struts.action.ActionServlet
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>/*.do</URL-pattern>
</servlet-mapping>
In web.xml, we also need to specify the mapping of application URLs to this servlet. In the
above code any URL with .do extension calls the ActionServlet to handle the request.
To carry out an appropriate action for a particular request, the ActionServlet is configured
using Action Mappings in the struts-config.xml file. An Action Mapping specifies a fully
qualified Action class name that should be invoked when a URL matching its path is
requested. Following is a sample action mapping :
<action path="/Register"
type="RegisterAction"
scope="request"
name="registerForm">
<forward name="success" path="/pages/Message.jsp"/>
<forward name="failure" path="/pages/Register.jsp"/>
</action>
When a URL for the application ending with Register.do is called, the ActionServlet searches
for a mapping with path as /Register. It then instantiates the class defined by the type
attribute to perform the required action. Any form parameters in the request object are
passed to the Action class using the form bean defined by the name attribute. The name
attribute defines a logical name for the form bean, the mapping for which done is using
<form-bean> tag in sturts-config.xml file as shown below:
<form-beans>
<form-bean name="registerForm"
type="RegisterForm"/>
</form-beans>
Using this input the Action class performs operations to serve the request. Depending on
the result of operation, the user is directed to the next view using the ActionForward object
(which represents the <forward> tag in Action Mappings).
Writing an Action Class
An Action class is an adapter between an incoming HTTP request and the corresponding
business logic that should be executed to process this request. It should define a perform
method which will be automatically invoked to serve the request. For each request, the
controller ( ActionServlet class) will select an appropriate Action class, create an instance (if
one does not exist), and call the perform method. The perform method should be
implemented to execute the business logic for serving the request, handle errors and navigate
to appropriate view based on outcome of the action. Usually it is a good practice to delegate
the business logic part of implementation to Enterprise Java Beans(EJB) or simple vanilla
Java Beans. Here is a sample implementation of action class
...
//class imports
....
throws IOException,
ServletException
{
......
// execute business logic
......
http://localhost:8080/GetProfile?method=update
For mapping a request URL to a particular Action class, the ActionServlet class is to be
provided with suitable information using ActionMapping interface. Struts provides a
declarative way in the form of XML configuration file to pass this information to the
controller servlet. The controller servlet parses this file and gets the required information to
handle the incoming request. The configuration file usually named as struts-config.xml file
should be defined and placed in the WEB-INF folder of the application Web Archive (WAR
file). The controller servlet knows the configuration file from the web.xml where it is
declared as follows :
<servlet>
....
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/struts-config.xml</param-value>
</init-param>
</servlet>
<struts-config>
<form-beans>
<form-bean name="registerForm"
type="RegisterForm"/>
</form-beans>
<global-forwards>
<forward name="Login" path="/Login"/>
</global-forwards>
<action-mappings>
<action path="/Profile"
type=" ProfileAction"
scope="request"
name="registerForm"
validate="true"
parameter="method" >
<forward name="success"
path="/pages/Profile.jsp"/>
<forward name="failure" path="/
pages/Login.jsp"/>
</action>
</action-mappings>
</struts-config>
<form-beans> :
Contains definition of the beans used by the application. A <form-bean> describes an
instance of ActionForm class that will be used to pass the form data to the action class.
Important attributes of <form-bean> are as follows:
<global-forwards>:
This elements define the forwards that can be used by all action
mappings. A Forward is an instance of ActionForward class that maps a
resource name to the actual resource in the application. These forward
names are used in application to forward the control to the next view
based on the outcome of execution of a request. Important attributes of
a <forward> element are as follows :
name : The logical name of the forward. This will be used in the
application to forward the request to the resource
referenced by this forward.
path : The relative path to the resource (typically jsp page).
redirect : true or false. If true, a redirect is carried out to the
resource instead of forward.
<action-mappings>:
This element is used for defining mapping for various actions using
<action> tags. An <action> tag is used to map a request URL to a
particular action and pass associated information. Here are important
attributes of <action> element :
import org.apache.struts.action.ActionForm;
/**
* Get the first name
*/
public String getFirstName(){
return (firstName);
}
/**
* Set the last name
*/
public void setfirstName(String firstName ){
this.firstName =firstName ;
}
/**
* Get the last name
*/
public String getLastName(){
return (lastName);
}
/**
* Set the last name
*/
public void setLastName(String lastName ) {
this.lastName =lastName ;
}
}
The ActionForm subclass follows standard Java Beans convention to name
the methods for a property.
This mechanism of Struts proves to be a better alternative to <jsp:
useBean> tag to capture form data. It helps to avoid calling Java Beans
in the JSP page(the view) avoiding tight coupling between the two and
provides a declarative way to do the same.
ActionForward Configuration
Global forward defined in the config file using <global-forward> tag can be
used by all the action classes to forward the control. For example an application
that requires a user to login before performing any operations, can define a
global forward to direct the user to a login page when he/she requests any
URL of the application. In addition, an action mapping can define forward
specific to its requirements using a <forward> tag in the action mapping.
Handling Exceptions
<action
path=/Profile
...
<exception key="exception.key" type="java.lang.NullPointerException"
handler="app.mypackage.ExceptionHandler"/>
</action>