Struts 2 Theme & Template

Please click the link:
Working with Struts 2 Theme & Template

Struts Tiles

Tiles is 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. For example, if you have to develop a web site having more that 500 page of static content and many dynamically generated pages. The layout of the web site often changes according to the business requirement. In this case you can use the Tiles framework to design the template for the web site and use this template to populate the contents. In future if there is any requirement of site layout change then you have to change the layout in one page. This will change the layout of you whole web site.

Steps To Create Tiles Application


Tiles is very useful framework for the development of web applications. Here are the steps necessary for adding Tiles to your Struts application:

1. Add the Tiles Tag Library Descriptor (TLD) file to the web.xml.
2. Create layout JSPs.
3. Develop the web pages using layouts.
4. Repackage, run and test application.

Add the Tiles TLD to web.xml file
Tiles can can be used with or without Struts. Following entry is required in the web.xml file before you can use the tiles tags in your application.

/tags/struts-tiles
/WEB-INF/struts-tiles.tld



Create layout JSPs.
Our web application layout is divided into four parts: To Banner, Left Navigation Bar, Content Area and Bottom of the page for copy right information. Here is the code for out template (template.jsp):
<%@ page language="java" %>
<%@ taglib uri="/WEB-INF/struts-tiles.tld" prefix="tiles" %>



<tiles:getAsString name="title" ignore="true"/>







Custom Validators in STRUTS

Struts Validator framework provides many validation rules that can be used in the web applications. If you application needs special kind of validation, then you can extend the validator framework to develop your own validation rule.

The client-side validation in Struts is well known. Here are some of the available features:

* required
* requiredif
* validwhen
* minlength
* maxlength
* mask
* byte
* short
* integer
* long
* float
* double
* byteLocale
* shortLocale
* integerLocale
* longLocale
* floatLocale
* doubleLocale
* date
* intRange
* longRange
* floatRange
* doubleRange
* creditCard
* email
* url

These are found in the validator-rules.xml inside the tags. The validator-rules.xml file is found in the commons-validator jar.

Let us know create a new validator for entering the name field of a form. The form should accept only "administrator" for the name field. To accomplish this edit the validator-rules.xml and add the following code under the tag:


0) {
jcv_handleErrors(fields, focusField);
}
return isValid;
}
]]>

Client Side Address Validation in Struts

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.

Enabling the Validator plug- in
To enable the validator plug-in open the file struts-config.xml and make sure that following line is present in the file.





Creating Message Resources
Message resources are used by the Validator Framework to generate the validation error messages. In our application we need to define the messages for name, Address and E-mail address. Open the Struts\strutstutorial\web\WEB-INF\MessageResources.properties file and add the following lines:
AddressForm.name=Name
AddressForm.address=Address
AddressForm.emailAddress=E-mail address

Developing Validation rules
In this application we are adding only one validation that the fields on the form should not be blank. Add the following code in the validation.xml.











The above definition defines the validation for the form fields name, address and emailAddress. The attribute depends="required" instructs the Validator Framework to generate the JavaScript that checks that the fields are not left blank. If the fields are left blank then JavaScript shows the error message. In the error message the message are taken from the key defined in the tag. The value of key is taken from the message resources (Struts\strutstutorial\web\WEB-INF\MessageResources.properties).

Applying Validation rules to JSP
Now create the AddressJavascriptValidation.jsp file to test the application. The code for AddressJavascriptValidation.jsp is as follows:
<%@ taglib uri="/tags/struts-bean" prefix="bean" %>
<%@ taglib uri="/tags/struts-html" prefix="html" %>



<bean:message key="welcome.title"/>





This application shows the use of Struts Validator.

The following form contains fields that are processed by Struts Validator.

Fill in the form and see how JavaScript generated by Validator Framework validates the form.























Please Enter the Following Details

Name



Address



E-mail address



Save

Cancel









The code is used to plug-in the Validator JavaScript.

Create the following entry in the struts-config.xml for the mapping the /AddressJavascriptValidation url for handling the form submission through AddressJavascriptValidation.jsp.




