Showing posts with label Struts. Show all posts
Showing posts with label Struts. Show all posts

Creating Own (Custom) Validations in Struts & Adding New Validation Rule , Definition with Example code

Useful validation methods like validateRequired , validateEmail , validateCreditCard , validateInteger , validateDate , ValidateMinLength and lotmore methods are already packaged with Struts Validator Framework . But application may require some specific validation method which may not be available with Struts validator. But it has a flexibility to create and add new validation rules which can be reused in any form. Writing custom validation method in a action form may not be reused . So you need to write in every form. Now let us create a custom validation method and add to the validation-rules.xml. For example , an Employee is assigned a target date to complete the work .The employer should not assign a date which is already past or sunday. DateValidate method is available in validation-rules.xml to check wheather the given date is valid (dd/MM/yyyy) or not. Now we have to write code for checking the given date is already passed or sunday .
Major Steps to create custom validation
1. Writing code for validation method
2. Adding Validation rule for the above method in the validation-rules.xml file
3. Adding new validation definitions to validation.xml file
4. Adding necessary error messages in the ApplicationResources.properties / MessageResources.properties.
Now let us go through the above steps in detail
Ist Step is writing code for Validation Method in our example it is sundayValidate to check the given date is already passed or sunday . The vaildation method should have the arguments / signatures as given below public static boolean validateSunday(Object bean,ValidatorAction val_action,Field field,ActionErrors errors,HttpServletRequest request) . The complete code is as follows. The validateSunday method is written in a class . In our example it is written in the class ValidationUtil under the util package.
  
package util;
import java.util.Calendar;
import java.util.GregorianCalendar;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.validator.Field;
import org.apache.commons.validator.ValidatorAction;
import org.apache.commons.validator.ValidatorUtil;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.validator.Resources;
public class ValidationUtil
{
public static boolean validateSunday(Object bean,ValidatorAction val_action,Field field,ActionErrors errors,HttpServletRequest request) {
String value = ValidatorUtil.getValueAsString(bean, field.getProperty());
try {
Calendar cal = Calendar.getInstance();
Calendar today = Calendar.getInstance();
today.set(today.get(Calendar.YEAR),today.get(Calendar.MONTH), today.get(Calendar.DAY_OF_MONTH), 12,0,0);
int dd=Integer.parseInt(value.substring(0,2));
int mm =Integer.parseInt(value.substring(3,5));
int yyyy = Integer.parseInt(value.substring(6,10));
cal.set(yyyy ,mm-1, dd ,12,0,0);
int DOW = cal.get(Calendar.DAY_OF_WEEK); // 1=Monday
if (cal.before(today) || (DOW-1)==0) {
errors.add(field.getKey(), Resources.getActionError(request,val_action,field));
return false;
}
} catch (Exception e) {
errors.add(field.getKey(), Resources.getActionError(request,val_action,field));
return false;
}
return true;
}
}

In the above method , Object is Form Bean object which contains the field values to be validated. Field object retrieves the <field> definition (field name) from the validation.xml for the field which is currently being validated. getValueAsString() method is used to retrieve the value for the field name (in our example targetDate) returned by the field.getProperty() from the Form bean . The logic checks the targetDate date is sunday or it is a past date . If it is sunday or old date , then the error message is added to ActionError object.

Now the 2nd step is adding Validation rule for the above method in the validation-rules.xml file
  
<form-validation>
<global>
.....
......
<validator name="sunday" classname="util.ValidationUtil" method="validateSunday"
methodParams="java.lang.Object,
org.apache.commons.validator.ValidatorAction,
org.apache.commons.validator.Field,
org.apache.struts.action.ActionErrors,
javax.servlet.http.HttpServletRequest"
depends=""
msg="errors.sunday">
</validator>
.....
</global>
</form-validation>

The validation method is given a name (in our example sunday) by using name attribute as given above . We have to also mention the class name of the method using classname attribute . Method name is mentioned by method attribute . The above validation rule can be referenced by field tag's depends attribute using name (in our example sunday) . Note : Validation rule must be placed in <global> element in validation-rules.xml file.

Now 3rd step is adding new validation definitions to validation.xml file whic is as follows .
  
<form-validation>
<formset>
.....
<form name="targetFrm">
<field property="empCode" depends="required">
<arg0 key="targetFrm.empCode" />
</field>
<field property="targetDate" depends="required, date, sunday">
<arg0 key="targetFrm.targetDate" />
<arg1 key="targetFrm.targetDate" />
<arg2 key="targetFrm.targetDate" />
<var>
<var-name>datePatternStrict</var-name>
<var-value>dd/MM/yyyy</var-value>
</var>
</field>
</form>
....
</formset>
</form-validation>

In the above definition field tag mentions the property name to be validated . depends attribute mentions the method reference to be called for validation. required calls the requiredMethod , date calls the dateValidate . sunday calls the sundayValidate which is a custom validation method written by us and defined in the validation-rules.xml file. required and date are already defined by default in the validation-rules.xml file with errors.required and errors.date message

Final and 4th step is adding error messages to ApplicationResources.properties
  
targetFrm.empCode=Employee Code
targetFrm.targetDate=Target Date
# general error msgs
errors.required={0} is required.
errors.sunday={0} is either old date or Sunday

