Search This Blog

Monday, November 16, 2009

Struts for Begineer


What are struts?

  1. Struts are an open source framework used for developing J2EE web applications using Model View Controller (MVC) design pattern.

  2. It uses and extends the Java Servlet API to encourage developers to adopt an MVC architecture.

Struts framework provides three key components:

  1. A request handler provided by the application developer that is used to map to a particular URI.

  2. A response handler which is used to transfer the control to another resource which will be responsible for completing the response.

  3. A tag library which helps developers to create the interactive form based applications with server pages.

MVC Architecture

Aim:

The main aim of the MVC architecture is to separate the business logic and application data from the presentation data to the user.

Here are the reasons why we should use the MVC design pattern.

  1. They are reusable: When the problem recurs, there is no need to invent a new solution; we just have to follow the pattern and adapt it as necessary.

  2. They are expressive: By using the MVC design pattern our application becomes more expressive.


Model:

  1. The model object knows about all the data that need to be displayed.

  2. It is model who is aware about all the operations that can be applied to transform that object. It only represents the data of an application.

  3. The model represents enterprise data and the business rules that manage, access and updates of this data.

  4. Model is not aware about the presentation data and how that data will be displayed to the browser.

View:

  1. The view represents the presentation of the application.

  2. The view object refers to the model. It uses the query methods of the model to obtain the contents and renders it.

  3. The view is not dependent on the application logic. It remains same if there is any modification in the business logic.

  4. In other words, we can say that it is the responsibility of the view's to maintain the consistency in its presentation when the model changes.

Controller:

  1. Whenever a user send request for something it always goes through the controller.

  2. The controller is responsible for intercepting the request from the view and send to the model for appropriate action.

  3. After the action can be taken in the data, after the appropriate data will be transfer to the view by controller.


Struts framework:


  1. Struts framework composed of approximately 300 class and interfaces which are organized 12 top level packages.

  2. Utility and helper class framework providing interacting with controller using class and interface.

  3. Even framework is providing predefine tag library for html GUI design.

The struts controller component:

  1. Whenever a user request for something, then the request is handled by the Struts Action Servlet.

  2. When the ActionServlet receives the request, it intercepts the URL and based on the Struts Configuration files, it gives the handling of the request to the Action class.

  3. Action class is a part of the controller and is responsible for communicating with the model layer.

The Struts View Components:

  1. The view components are responsible for presenting information to the users and accepting the input from them.

  2. They are responsible for displaying the information provided by the model components.

  3. Mostly we use the Java Server Pages (JSP) for the view presentation. To extend the capability of the view we can use the Custom tags, java script etc.

The Struts model component:

  1. The model components provide a model of the business logic behind a Struts program. It provides interfaces to databases or back- ends systems.

  2. Model components are generally a java class. There is not any such defined format for a Model component, so it is possible for us to reuse Java codes which are written for other projects. We should choose the model according to our client requirement.

Struts working

Struts Controller:

  1. The class org.apache.struts.action.ActionServlet is the heart of the Struts Framework. It is the Controller part of the Struts Framework.

  2. ActionServlet is configured as Servlet in the web.xml file as shown in the following code snippets.



action
org.apache.struts.action.ActionServlet

config
/WEB-INF/struts-config.xml


debug
2


detail
2

2

tag in the web.xml file specifies the url pattern to be handled by the servlet. By default it is *.do, but it can be changed to anything.



action
*.do


What is Action Class?

  1. An Action class in the struts application extends Struts 'org.apache.struts.action.Action" Class.

  2. Action class acts as wrapper around the business logic and provides an interface to the application's Model layer.

  3. It acts as glue between the View and Model layer. It also transfers the data from the view layer to the specific business process layer and finally returns the processed data from business layer to the view layer.



Action Class working procedure:

  1. An Action works as an adapter between the contents of an incoming HTTP request and the business logic that corresponds to it.

  2. Then the struts controller (ActionServlet) selects an appropriate Action and creates an instance if necessary, and finally calls execute method.

