Professional Documents
Culture Documents
Struts
[Objective]
Tag Libraries
STRUTS Configuration File Web Application Descriptor File Application Resources File Resources
Model-View-Controller Architecture
Model-View-Controller Architecture
[MVC]
Divides functionality among objects involved in maintaining and presenting data
Model-View-Controller Architecture
[MVC]
MVC Advantages
MVC separates design concerns (data persistence & behavior, presentation and control), decreasing code duplication, centralizing* control, and making the application more easily modifiable MVC also helps developers with different skill sets to focus on their core skills and collaborate through clearly defined interfaces New data sources are easy to add to an MVC application by creating code that adapts the new data source to the view API New client types are easy to add by adapting the new client type to operate as an MVC view MVC clearly defines the responsibilities of participating classes, making bugs easier to track down and eliminate
Struts
[MVC]
Note : The Struts project was launched in May 2000 by Craig R. McClanahan to provide a standard MVC framework to the Java community. In July 2001, Struts 1.0 was released.
Model Components
Model Components
The model represents business data and business logic.
*Note: Internal State of the System.
Operations that govern access and modification of the business data Often the model serves as a software approximation to real-world functionality It notifies views when it changes and provides the ability for the view to query the model about its state It also provides the ability for the controller to access application functionality encapsulated by the model
Model Components
JavaBeans and Scope
Page visible within a single JSP page, for the lifetime of the current request
Request visible within a single JSP page, as well as to any page or servlet that is included in this page, or forwarded to by this page Session visible to all JSP pages and servlets that participate in a particular user session, across one or more requests
Application - visible to all JSP pages and servlets that are part of a web application
Model Components
Business Logic Beans
Should encapsulate the functional logic of your application as method calls on, JavaBeans designed for this purpose For small to medium sized applications, business logic beans might be ordinary JavaBeans that interact with system state beans passed as arguments, or ordinary JavaBeans that access a database using JDBC calls For larger applications, these beans will often be stateful or stateless Enterprise JavaBeans (EJBs)
Model Components
ActionForm Beans
Extends the ActionForm class
View Components
View Components
The view renders the contents of the model
It accesses data from the model and specifies how that data should be presented
It updates data presentation when the model changes. The view also forwards user input to the controller.
*Forms and Form Bean interactions HTML Forms and their limitations Errors not easily handled
View Components
<%@ page language="java" %> <%@ taglib uri="/WEB-INF/struts-html. tld" prefix="html" %> <%@ taglib uri="/WEB-INF/struts-bean. tld" prefix="bean" %> <html:html> <head> <title> <bean: message key="logon. title"/> </title> <body bgcolor="white"> <html:errors/> <html:form action=/logonpath.do"> <table border="0" width="100%"> <tr> <th align="right"> <html:message key="prompt. username"/> </th> <td align="left"> <html:text property="username" size="16"/> </td> </tr> <tr> <td align="right"> <html:submit> <bean: message key="button. submit"/> </html:submit> </td>
View Components
Within the <form-beans> section in the struts-config.xml file, you would define a form tag like the following: <form-bean name="CustomerFormBean" type="com.javaTraining.CustomerForm" />
This <form-bean> tag is also referenced within the <action-mappings> tag in the struts-config .xml file, like the following: <action path="/CustomerAction" type="com. javaTraining.CustomerAction" name="CustomerFormBean" scope="request" input="/pgcustomer.jsp"> <forward name="Save" path="/pgindex.jsp"/> <forward name="Add Account" path="/pgaddaccount.jsp"/> <forward name="Cancel" path="/pgindex.jsp"/> </action>
View Components
Useful Presentation Tags
[logic] iterate repeats its tag body once for each element of a specified collection (which can be an Enumeration, a Hash table, a Vector, or an array of objects)
[logic] present depending on which attribute is specified, this tag checks the current request, and evaluates the nested body content of this tag only if the specified value is present [logic] notPresent the companion tag to present, notPresent provides the same functionality when the specified attribute is not present
View Components
Useful Presentation Tags continued
[html] link generates a HTML <a> element as an anchor definition or a hyperlink to the specified URL, and automatically applies URL encoding to maintain session state in the absence of cookie support
[html] img generates a HTML <img> element with the ability to dynamically modify the URLs specified by the "src" and "lowsrc" attributes in the same manner that <html:link> can [bean] parameter retrieves the value of the specified request parameter, and defines the result as a page scope attribute of type String or String
View Components
Automatic Form Validation
Struts offers an additional facility to validate the input fields it has received
To utilize this feature, override the validate() method in your ActionForm class
The validate() method is called by the controller servlet after the bean properties have been populated, but before the corresponding action class's execute() method is invoked
Controller Components
Controller Components
The controller defines the application behavior Dispatches user requests and selects views for presentation Interprets user inputs and maps them into actions to be performed by the model In a stand-alone GUI client, user inputs include button clicks and menu selections. In a Web application, they are HTTP GET and POST requests to the Web tier. The controller selects the next view to display based on the user interactions and the outcome of the model operations An application typically has one controller for each set of related functionality
*Note : org.apache.struts.action.ActionServlet is the default Servlet that is provided with Struts. This Servlet can be used, or it can be extended. If extended, the extended version should be defined in the web.xml file. For smaller applications, ActionServlet typically provides the necessary functionality. For larger applications, it is typically extended.
Controller Components
ActionServlet
process user requests, determine what the user is trying to achieve according to the request, pull data from the model (if necessary) to be given to the appropriate view, and select the proper view to respond to the user.
Controller Components
Your primary responsibilities are:
Write an Action class (that is, an extension of the Action class) for each logical request that may be received
Write the action mapping configuration file (in XML) that is used to configure the controller Servlet (struts-config.xml) Update the web application deployment descriptor file (in XML) for your application to include the necessary Struts components Add the appropriate Struts components to your application
*Note: The Action class defines a execute method that you override
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception
Controller Components
A typical Action class will implement the following logic in its execute() method
Controller Components
Design issues to remember when coding Action classes include the following The controller Servlet creates only one instance of your Action class, and uses it for all requests. Thus, you need to code your Action class so that it operates correctly in a multithreaded environment, just as you must code a Servlets service() method safely The most important principle that aids in thread-safe coding is to use only local variables, not instance variables, in your Action class The beans that represent the Model of your system may throw exceptions due to problems accessing databases or other resources. You should trap all such exceptions in the logic of your execute() method, and log them to the application log file
As a general rule, allocating scarce resources and keeping them across requests from the same user (in the user's session) can cause scalability problems
Action Class process the specified HTTP request, and create the corresponding HTTP response (or forward to another web component that will create it), with provision for handling exceptions thrown by the business logic. Return an ActionForward instance describing where and how control should be forwarded, or null if the response has already been completed.
Parameters:
mapping - The ActionMapping used to select this instance form - The optional ActionForm bean for this request (if any) request - The HTTP request we are processing response - The HTTP response we are creating
Throws:
Action class throws java.lang.Exception - if the application business logic throws an exception
Tag Libraries
Tag Libraries
HTML Tags
Bean Tags
Logic Tags Template Tags Custom Tags
Tag Libraries
HTML
The tags in the Struts HTML library form a bridge between a JSP view and the other components of a Web application. Since a dynamic Web application often depends on gathering data from a user, input forms play an important role in the Struts framework. Consequently, the majority of the HTML tags involve HTML forms. Other important issues addressed by the Struts-HTML tags are messages, error messages, hyper linking and internationalization.
button option submit buttons textareas checkboxes hidden multibox radio buttons select lists with embedded options text input fields cancel file image password input fields reset buttons
Tag Libraries
bean
Tag Name cookie define header include message page parameter resource size struts
Description Define a scripting variable based on the value(s) of the specified request cookie. Define a scripting variable based on the value(s) of the specified bean property. Define a scripting variable based on the value(s) of the specified request header. Load the response from a dynamic application request and make it available as a bean. Render an internationalized message string to the response. Expose a specified item from the page context as a bean. Define a scripting variable based on the value(s) of the specified request parameter. Load a web application resource and make it available as a bean. Define a bean containing the number of elements in a Collection or Map. Expose a named Struts internal configuration object as a bean.
write
Render the value of the specified bean property to the current JspWriter.
Tag Libraries
logic
Tag Name empty equal forward greaterEqual greaterThan iterate lessEqual lessThan match messagesNotPresent messagesPresent
Description Evaluate the nested body content of this tag if the requested variable is either null or an empty string. Evaluate the nested body content of this tag if the requested variable is equal to the specified value. Forward control to the page specified by the specified ActionForward entry. Evaluate the nested body content of this tag if requested variable is greater than or equal to specified value. Evaluate the nested body content of this tag if the requested variable is greater than the specified value. Repeat the nested body content of this tag over a specified collection. Evaluate the nested body content of this tag if requested variable is greater than or equal to specified value. Evaluate the nested body content of this tag if the requested variable is less than the specified value. Evaluate the nested body content of this tag if specified value is an appropriate substring of requested variable. Generate the nested body content of this tag if the specified message is not present in this request. Generate the nested body content of this tag if the specified message is present in this request. Evaluate the nested body content of this tag if the requested variable is neither null nor an empty string. Evaluate the nested body content of this tag if the requested variable is not equal to the specified value. Evaluate the nested body content of tag if specified value not an appropriate substring of requested variable. Generate the nested body content of this tag if the specified value is not present in this request. Generate the nested body content of this tag if the specified value is present in this request. Render an HTTP Redirect
notEmpty
notEqual notMatch notPresent present redirect
struts-config.xml
<?xml version="1.0" encoding="ISO-8859-1" ?> <!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.0//EN" "http://jakarta.apache.org/struts/dtds/strutsconfig_1_0.dtd"> <struts-config> <!-- ========== Form Bean Definitions =================================== --> <form-beans> <form-bean name="CryptForm" type="com.pri.imagebrokerWeb.CryptForm" /> </form-beans> <!-- ========== Global Forward Definitions ============================== --> <global-forwards> <forward name="start" path="/index.html"/> </global-forwards> <!-- ========== Action Mapping Definitions ============================== --> <action-mappings> <action path="/CryptForm" type="com.pri.imagebrokerWeb.CryptAction" name="CryptForm" scope="request" input="/pgCrypt.jsp"> <forward name="encrypt" path="/pgCryptDisplay.jsp"/> </action> </action-mappings> </struts-config>
web.xml File
The final step in setting up the application is to configure the application deployment descriptor (stored in file WEB-INF/web.xml) to include all the Struts components that are required. Using the deployment descriptor for the example application as a guide, we see that the following entries need to be created or modified.
web.xml File
<?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN" "http://java.sun.com/j2ee/dtds/web-app_2_2.dtd"> <web-app id="WebApp"> <display-name>imagebrokerWeb</display-name> <!-- Action Servlet Configuration --> <servlet> <servlet-name>action</servlet-name> <servlet-class>org.apache.struts.action.ActionServlet</servlet-class> <init-param> <param-name>application</param-name> <param-value>imagebrokerWeb</param-value> </init-param> <init-param> <param-name>config</param-name> <param-value>WEB-INF/struts-config.xml</param-value> </init-param> </servlet>
web.xml File
Contd . . .
<servlet-mapping> <servlet-name>action</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> <!-- The Welcome File List --> <welcome-file-list> <welcome-file>index.html</welcome-file> </welcome-file-list>
web.xml File
<taglib> <taglib-uri>WEB-INF/struts-bean.tld</taglib-uri> <taglib-location>/WEB-INF/struts-bean.tld</taglib-location> </taglib> <taglib> <taglib-uri>WEB-INF/struts-html.tld</taglib-uri> <taglib-location>/WEB-INF/struts-html.tld</taglib-location> </taglib> <taglib> <taglib-uri>WEB-INF/struts-logic.tld</taglib-uri> <taglib-location>/WEB-INF/struts-logic.tld</taglib-location> </taglib> </web-app>
Dispatch Action
Struts Dispatch Action (org.apache.struts.actions.DispatchAction) is one of the Built-in Actions provided along with the struts framework. org.apache.struts.actions.DispatchAction class enables a user to collect related functions into a single Action. It eliminates the need of creating multiple independent actions for each function.
Forward Action
The org.apache.struts.actions.ForwardAction class enables a user to forward request to the specified URL. ForwardAction is a utility class that is used in cases where a user simply needs to forward the control to an another JSP page.
Linking directly a JSP to an another, violates the MVC principles. So we achieve this through action-mapping. Note that we do not create any action class.
With ForwardAction , simply create an action mapping in the Strut Configuration and specify the location where the action will forward the request..
LookupDispatchAction
The org.apache.struts.actions.LookupDispatchAction class is a subclass of org.apache.struts.actions.DispatchAction class. This class enables a user to collect related functions into a single action class.
It eliminates the need of creating multiple independent actions for each function.
*LookupDispatchAction class is much like the DispatchAction class except that it uses a Java Map and ApplicationResource.properties file to dispatch methods .
MappingDispatchAction
The org.apache.struts.actions.MappingDispatchAction class is a subclass of org.apache.struts.actions.DispatchAction class. This class enables a user to collect related functions into a single action class.
Switch Action
A standard Action that switches to a new module and then forwards control to a URI within the new module Valid request parameters for this Action are:
page - Module-relative URI (beginning with "/") to which control should be forwarded after switching. prefix - The module prefix (beginning with "/") of the module to which control should be switched. Use a zero-length string for the default module. The appropriate ModuleConfig object will be stored as a request attribute, so any subsequent logic will assume the new module.
Switch Action
We have a web application that uses Struts. Struts has two modules: the default module and an admin module, both shown below:
<servlet> <servlet-name>action</servlet-name> <servlet-class> org.apache.struts.action.ActionServlet </servlet-class> <init-param> <param-name>config</param-name> <param-value>/WEB-INF/struts-config.xml </param-value> </init-param> <init-param> <param-name>config/admin</param-name> <param-value>/WEB-INF/struts-config-admin.xml </param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet>
Switch Action
<action path="/switch" type="org.apache.struts.actions.SwitchAction"> </action>
<action path="/userSubmit" attribute="userForm" input="/form/userForm.jsp" name="userForm" scope="request" type="action.UserAction"> <forward name="success" path="/switch.do?page=/listUsers.do&prefix=/admin"/> </action>
Validation Framework
Validation
Validator Framework emits the JavaScript code which validates the user input on the browser. Steps: 1. Enabling the Validator plug-in: This makes the Validator available to the system. 2. Create Message Resources for the displaying the error message to the user. 3. Developing the Validation rules We have to define the validation rules in the validation.xml for the address form. Struts Validator Framework uses this rule for generating the JavaScript for validation. 4. Applying the rules: We are required to add the appropriate tag to the JSP for generation of JavaScript.
Struts Tiles
Tiles is a framework for the development user interface.
Tiles enables the developers to develop the web applications by assembling the reusable tiles (jsp, html, etc..).
Tiles uses the concept of reuse and enables the developers to define a template for the web site and then use this layout to populate the content of the web site. For example, if you have to develop a web site having more that 500 page of static content and many dynamically generated pages.
2. Create layout JSPs. 3. Develop the web pages using layouts. 4. 5. Repackage, run and test application. Add the Tiles TLD to web.xml file
Resources
Resources
Main Struts Web Site http://jakarta.apache.org/struts/index.html Struts User Guide http://jakarta.apache.org/struts/userGuide/index.html Various Struts Resources http://jakarta.apache.org/struts/resources.html Struts1 http://www.roseindia.net/struts