Monday, 28 May 2012

Struts Validation Introduction

Validation:
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. Struts Framework emits the java scripts and it can be used to validate the form data on the client browser. Server side validation of the form can be accomplished by sub classing your From Bean with DynaValidatorForm class.

Using Validator Framework

Validator uses the XML file to pickup the validation rules to be applied to an form. In XML validation requirements are defined applied to a form. In case we need special validation rules not provided by the validator framework, we can plug in our own custom validations into Validator.

The Validator Framework uses two XML configuration files validator-rules.xml and validation.xml. The validator-rules.xml defines the standard validation routines, these are reusable and used in validation.xml. to define the form specific validations. The validation.xml defines the validations applied to a form bean.

Example

<form name="logonForm">
<field property="username"
   depends="required">
   <arg key="logonForm.username"/>
  </field>
   <field property="password"
   depends="required,mask">
   <arg key="logonForm.password"/>
   <var>
  <var-name>mask</var-name>
  <var-value>^[0-9a-zA-Z]*$</var-value>
  </var>
  </field>
  </form>

Friday, 25 May 2012

ActionForm

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

import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.*;
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;
  }
 public void reset(ActionMapping mapping, HttpServletRequest request) {
  this.name=null;
  this.address=null;
  this.emailAddress=null;
}

public ActionErrors validate
  ActionMapping mapping, HttpServletRequest request ) {
  ActionErrors errors = new ActionErrors();
  
  ifgetName() == null || getName().length() ) {
  errors.add("name",new ActionMessage("error.name.required"));
  }
  ifgetAddress() == null || getAddress().length() ) {
  errors.add("address",new ActionMessage("error.address.required"));
  }
  ifgetEmailAddress() == null || getEmailAddress().length() ) {
  errors.add("emailaddress",new ActionMessage("error.emailaddress.required"));
  }

  return errors;
  }

AddressAction.java
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 AddressAction extends Action
{
  public ActionForward execute(
  ActionMapping mapping,
  ActionForm form,
  HttpServletRequest request,
  HttpServletResponse responsethrows Exception{
  return mapping.findForward("success");
  }
}


Now we have to create an entry for form bean in the struts-config.xml. Add the following lines in the struts-config.xml file:
<form-bean
name="AddressForm"
type="com.ActionForm.AddressForm"/>

Add the following line in the struts-config.xml file for handling the action "/Address.do":
<action
   path="/Address"
   type="com.Action.AddressAction"
   name="AddressForm"
   scope="request"
   validate="true"
   input="/pages/Address.jsp">
  <forward name="success" path="/pages/success.jsp"/>
</action>


Now create Address.jsp, which is our form for entering the address details. Code for Address.jsp is as follows:

Address.jsp

<%@ taglib uri="/tags/struts-bean" prefix="bean" %>
   
<%@ taglib uri="/tags/struts-html" prefix="html" %>
 
   
<html:html locale="true">

   
<head>

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

   
<html:base/>

   
</head>

   
<body bgcolor="white">

   
<html:form action="/Address">

   
<html:errors/>

   
<table>

       
<tr>

         
<td align="center" colspan="2">
               
<font size="4">Please Enter the Following Details</font>
       
</tr>
       
<tr>
         
<td align="right">
           
Name
         
</td>
         
<td align="left">
           
<html:text property="name" size="30" maxlength="30"/>
         
</td>
       
</tr>
       
<tr>
         
<td align="right">
           
Address
         
</td>
         
<td align="left">
           
<html:text property="address" size="30" maxlength="30"/>
         
</td>
       
</tr>

       
<tr>
         
<td align="right">
            E
-mail address
         
</td>

         
<td align="left">
           
<html:text property="emailAddress" size="30" maxlength="30"/>
         
</td>
       
</tr>
       
<tr>
         
<td align="right">
           
<html:submit>Save</html:submit>
         
</td>
         
<td align="left">
           
<html:cancel>Cancel</html:cancel>
         
</td>
       
</tr>
 
</table>
   
</html:form>
   
</body>
   
</html:html>




Thursday, 24 May 2012

Action Class

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.

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

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 responsethrows Exception{
  return mapping.findForward("testAction");
  }

}

Understanding Action Class
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
Adding the Action Mapping in the struts-config.xmlTo test the application we will add a link in the index.jsp
<html:link page="/TestAction.do">Test the Action</html:link>

 <action
      path="/TestAction">
            <forward name="testAction" path="/pages/TestAction.jsp"/>
   </action>

ActionServlet

Action Servlet :
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.

<servlet>
   <servlet-name>action</servlet-name>
  <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
</servlet>

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

<servlet-mapping>
  <servlet-name>action</servlet-name>
  <url-pattern>*.do</url-pattern>
</servlet-mapping>

The above mapping maps all the requests ending with .do to the ActionServlet. ActionServlet uses the configuration defined in struts-config.xml file to decide the destination of the request. Action Mapping Definitions (described below) is used to map any action.
Example:

Welcome.jsp

<%@ taglib uri="/tags/struts-bean" prefix="bean" %>
<%@ taglib uri="/tags/struts-html" prefix="html" %>
<html:html locale="true">
<head>
   <title><bean:message key="welcome.title"/></title>
   <html:base/>
</head>
  <body bgcolor="white">
  <h3><bean:message key="welcome.heading"/></h3>
  <p><bean:message key="welcome.message"/></p>
</body>
</html:html>

Forwarding the Welcome.do request to Welcome.jsp
  • The "Action Mapping Definitions" is the most important part in the struts-config.xml. This section takes a form defined in the "Form Bean Definitions" section and maps it to an action class.
  • Following code under the <action-mappings> tag is used to forward the request to the Welcome.jsp.
<action  path="/Welcome"
  forward="/pages/Welcome.jsp"
/>

To call this Welcome.jsp file we will use the following code.
<html:link page="/Welcome.do">First Request to the controller
</html:link>

Once the use clicks on on First Request to the controller link on the index page, request (for Welcome.do) is sent to the Controller and the controller forwards the request to Welcome.jsp. The content of Welcome.jsp is displayed to the user.

 

Struts MVC architecture



Struts is fully works on MVC architecture MVC means Model View Controller which explain is as follows
  • The Model contains the logic and ineract with the persistance storage to retrive and manipulate data.
  • The View is responsible for displaying for the results back to the user. In Struts the view layer is implemented using JSP.
  • The Controller Handles all the request from the user and selects the appropriate view to return. In struts the controller's jobis done by ActionServlet.


The following Events happen when the client browser issues an HTTP request.
  1. The Action Servlet receive the request.
  2. struts-config.xml file contains the details regarding Action, ActionForms,ActionMapping and ActionForwards.
  3. During the startup ActionServlet reads the struts-config.xml file and creates a database of configration object. Later while processing the request the ActionServlet makes a decision by refering to the object.
When the ActionServlet receives the request it does the following tasks.
  1. Bundles all the request into a javabeans classwhich extends struts ActionForm class.
  2. Decides which action class to invoketo process the request.
  3. validate the data entered by the user.
  4. The action class process the request with the help of the model component. The model interacts with database and process the request.
  5. After completing the request processing the action Class returns an ActionForward to the controller.
  6. Based on the ActionForward the controller will invoke the appropriate view.
  7. The HTTP response is rendered  back to the user by the view component.