To use the Action, we need to Subclass and overwrite the execute () method.

  1. The ActionServlet (command) passes the parameterized class to Action Form using the execute() method.

  2. The return type of the execute method is ActionForward which is used by the Struts Framework to forward the request to the file as per the value of the returned ActionForward object.

Understanding Action Class
Here is the signature of the Action Class.

public ActionForward execute(ActionMapping mapping,

ActionForm form,

javax.servlet.http.HttpServletRequest request,

javax.servlet.http.HttpServletResponse response)

throws java.lang.Exception

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 forward0ed, 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



What is ActionForm?

An ActionForm is a JavaBean that extends org.apache.struts.action.ActionForm.

  1. ActionForm maintains the session state for web application and the ActionForm object is automatically populated on the server side with data entered from a form on the client side.

  2. The validate() method is used to validate the inputs. If any or all of the fields on the form are blank, error messages are added to the ActionMapping object. Note that we are using ActionMessage class, ActionError is now deprecated and will be removed in next version.

  3. Validate methods has two parameters one is ActionMapping, HttpServletRequest.

public ActionErrors validate(
ActionMapping mapping, HttpServletRequest request ) {
ActionErrors errors = new ActionErrors();

if( getName() == null || getName().length() <>
errors.add("name",new ActionMessage("error.name.required"));
}
if( getAddress() == null || getAddress().length() <>
errors.add("address",new ActionMessage("error.address.required"));
}
if( getEmailAddress() == null || getEmailAddress().length() <>
errors.add("emailaddress",new ActionMessage("error.emailaddress.required"));
}

return errors;
}

Struts HTML Tag:

Struts provide HTML tags library for easy creation of user interface.

To use Struts HTML tags we have to include following line <%@ taglib uri=”” prefix =”html” %>




Submit

Reset




Submit

Reset







Struts Validator Framework


  1. Struts Framework provides the functionality to validate the form data. It can be use to validate the data on the users browser as well as on the server side.

  2. Struts Framework emits the java scripts and it can be used to validate the form data on the client browser.

  3. The Validator framework was developed by David Winterfeldt as third-party add-on to Struts.

Using Validator Framework


  1. The Validator Framework uses two XML configuration files validator-rules.xml and validation.xml.

  2. The validator-rules.xml defines the standard validation routines, these are reusable and used in validation.xml. to define the form specific validations.

  3. The validation.xml defines the validations applied to a form bean

Structure of validator-rule.xml


  1. The validation-rules.xml is provided with the Validator Framework and it declares and assigns the logical names to the validation routines

  2. It also contains the client-side javascript code for each validation routine. The validation routines are java methods plugged into the system to perform specific validations.

Eg., Structure

classname="org.apache.struts.validator.FieldChecks"

method="validateMinLength"

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.minlength"

jsFunction="org.apache.commons.validator.javascript.validateMinLength"/>

Structure of validation.xml

  1. This validation.xml configuration file defines which validation routines that are used to validate Form Beans.

  2. You can define validation logic for any number of Form Beans in this configuration file. Inside that definition, you specify the validations you want to apply to the Form Bean's fields.

  3. The definitions in this file use the logical names of Form Beans from the struts-config.xml file along with the logical names of validation routines from the validator-rules.xml file to tie the two together.




property="username"

depends="required">

property="password"

depends="required,mask">

mask

^[0-9a-zA-Z]*$



Client Side Address Validation in Struts

Validator Framework emits the JavaScript code which validates the user input on the browser. To accomplish this we have to follow the following 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.

  5. Build and test: We are required to build the application once the above steps are done before testing.

Developing Simple Struts Tiles Application

what is Struts Tiles?

Tiles are a framework for the development user interface. Tiles is 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.

1 comment:

  1. Hi Muthu, thanks for adding the following stuff, good work......

    ReplyDelete