Struts 1

  • November 2019
  • PDF

This document was uploaded by user and they confirmed that they have the permission to share it. If you are author or own the copyright of this book, please report to us by using this DMCA report form. Report DMCA


Overview

Download & View Struts 1 as PDF for free.

More details

  • Words: 4,453
  • Pages: 16
Struts Struts is a open source framework which make building of the web applications easier based on the java Servlet and JavaServer pages technologies. Struts framework was created by Craig R. McClanahan and donated to the Apache Software Foundation in 2000. The Project now has several committers, and many developers are contributing to overall to the framework. Developing web application using struts frame work is fairly complex, but it eases things after it is setup. It encourages software development following the MVC design pattern. Many web applications are JSP-only or Servlets-only. With JSP and Servlets, Java code is embedded in the HTML code and the Java code calls println methods to generate the HTML code respectively. Both approaches have their advantages and drawbacks; Struts gathers their strengths to get the best of their association. Struts is based on Model-View-Controller (MVC) design paradigm, it is an implementation of JSP Model 2 Architecture. For more of Model-View-Controller (MVC) click here. Consists of 8 Top-Level Packagesand approx 250 Classes and Interfaces. Struts is a set of cooperating classes, servlets, and JSP tags that make up a reusable MVC 2 design. This definition implies that Struts is a framework, rather than a library, but Struts also contains an extensive tag library and utility classes that work independently of the framework. The overview of struts Client browser An HTTP request from the client browser creates an event. The Web container will respond with an HTTP response. Controller The controller is responsible for intercepting and translating user input into actions to be performed by the model. The controller is responsible for selecting the next view based on user input and the outcome of model operations.The Controller receives the request from the browser, and makes the decision where to send the request. With Struts, the Controller is a command design pattern implemented as a servlet. The struts-config.xml file configures the Controller. Business logic The business logic updates the state of the model and helps control the flow of the application. With Struts this is done with an Action class as a thin wrapper to the actual business logic. Model A model represents an application’s data and contains the logic for accessing and manipulating that data. Any data that is part of the persistent state of the application should reside in the model objects. The business objects update the application state. ActionForm bean represents the Model state at a session or request level, and not at a persistent level. Model services are accessed by the controller for either querying or effecting a change in the model state. The model notifies the view when a state change occurs in the model.The JSP file reads information from the ActionForm bean

using JSP tags. View The view is responsible for rendering the state of the model. The presentation semantics are encapsulated withinthe view, therefore model data can be adapted for several different kinds of clients.The view modifies itself when a change in the model is communicated to the view. A view forwards user input to the controller.The view is simply a JSP file. There is no flow logic, no business logic, and no model information -just tags. Tags are one of the things that make Struts unique compared to other frameworks like Velocity. MVC The MVC (Model-View-Controller) architecture the client request is first intercepted by a servlet referred as controller servlet. this servlet handles the initial processing of the request and determines which JSP page to display next. Here the controller servlet is the single point of entry, there is a clear sepration of business logic, presentation output and request processing. MCV architecture is a way of decomposing an application into three parts: The model maintains the state and data that the application represents. The view allows the display of information about the model to the user. The controller allows the user to manipulate the application. the model, the view and the controller. MVC was originally applied in the graphical user interaction model of input, processing and output. In Struts, the view is handled by JSPs and presentation components, the model is represented by Java Beans and the controller uses Servlets to perform its action. Model A model represents an application’s data and contains the logic for accessing and manipulating that data. Any data that is part of the persistent state of the application should reside in the model objects. The business objects update the application state. ActionForm bean represents the Model state at a session or request level, and not at a persistent level. Model services are accessed by the controller for either querying or effecting a change in the model state. The model notifies the view when a state change occurs in the model.The JSP file reads information from the ActionForm bean using JSP tags. View The view is responsible for rendering the state of the model. The presentation semantics are encapsulated within the view, therefore model data can be adapted for several different kinds of clients.The view modifies itself when a change in the model is communicated to the view. A view forwards user input to the controller.The view is simply a JSP or HTML file. There is no flow logic, no business logic, and no model information -- just tags. Tags are one of the things that make Struts unique compared to other frameworks like Velocity. Controller The controller is responsible for intercepting and translating user input into actions to be performed by the model. The controller is responsible for selecting the next view based on user input and the outcome of model operations.The Controller receives the request from the browser, and makes the decision where to send the request. With