Add the following line in the index.jsp to call the form.


  • Client Side Validation for Address Form


    The Address Form that validates the data on the client side using Stuts Validator generated JavaScript.
  • Struts 2 Features

    The strut-2 framework is designed for the compilation of the entire development cycle including of building, developing and maintaining the whole application. It is very extensible as each class of the framework is based on an Interface and all the base classes are given an extra application and even you can add your own. The basic platform requirements are Servlet API 2.4, JSP API 2.0 and Java 5.

    How Struts Works

    The basic purpose of the Java Servlets in struts is to handle requests made by the client or by web browsers. In struts JavaServerPages (JSP) are used to design the dynamic web pages. In struts, servlets helps to route request which has been made by the web browsers to the appropriate ServerPage. The use of servlet as a router helps to make the web applications easier to design, create, and maintain. Struts is purely based on the Model- View- Contoller (MVC) design pattern. It is one of the best and most well developed design patterns in use. By using the MVC architecture we break the processing in three sections named Model, the View, and the Controller. Below we are describing the working of struts.

    1. As we all are well aware of the fact that each application we develop has a deployment descriptor i.e. WEB-INF/web.xml. This is the file which the container reads.
    This file has all the configuration information which we have defined for our web application. The configuration information includes the index file, the default welcome page, the mapping of our servlets including path and the extension name, any init parameters, information related to the context elements.
    In the file WEB-INF/web.xml of struts application we need to configure the Struts ActionServlet which handles all the request made by the web browsers to a given mapping. ActionServlet is the central component of the Struts controller. This servlet extends the HttpServlet. This servlet basically performs two important things. First is : When the container gets start, it reads the Struts Configuration files and loads it into memory in the init() method. You will know more about the Struts Configuration files below. Second point is: It intercepts the HTTP request in the doGet() and doPost() method and handles it appropriately.

    2. In struts application we have another xml file which is a Struts configuration file named as struts.config.xml. The name of this file can be changed. The name of the struts configuration file can be configured in the web.xml file. This file is placed under the WEB-INF directory of the web application. It is an XML document that describes all or part of Struts application. This file has all the information about many types of Struts resources and configures their interaction. This file is used to associate paths with the controller components of your application., known as Action classes like . This tag tells the Struts ActionServlet that whenever the incoming request is http://myhost/myapp/login.do, then it must invoke the controller component LoginAction. Above, you can see that we have written .do in the URL. This mapping is done to tell the web application that whenever a request is received with the .do extension then it should be appended to the URL.

    3. For each action we also have to configure Struts with the names of the resulting pages that will be shown as a result of that action. In our application there can be more than one view which depends on the result of an action. One can be for a success and the other for the failure. If the result action is "success" then the action tells the ActionServlet that the action has been successfully accomplished or vice- versa. The struts knows how to forward the specific page to the concerned destination. The model which we want to use is entirely to you, the model is called from within the controller components.

    4. Action can also get associate with a JavaBean in our Struts configuration file. Java bean is nothing but a class having getter and setter methods that can be used to communicate between the view and the controller layer. These java beans are validated by invoking the validate() method on the ActionForm by the help of the Struts system. The client sends the request by the normal form submission by using Get or Post method, and the Struts system updates that data in the Bean before calling the controller components.

    5. The view we use in the struts can be either Jsp page, Velocity templates, XSLT pages etc. In struts there are set of JSP tags which has been bundled with the struts distribution, but it is not mandatory to use only Jsp tags, even plain HTML files can be used within our Struts application but the disadvantage of using the html is that it can't take the full advantage of all the dynamic features provided in the struts framework.
    The framework includes a set of custom tag libraries that facilitate in creating the user interfaces that can interact gracefully with ActionForm beans. The struts Jsp taglibs has a number of generic and struts specific tags tags which helps you to use dynamic data in your view. These tags helps us to interact with your controller without writing much java code inside your jsp. These tags are used create forms, internally forward to other pages by interacting with the bean and helps us to invoke other actions of the web application.
    There are many tags provided to you in the struts frameworks which helps you in sending error messages, internationalization etc.


    Note: The points we have described above will be in effect if and only if when the ActionServlet is handling the request. When the request is submitted to the container which call the ActionServlet, make sure that the extension of the file which we want to access should have the extension .do.

    Struts working:

    Process flow:

    web.xml : Whenever the container gets start up the first work it does is to check the web.xml file and determine what struts action Servlets exist. The container is responsible for mapping all the file request to the correct action Servlet.

    A Request : This is the second step performed by the container after checking the web.xml file. In this the user submits a form within a browser and the request is intercepted by the controller.

    The Controller : This is the heart of the container. Most Struts application will have only one controller that is ActionServlet which is responsible for directing several Actions. The controller determines what action is required and sends the information to be processed by an action Bean. The key advantage of having a controller is its ability to control the flow of logic through the highly controlled, centralized points.

    struts.config.xml : Struts has a configuration file to store mappings of actions. By using this file there is no need to hard code the module which will be called within a component. The one more responsibility of the controller is to check the struts.config.xml file to determine which module to be called upon an action request. Struts only reads the struts.config.xml file upon start up.

    Model : The model is basically a business logic part which takes the response from the user and stores the result for the duration of the process. This is a great place to perform the preprocessing of the data received from request. It is possible to reuse the same model for many page requests. Struts provides the ActionForm and the Action classes which can be extended to create the model objects.

    View : The view in struts framework is mainly a jsp page which is responsible for producing the output to the user.

    Struts tag libraries : These are struts components helps us to integrate the struts framework within the project's logic. These struts tag libraries are used within the JSP page. This means that the controller and the model part can't make use of the tag library but instead use the struts class library for strut process control.

    Property file : It is used to store the messages that an object or page can use. Properties files can be used to store the titles and other string data. We can create many property files to handle different languages.

    Business objects : It is the place where the rules of the actual project exists. These are the modules which just regulate the day- to- day site activities.

    The Response : This is the output of the View JSP object.

    Understanding Struts Controller

    The class org.apache.struts.action.ActionServlet is the heart of the Struts Framework. It is the Controller part of the Struts Framework. 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


    This servlet is responsible for handing all the request for the Struts Framework, user can map the specific pattern of request to the ActionServlet. 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. Following code form the web.xml file shows the mapping.


    action
    *.do


    What is Action Class?


    An Action class in the struts application extends Struts 'org.apache.struts.action.Action" Class. Action class acts as wrapper around the business logic and provides an inteface to the application's Model layer. 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 procssed data from business layer to the view layer.

    An Action works as an adapter between the contents of an incoming HTTP request and the business logic that corresponds to it. Then the struts controller (ActionServlet) slects 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. In the Action Class don't add the business process logic, instead move the database and business process logic to the process or dao layer.

    The ActionServlet (commad) passes the parameterized class to Action Form using the execute() method. 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.

    Developing our Action Class?

    Our Action class (TestAction.java) is simple class that only forwards the TestAction.jsp. Our Action class returns the ActionForward called "testAction", which is defined in the struts-config.xml file (action mapping is show later in this page). Here is code of our Action Class:

    TestAction.java
    package roseindia.net;

    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;

    import org.apache.struts.action.Action;
    import org.apache.struts.action.ActionForm;
    import org.apache.struts.action.ActionForward;
    import org.apache.struts.action.ActionMapping;

    public class TestAction extends Action
    {
    public ActionForward execute(
    ActionMapping mapping,
    ActionForm form,
    HttpServletRequest request,
    HttpServletResponse response) throws Exception{
    return mapping.findForward("testAction");
    }
    }


    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



    What is ActionForm?


    An ActionForm is a JavaBean that extends org.apache.struts.action.ActionForm. 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.

    We will first create the class AddressForm which extends the ActionForm class. Here is the code of the class:

    AddressForm.java
    package roseindia.net;

    import javax.servlet.http.HttpServletRequest;

    import org.apache.struts.action.*;


    /**
    * @author Deepak Kumar
    * @Web http://www.roseindia.net
    * @Email roseindia_net@yahoo.com
    */

    /**
    * Form bean for the Address Entry Screen.
    *
    */
    public class AddressForm extends ActionForm
    {
    private String name=null;
    private String address=null;
    private String emailAddress=null;

    public void setName(String name){
    this.name=name;
    }

    public String getName(){
    return this.name;
    }

    public void setAddress(String address){
    this.address=address;
    }

    public String getAddress(){
    return this.address;
    }


    public void setEmailAddress(String emailAddress){
    this.emailAddress=emailAddress;
    }

    public String getEmailAddress(){
    return this.emailAddress;
    }


    /**
    * Reset all properties to their default values.
    *
    * @param mapping The mapping used to select this instance
    * @param request The servlet request we are processing
    */
    public void reset(ActionMapping mapping, HttpServletRequest request) {
    this.name=null;
    this.address=null;
    this.emailAddress=null;
    }

    /**
    * Reset all properties to their default values.
    *
    * @param mapping The mapping used to select this instance
    * @param request The servlet request we are processing
    * @return errors
    */
    public ActionErrors validate(
    ActionMapping mapping, HttpServletRequest request ) {
    ActionErrors errors = new ActionErrors();

    if( getName() == null || getName().length() < 1 ) { errors.add("name",new ActionMessage("error.name.required")); } if( getAddress() == null || getAddress().length() < 1 ) { errors.add("address",new ActionMessage("error.address.required")); } if( getEmailAddress() == null || getEmailAddress().length() < 1 ) { errors.add("emailaddress",new ActionMessage("error.emailaddress.required")); } return errors; } } The above class populates the Address Form data and validates it. 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.
    Struts HTML Tags



    Struts provides HTML tag library for easy creation of user interfaces. In this lesson I will show you what all Struts HTML Tags are available to the JSP for the development of user interfaces.

    To use the Struts HTML Tags we have to include the following line in our JSP file:

    <%@ taglib uri="/tags/struts-html" prefix="html" %>

    above code makes available the tag to the jsp.


    Struts HTML Tags
    Looks up the message corresponding to the given key in the message resources and displays it.
    Tag creates the password field. The string is stored in the property named prop in the form bean.
    Tag creates the text field. The string is retrieved from and later stored in the property named text1 in the form bean.
    Submit Tag creates a submit button with the provided content as the button text.
    Reset Tag creates a reset button with the provided content as the button text.
    Tag prints all the available error on the page.
    Tag creates the file upload element on the form. The property must be of the type org.apache.struts.upload.FormFile.
    Tag creates check box on the form.
    Tag creates the hidden html element on the form.
    Tag creates the check box on the form.
    Tag creates list box on the form. The property selectBox must be an array of supported data-types, and the user may select several entries. Use to specify the entries.
    Tag creates the text area on the form.
    Tag is used to create the HTML Form for posting the data on the server.
    Tag generates the base tag. tells the browser to pretend that the current page is located at some URL other than where the browser found it. Any relative reference will be calculated from the URL given by instead of the actual URL. goes in the section.
    Tag renders an HTML Element.