The jsp code (part) is given below.
targetDate.jsp
  
<HTML>
......
<TITLE>Employee Targetdate assign</TITLE>
</HEAD>
<body> <html:errors />
<html:javascript formName="targetFrm" />
<html:form action="/targetDate">
<bean:message key="targetFrm.empCode" />
<html:text property="empCode"></html:text> <br />
<bean:message key="targetFrm.targetDate" />
<html:text property="targetDate"></html:text> <br />
<html:submit value="Submit"></html:submit>
</html:form> </body>
....
</HTML>

The struts-config.xml (part) code is as follows
  
<form-beans>
</form-bean>
<form-bean name="targetFrm" type="strutsvalidatorweb.forms.empForm">
</form-bean>
</form-beans>

<action-mappings>
<action name="targetFrm" path="/targetDate" scope="request" type="strutsvalidatorweb.actions.empEnty" validate="true" input="/targetDate.jsp" parameter="method">
<forward name="target" path="./target.jsp">
</forward>
</action>
</action-mappings>

empForm code (part) is given below
  
public class empForm extends ValidatorForm {
private String empCode = null;
private String targetDate=null;
public String getEmpCode() {return empCode;}
public String getEmpName() {return empName;}
public String getTargetDate() {return targetDate;}
public void setTargetDate(String string) {targetDate = string;}
}


For more detail about Struts Validator Framework with example , please visit Struts validator framework example
Output :

Note : In the above jsp , input date should be given as dd/MM/yyyy (total 10 digits , year should be in 4 digits) because we have given date pattern as datePatternStrict with the value dd/MM/yyyy. Other date format strictly not accepted. To accept other format you have to give datePattern , but you need to change code to split the date in the the validateSunday method .
Read more...

Configure web.xml for Struts | specify struts-config.xml in Deployment Descriptor

One of benefits using the Struts framework is that application’s configuration can be specified in an external centralised configuration file (struts-config.xml) instead of being hard coded into the application. This simplifies development because changes can be made to the application without having to recompile any code. Struts configure files (struts-config.xml) are specified in the web.xml as shown below
<web-app>
<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>
<load-on-startup>1</load-on-startup>
</servlet>
......
</web-app>


The Struts configuration file is specified by declaring config parameter is a servlet initialization parameter . The config parameter must be set to your configuration file with the relative path of Web application , which will be the protected /WEB-INF/ directory so that it can be accessed only from server-side applications.
Struts supports the use of multiple configuration files. Configuration settings can be broken down into 2 or more files, which allows teams of developers to work on an application in parallel without having the configuration file be a point of contention. Multiple configuration files can be specified in web.xml as shown below seperated by comma . If there is any overlap among the files’ settings, Struts will use the last settings specified. For example, if struts-config.xml specifies a setting and then struts-config2.xml specifies the same setting with a different value, the setting in struts-config2.xml will override the one in struts-config.xml, provided that file struts-config2.xml is loaded after file struts-config.xml.
The following configuration shows the how to configure multiple configuration files.
<init-param>
<param-name>config</param-name>
<param-value>
/WEB-INF/struts-config.xml, /WEB-INF/struts-config2.xml, /WEB-INF/struts-config3.xml,
</param-value>
</init-param>

Struts version 1.1 added support for application modules. The module feature allows applications to be broken as mini application inside a large application. For this we have to create a separate configuration file for each module, as shown below
<servlet>
<param-name>config</param-name>
<param-value>/WEB-INF/struts-config.xml</param-value>
</init-param>

<init-param>
<param-name>config/ModuleA</param-name>
<param-value>/WEB-INF/struts-config-moduleB.xml</param-value>
</init-param>

<init-param>
<param-name>config/ModuleB</param-name>
<param-value>/WEB-INF/struts-config-moduleA.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>


Note : For module configuration files, parameter names must begin with config/ in order for Struts to recognize them. eg. config/moduleA , config/moduleB . Following / is the logic name for the modules.




Read more...

What is MVC (Model 2) Architecture? Use of Struts Framework for MVC

MVC stands for Model, View, Controller .There are two models are there for building JSP based Web applications. Model 1 & Model 2 . Model 2 is referred to MVC (Model-View-Controller) . The main purpose of the MVC architecture is to separate the business logic and the data from the presentation to the user. (Model- (bean,EJB), View - (Html,Jsp),Controller -(ActionServlet) )

Benefits of MVC : .
They are resuable : Maintenance of large applications are very easy. Suppose if you want to convert your application to support mobile browsing, yuo have to just change the view (JSP) part. No need to change the business logic part as it is seperate.
        1) Model : In the MVC architecture , Model components provide an interface to the data and / or services used by an application. Controller does not have the code for manipulating an applications's data. Instead they communicate with the model components that perform the data access and manipulation. Thus the model component provides the business logic. Model components can be a basic java bean or EJB or Web Services.
           2) View : View Components are used to generate the response to the browser. Example of View Components are JSP or HTML Pages.
             3) Controller : This is the core of MVC. This is a servlet that receives requests for the application and manages the flow of data between the Model components and View Components.

MVC can be implemented by the frame work Struts or Spring

Read more...

 
Copyright 2011 Java Online