Struts, the Controller is a command design pattern implemented as a servlet. The struts-config.xml file configures the Controller. Struts Model A model represents an application’s data and contains the logic for accessing and manipulating that data. Any data that is part of the persistent state of the application should reside in the model objects. The business objects update the application state. ActionForm bean represents the Model state at a session or request level, and not at a persistent level. Model services are accessed by the controller for either querying or effecting a change in the model state. The model notifies the view when a state change occurs in the model.The JSP file reads information from the ActionForm bean using JSP tags. The Struts frame work doen't offer much in the way pf building model components. The Enterprise JavaBeans (EJB), Java Data Objects(JDO) and JavaBeans can be use as a model. Struts frame work doesn't limit you to one particular model implementation. Struts View The view is responsible for rendering the state of the model. The presentation semantics are encapsulated within the view, therefore model data can be adapted for several different kinds of clients.The view modifies itself when a change in the model is communicated to the view. A view forwards user input to the controller.The view is simply a JSP or HTML file. There is no flow logic, no business logic, and no model information -- just tags. Tags are one of the things that make Struts unique compared to other frameworks like Velocity. The view components typically employed in a struts application are HTML Data Transfer Objects Struts ActionForms JavaServer pages Custom tags Java resource bundles Struts ActionForm Struts ActionForm objects are used to pass client input data back and forth between the user and the business layer. The framework automatically collects the input from the request and passes this data to an Action using a form bean, which is then passed to the business layer. Struts Controller The controller is responsible for intercepting and translating user input into actions to be performed by the model. The controller is responsible for selecting the next view based on user input and the outcome of model operations. The Controller receives the request from the browser, invoke a business operation and coordinating the view to return to the client. The controller is implemented by a java servlet, this servlet is centralized point of control for the web application. In struts framework the controller responsibilities are implemented by several different components like

The ActionServlet Class The RequestProcessor Class The Action Class The ActionServlet extends the javax.servlet.http.httpServlet class. The ActionServlet class is not abstract and therefore can be used as a concrete controller by your application. The controller is implemented by the ActionServlet class. All incoming requests are mapped to the central controller in the deployment descriptor as follows. <servlet> <servlet-name>action <servlet-class>org.apache.struts.action.ActionServlet All request URIs with the pattern *.do are mapped to this servlet in the deployment descriptor as follows. <servlet-mapping> <servlet-name>action *.do *.do A request URI that matches this pattern will have the following form. http://www.my_site_name.com/mycontext/actionName.do

The preceding mapping is called extension mapping, however, you can also specify path mapping where a pattern ends with /* as shown below. <servlet-mapping> <servlet-name>action /do/* *.do A request URI that matches this pattern will have the following form. http://www.my_site_name.com/mycontext/do/action_Name The class org.apache.struts.action.requestProcessor process the request from the controller. You can sublass the RequestProcessor with your own version and modify how the request is processed. Once the controller receives a client request, it delegates the handling of the request to a helper class. This helper knows how to execute the business operation associated with the requested action. In the Struts framework this helper class is descended of org.apache.struts.action.Action class. It acts as a bridge between a client-side user action and business operation. The Action class decouples the client request from the business model. This decoupling allows for more than one-to-one mapping between the user request and an action. The Action class also can perform other functions such as authorization, logging before invoking business operation. the Struts Action class contains several methods, but most important method is the execute() method.

public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception; The execute() method is called by the controller when a request is received from a client. The controller creates an instance of the Action class if one doesn’t already exist. The strut framework will create only a single instance of each Action class in your application. Action are mapped in the struts configuration file and this configuration is loaded into memory at startup and made available to the framework at runtime. Each Action element is represented in memory by an instance of the org.apache.struts.action.ActionMapping class . The ActionMapping object contains a path attribute that is matched against a portion of the URI of the incoming request. path= "/somerequest" type="com.somepackage.someAction" scope="request" name="someForm" validate="true" input="somejsp.jsp" Once this is done the controller should determine which view to return to the client. The execute method signature in Action class has a return type org.apache.struts.action.ActionForward class. The ActionForward class represents a destination to which the controller may send control once an action has completed. Instead of specifying an actual JSP page in the code, you can declaratively associate as action forward through out the application. The action forward are specified in the configuration file.

path= "/somerequest" type="com.somepackage.someAction" scope="request" name="someForm" validate="true" input="somejsp.jsp"
The action forward mappings also can be specified in a global section, independent of any specific action mapping.

Struts Tag Library The Struts framework provides a fairly rich set of framework components. It also includes a set of tag libraries that are designed to interact intimately with the rest o the framework. The customg tags provided by Struts framework are grouped into four distinct libraries 1. HTML 2. Bean 3. Logic 4. Template And a special library called Nested tag library. Custom tags with in Struts HTML tag library base button cancel checkbox errors file form frame hidden html image img javascript link messages multibox option options options Collection password radio reset rewrite select submit text textarea

- renders an HTML base element - renders a button input fiels - renders a cancel button - renders a checkbox input field - conditionnaly renders a set of accumulated error messages - renders a file select input field - defines an HTML form element - renders an HTML frame element - renders a hidden field - renders an HTMl html element - renders an input tag of type "image" - renders an HTMl img tag - renderts JavaScript validation rules loaded by ValidationPlugin - renders an HTML anchoror hyperlink - Conditionally displays a set of accumulated messages -renders multiple checkbox input fields - renders a select option - renders a collection of select options - render a collection of select options -renders apassword input field -renders a radio button input field -renders a rest button input field - renders a URI -renders a select element -renders a submi button -renders an input field of type "text" -renders an textarea input field

Struts Internationalization (i18n) Struts Internationalization (i18n) can be done with some handy modifications in our existing application. We have to know the two Internationalization (i18n) components that are packaged with the Struts Framework. The first of these components, which is managed by the application Controller, is a Message class that references a resource bundle containing Locale-dependent strings. The second Internationalization (i18n)

component is a JSP custom tag, , which is used in the View layer to present the actual strings managed by the Controller. In this section we will move with an example to understand the whole process. We are continuing the same example which we used earlier to understand the simple struts example in the section Struts Example. First thing we will require for Internationalization (i18n) is a set of simple Java properties files. Each file contains a key/value pair for each message that you expect your application to present, in the language appropriate for the requesting client. This property file contains the key/value pairs for the default language of your application. The naming format for this file is ResourceBundleName.properties. An example of this default file, using English as the default language, would be ApplicationResources.properties A sample entry in this file would be app.name=Name, this tells Struts that for every occurrence of the app.name key the Name will be substituted. We must define a properties file for each language that your application will use. This file must follow the same naming convention as the default properties file, except that it must include the two-letter ISO language code of the language that it represents. Example of this naming convention For an German-speaking client would be ApplicationResources_de.properties For an French-speaking client would be ApplicationResources_fr.properties For an Italian-speaking client would be ApplicationResources_it.properties For an Spanish-speaking client would be ApplicationResources_es.properties Now add the respective entries in each properties files you require. After you define all of the properties files for your application, you need to make Struts aware of them. It is achieved by adding a <message-resources> sub-element to the struts-config.xml file. Then you should copy all the resource bundles into the application classpath, /WEB-INF/classes/example, and then use the package path plus the base file name as the value of the <message-resources> subelement. The following snippet shows an example of using the <message-resources> subelement to configure a resource bundle, using the properties files described above <message-resources parameter="example.ApplicationResources"/> Once this part is done we customise the view part , this is achieved throught the second i18n component defined by the Struts Framework is a JSP custom tag, , which is used to present the actual strings that have been loaded by the Controller. To use the , we must first deploy the bean tag library, which contains the tag. Deploying a tag library is a very simple process that requires only the addition of a new entry in the web.xml file of the Web application using the bean library. Here is an example of this entry: /WEB-INF/struts-bean.tld /WEB-INF/struts-bean.tld

Also check that the struts-bean.tld file is copied to the /WEB-INF/ folder. tag and how it is configured for use. Now we are done we will check step by step of our saple application. 1. WeCreate the resource bundles that will contain the key/value pairs used in your application. For our application, we will have four properties files that contain our resource bundles. The German ApplicationResources_de.properties file. app.name=Name app.hello=Hallo The French ApplicationResources_fr.properties file. app.name=Nom app.hello=Bonjour The Italian ApplicationResources_it.properties file. app.name=Nome app.hello=Ciao The Spanish ApplicationResources_fr.properties file. app.name=Nombre app.hello=Hola The English ApplicationResources.properties file. app.name=Name app.hello=Hello 2. Copy all of the properties files to the /WEB-INF/classes/example directory. Add an application <message-resources /> subelement, naming the wiley. ApplicationResources to the struts-config.xml file, as shown <struts-config> <message-resources parameter="example.ApplicationResources"/> 3. Modify the web.xml file as discussed above by adding /WEB-INF/struts-bean.tld

/WEB-INF/struts-bean.tld
4. Modify the index.jsp file index.jsp <%@ page language="java" %> <%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %> <%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %> Sample Struts Application
:
Modify the diplayname.jsp displayname.jsp

<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %> Sample Struts Display Name
<%= request.getAttribute("NAME") %> !!
So we are done with Internationalization (i18n) you need to open your Web browser to the following URL: http://localhost:port/example/

Installing Struts In order to do any Java development you need the Java Developer Kit. You can find JDK1.4 at http://java.sun.com. Just You

execute will

need

the

installation

executable

and

follow

setup

PATH

the

JAVA

to

the

and

the HOME

instructions. variables;

Struts can also be found as a subproject of the Jakarta project (http://jakarta.apache.org). There is no Struts installation for the moment, just uncompress it in a convenient directory. Copy the following JAR files, extracted from the Jakarta Struts archive, to the /WEB-INF/lib directory: struts.jar commons-beanutils.jar commons-collections.jar commons-digester.jar commons-logging.jar commons-validator.jar Copy the tld files struts-html.tld struts-bean.tld struts-logic.tld struts-nested.tld struts-template.tld

you

want

to

use

in

the

/WEB-INF

directory:

If you want to use tiles add the struts-tiles.tld also in the /WEB-INF directory. Add struts-config.xml file in the /WEB-INF directory Fot

configuring

the

struts

for

you

application

refer

to

Configuring

Struts.

For Struts documentation, install notes, and downloads, see the Struts Home page. Struts Example Struts is modeled after the MVC design pattern, you can follow a standard development process for all of your Struts Web applications. Identificaty of the application Views, the Controller objects that will service those Views, and the Model components being operated on. 1. Define and create all of the Views, in relation to their purpose, that will represent the user interface of our application. Add all ActionForms used by the created Views to the struts-config.xml file. 2. Create the components of the application’s Controller. 3. Define the relationships that exist between the Views and the Controllers (strutsconfig.xml). 4. Make the appropriate modifications to the web.xml file, describe the Struts components to the Web application.

Lets Start with step one. we will create the view file named index.jsp index.jsp <%@ page language="java" %> <%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %> Sample Struts Application
Name:
We have used some Struts-specific Form tag like instead of HTML tags. In the Form tags the attributes you can find some attributes defined in we will go through it. action : Represents the URL to which this form will be submitted. This attribute is also used to find the appropriate ActionMapping in the Struts configuration file, which we will describe later in this section. The value used in our example is Name, which will map to an ActionMapping with a path attribute equal to Name. name :Identifies the key that the ActionForm will be referenced by. We use the value NameForm. An ActionForm is an object that is used by Struts to represent the form data as a JavaBean. It main purpose is to pass form data between View and Controller components. We will discuss NameForm later in this section. type :Names the fully qualified class name of the form bean to use in this request. For this example, we use thevalue example.NameForm, which is an ActionForm object containing data members matching the inputs of this form. To use the HTML tags, you must first add a taglib entry in the application’s web.xml file that references the URI /WEB-INF/struts-html.tld. This TLD describes all of the tags in the HTML tag library. The following snippet shows the element that must be added to the web.xml file: /WEB-INF/struts-html.tld /WEB-INF/struts-html.tld

The struts-html.tld is placed in the /WEB_INF directory. Next Step is to create the action form The ActionForm used in this example contains a single data member that maps directly to the name input parameter of the form defined in the index.jsp View. When an is submitted, the Struts framework populates the matching data members of the ActionForm with the values entered into the tags. The Struts framework does this by using JavaBean reflection. The accessors of the ActionForm must follow the JavaBean standard naming convention for example private String name; public void setName(String name); public String getName(); The NameForm.java file is shown below NameForm.java package example; //import statements import javax.servlet.http.HttpServletRequest; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionMapping; public class NameForm extends ActionForm { private String name = null; public String getName() { return (name); } public void setName(String name) { this.name = name; } public void reset(ActionMapping mapping, HttpServletRequest request) { this.name = null; } }

To deploy the NameForm to our Struts application, you need to compile this class, move it to the /WEB-INF/classes/example directory, and add the following line to the section of the /WEB-INF/struts-config.xml file: This makes the Struts application aware of the NameForm and how it should be referenced. Now we create the out page for the sample application. Lets name it diplayname.jsp displayname.jsp

Sample Struts Display Name
Hello <%= request.getAttribute("NAME") %> !!
Now we move to the step two of creating the application's controller In a Struts application, two components make up the Controller. These two components are the org.apache.struts.action.ActionServlet and the org.apache. struts.action.Action classes. In most Struts applications, there is one org. apache.struts.action.ActionServlet implementation and can have many org.apache. struts.action.Action implementations. The org.apache.struts.action.ActionServlet is the Controller component that handles client requests and determines which org.apache.struts.action.Action will process the received request. When assembling simple applications, such as the one we are building, the default ActionServlet will satisfy your application needs, and therefore, you do not need to create a specialized org.apache.struts.action.ActionServlet implementation. The second component of a Struts Controller is the org.apache.struts. action.Action class. As opposed to the ActionServlet, the Action class must be extended for each specialized function in your application. This class is where your application’s specific logic begins. NameAction.java package example; import import import import import import import import

java.io.IOException; javax.servlet.ServletException; javax.servlet.http.HttpServletRequest; javax.servlet.http.HttpServletResponse; org.apache.struts.action.Action; org.apache.struts.action.ActionForm; org.apache.struts.action.ActionForward; org.apache.struts.action.ActionMapping;

public class NameAction extends Action { public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String target = new String("success"); if ( form != null ) { // Use the NameForm to get the request parameters NameForm nameForm = (NameForm)form; String name = nameForm.getName();

} // if no mane supplied Set the target to failure if ( name == null ) { target = new String("failure"); } else { request.setAttribute("NAME", name); } return (mapping.findForward(target)); } } Moving to step three, to deploy the NameAction to our Struts application, we need to compile the NameAction class and move the class file to /WEB-INF/classes/example directory, and add the following entry to the section of the /WEBINF/struts-config.xml file:

For step four we modify the web.xml file. We have to to tell the Web application about our ActionServlet. This is accomplished by adding the following servlet definition to the /WEB-INF/web.xml file: <servlet> <servlet-name>action <servlet-class> org.apache.struts.action.ActionServlet <param-name>config <param-value>/WEB-INF/struts-config.xml 1 Once we have told the container about the ActionServlet, we need to tell it when the action should be executed. To do this, we have to add a <servlet-mapping> element to the /WEB-INF/ web.xml file: <servlet-mapping> <servlet-name>action *.do You will notice in the previously listed index.jsp that our action does not include a .do at the end of the URL. We do not have to append the .do because it is automatically appended if we use the tag. If you do not use the tag, then you will need to append .do to the action's URL. This mapping tells the Web

application that whenever a request is received with .do appended to the URL, the servlet named action should service the request. Now you are ready to run the application, to begin using this application, you need to open your Web browser to the following URL: http://localhost:port/example/ Configuring Struts Struts framework use two related type of configuration file, which nust be configured properly before and application will work correctly. Both configration files are XML based. The first one is the web application deployment descriptor web.xml and the second one the Struts configuration file, it is comonly named struts-config.xml. Configuring

web.xml

There are few Struts-specific configuration options that you must configure within this file when using the struts framework. Modify the web.xml file in /WEB-INF directory by adding the .tld file you want to use like if you are using struts-html.tld then /WEB-INF/struts-html.tld /WEB-INF/struts-html.tld Configure the ActionServlet that will receive all the incoming request for the appliation. The two steps involved in configuring the Struts controller servlet in the web.xml are, first to use the servlet element to configure the servlet instance that can be latter mapped in the servlet mapping element. Using servlet element to configure the servlet class in web.xml <web-app> <sertvlet> <servlet-name>some name <servlet-class>the class name

Configure servlet mapping <web-app> <sertvlet> <servlet-name>some name <servlet-class>the class name <sertvlet-mapping> <servlet-name>some name *.do

Struts 1.0 and 1.1 The new features added to Struts 1.1 are 1. 2. 3. 4. 5. 6. 7. 8. 9 10. 11. 12. 13.

RequestProcessor class Method perform() replaced by execute() in Struts base Action Class Changes to web.xml and struts-config.xml Declarative exception handling Dynamic ActionForms Plug-ins Multiple Application Modules Nested Tags The Struts Validator Change to the ORO package Change to Commons logging Removal of Admin actions Deprecation of the GenericDataSource

Related Documents

Struts 1
November 2019 7
Struts 1
May 2020 3
Struts 1
November 2019 4
Struts
June 2020 26
Struts
November 2019 49
Struts
May 2020 36