Posts Tagged ‘Model–view–controller’

English: Logo of Apache Struts

Apache Struts has changed the way we develop a Web application. Since its inception as an MVC architecture, Struts has been extensively used in J2EE world to develop robust, extendable and effective web applications.

Introduction to Struts Validation Framework

One of the important features of Struts framework is Struts Validation framework that performs validation on incoming form data. Validation framework was introduced by David Winterfeldt as an external plugin to Struts framework. It’s functionality has since been split so that validator can serve as the basis for a independant component and is now part of Jakarta Commons.

The Struts framework’s simple validation interface alleviates much of the headache associated with handling data validation, allowing you to focus on validation code and not on the mechanics of capturing data and redisplaying incomplete or invalid data.

In order to do form validation without Validator framework, one has to use validate() method of the form bean (ActionForm class) to perform this task. Also one has to handle error messages during manual validation. Lot of fields that we validate require same logic to validate them, hence code is unneccessarily duplicated (if not managed properly).

Validation framework comes with set of useful routines to handle form validation automatically and it can handle both server side as well as client side form validation. If certain validation is not present, you can create your own validation logic and plug it into validation framework as a re-usable component.

Validator uses two XML configuration files to determine which validation routines should be installed and how they should be applied for a given application, respectively. The first configuration file, validator-rules.xml, declares the validation routines that should be plugged into the framework and provides logical names for each of the validations. The validator-rules.xml file also defines client-side JavaScript code for each validation routine. Validator can be configured to send this JavaScript code to the browser so that validations are performed on the client side as well as on the server side.

The second configuration file, validation.xml, defines which validation routines should be applied to which Form Beans. 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.

Using the Validator framework involves enabling the Validator plug-in, configuring Validator’s two configuration files, and creating Form Beans that extend the Validator’s ActionForm subclasses. The following sections explain in detail how to configure and use Validator.

Create a Struts project

Create a struts web application project. I assume you have working environment set for a Struts project. If not then go through the tutorial: Creating Struts application using Eclipse and create a struts project.

Create Form Beans

struts validator form bean
Create a form bean in your project called CustomerForm and copy following code in it.

package net.viralpatel.struts.validation.form;
import org.apache.struts.validator.ValidatorForm;
public class CustomerForm extends ValidatorForm {
    
    private String name;
    private String telephone;
    private String email;
    private int age;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getTelephone() {
        return telephone;
    }
    public void setTelephone(String telephone) {
        this.telephone = telephone;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
}

We will use this validator plugin to validate this form. Note that the form bean is extended from class ValidatorForm and not ActionForm as we generally do in Struts project.

Add Validator Plug-in in struts-config.xml

In order to use Validator in our project we need to configure it in struts-config.xml file. For this add following code in your struts-config.xml file.

<!-- Validator Configuration -->
<plug-in className="org.apache.struts.validator.ValidatorPlugIn">
    <set-property property="pathnames"
        value="/WEB-INF/validator-rules.xml,
                /WEB-INF/validation.xml" />
</plug-in>

This definition tells Struts to load and initialize the Validator plug-in for your application. Upon initialization, the plug-in loads the comma-delimited list of Validator config files specified by the pathnames property. Each config file’s path should be specified by use of a Web application-relative path, as shown in the previous example.

Define validations for the form

validation.xml file struts validator framework

Create a file validation.xml in your applications WEB-INF directory. And copy following content in it.

<?xml version="1.0" encoding="UTF-8" ?>
<!--DOCTYPE form-validation PUBLIC
          "-//Apache Software Foundation//DTD Commons Validator Rules Configuration 1.1.3//EN"
          "http://jakarta.apache.org/commons/dtds/validator_1_1_3.dtd">
<form-validation>
<global>
    <constant>
    <constant-name>telephoneFormat</constant-name>
    <constant-value>^\d{5,10}$</constant-value>
    </constant>
</global>
<formset>
    <form name="CustomerForm">
        <field property="name" depends="required">
            <arg key="label.name" />
        </field>
        <field property="age" depends="required, integer, intRange">
            <arg0 key="label.age" />
            <arg1 key="${var:min}" resource="false"/>
            <arg2 key="${var:max}" resource="false"/>
            <var>
                <var-name>min</var-name>
                <var-value>1</var-value>
            </var>
            <var>
                <var-name>max</var-name>
                <var-value>125</var-value>
            </var>
        </field>
        <field property="telephone" depends="required, mask">
            <arg key="label.telephone" />
            <arg1 key="label.telephone" />
            <var>
                <var-name>mask</var-name>
                <var-value>${telephoneFormat}</var-value>
            </var>
        </field>
        <field property="email" depends="email">
            <arg0 key="label.email" />
            <arg1 key="label.email" />
        </field>
    </form>
</formset>
</form-validation>

In the above xml file, we have defined the rules for form validation. Note that we are validating form CustomerForm and the fields being validated are name, age, telephone and email. tag defines the validation for a property of form. We can specify different rules like required, integer, email, intRange, mask etc in depends attribute of field tag..

Also you can define constants that can be reused in the validation xml using global constants tag.

Struts-config.xml entry for the action

Following is the entry in struts-config.xml file which maps the Action to our Validator form.

<form-beans>
    <form-bean name="CustomerForm"
        type="net.viralpatel.struts.validation.form.CustomerForm" />
</form-beans>
...
...
...
<action-mappings>
...
    <action path="/customer" name="CustomerForm" validate="true"
        input="/index.jsp"
        type="net.viralpatel.struts.validation.action.CustomerAction">
        <forward name="success" path="/Customer.jsp" />
        <forward name="failure" path="/index.jsp" />
    </action>
...
</action-mappings>

Configuring ApplicationResources.properties

Struts validation framework uses externalization of the error messages. The messages are stored in a property file (ApplicationResource.properties) and are referred by the key values. Copy following in your ApplicationResource.properties (or MessageResource.properties).

label.name= Name
label.email= Email
label.telephone= Telephone
label.age= Age
# general error msgs
errors.header=<font size="2"><UL>
errors.prefix=<LI><span style="color: red">
errors.suffix=</span></LI>
errors.footer=</UL></font>
errors.invalid={0} is invalid.
errors.maxlength={0} can not be greater than {1} characters.
errors.minlength={0} can not be less than {1} characters.
errors.range={0} is not in the range {1} through {2}.
errors.required={0} is required.
errors.byte={0} must be an byte.
errors.date={0} is not a date.
errors.double={0} must be an double.
errors.float={0} must be an float.
errors.integer={0} must be an integer.
errors.long={0} must be an long.
errors.short={0} must be an short.

Create JSP to display the form

Create a JSP file called index.jsp and copy following content in it.

<%@ taglib uri="http://struts.apache.org/tags-html" prefix="html"%>
<%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%>
<html>
<head>
<title>Struts Validation Framework example.</title>
</head>
<body>
<html:errors />
<html:javascript formName="CustomerForm" />
<html:form action="/customer">
    <bean:message key="label.name" />
    <html:text property="name"></html:text>
    <br />
    <bean:message key="label.age" />
    <html:text property="age"></html:text>
    <br />
    <bean:message key="label.email" />
    <html:text property="email"></html:text>
    <br />
    <bean:message key="label.telephone" />
    <html:text property="telephone"></html:text>
    <br />
    <html:submit value="Submit"></html:submit>
</html:form>
</body>
</html>

Running the application

We are done with our application. Now execute it from any web container (Tomcat in my case) and open in browser.
struts validator form screen

Enter any invalid value in the form and press submit.

struts-validator-form-screen2

Reference :http://viralpatel.net

Mostly everyone starts out programming with a Hello World exercise, so let’s not stray from the group since it seems they are doing well…

As we go through this series I will explain concepts like Objective-C (the programming language iOS apps are written in), iPhone development, and programming in general…

Lets get started!

1. Open Xcode and click “Create a new Xcode Project”
2. Select “View-Based Application” and click choose…

3.Give your app the name “HelloWorld

When the application project opens you will be presented with a view similar to this…

If you click on the files from the classes folder you will be able to see the code in the right window. As you can see Apple gives you some pre-written code that is commented out. On that note, I’ll explain to you what a comment is… A comment is text that will not be executed by the compiler (Xcode). A comment that is just one line will with start with a “//” and a comment that is more than one line long is started with a “/*” and ended with a “*/”… Comments come in very useful when developing programs. You can use comments to document code for later viewing or to document code for other developers.

Before we start writing our first app I need introduce and explain a few concepts, OOP (Object Oriented Programming), MVC (Modal View Controller), and “.h” and “.m” files. Let me take a shot at explaining OOP to you… The Object in Object Oriented Programming is basically two files of code (.h and .m) that work together so that a developer can call that code in their own programs. This provides a massive framework for developers so that they don’t have to start completely from scratch. If you are having troubles understanding the object oriented programming concept you can ask me questions by emailing me at Derek@homeschooldev.com.

Now lets start with the “.h” and “.m” files. Open up the “HelloWorldViewController.h” file by single clicking on the file. As you can see, the code is displayed in the window to the right. A “.h” (header) file is a basically a blue print to an object and a “.m” (implementation file) is where all the code is implemented and executed from. If you don’t understand this concept yet, that’s ok, we will come back to it…

MVC (Model View Controller) is something that is used when developing apps for iOS and Mac OS X. It is something that splits up the code and the actual interface that the user sees. Model, is the users data and the data you display to the user, View is what the user interfaces with and a controller is your code that manages the link between the view and the model. This concept may seem edgy now, but it will grow on you very quickly and makes the life of a programmer much easier and organized.

Lets get coding!

In the header file, “HelloWorldViewController.h”, we are going to declare an IBOutlet. An IBOutlet is what connects your code to a visual object, such as a label or a button.

3. Between the curly braces type “IBOutlet UILabel *label;” and outside the curly braces type “-(IBAction)button;”

An IBAction is a method (block of code) that can be called. An IBAction is recognized by the view and allows you to connect that specific method (block of code) to a UI item, such as a button so that the button will execute that block of code.

That’s all we need to do in the header file… Now lets start designing the interface.

4. Open the folder named “Resources” and double click the file named “HelloWorldViewController.xib”

This will bring up a window similar to this:

This is the program you use to design your user interface. On the left you are given a list of objects that you can use in your user interface, to the right of that you are given the window where you put the objects to design the interface, the next window isn’t important right now, and the next window is called the inspector and is the window where you can change all the attributes of nearly everything in your UI.

Lets start designing!

5. From the left window, drag a label onto your view.


6. Now that you have your label on your view, resize the label using the blue lines as a guide.


7. Now center the text in the label using the button in the inspector window:

8. Clear the text from the label using the textfield in the inspector window named “Text”

 


9. Now lets put a button on our view and give it a name using the same methods that we just used to put a label on our view.

We are done designing the view, but the code we are about to write has no idea when to be called. We must add a link between the code and the UI element.

10. Select “Files Owner” from the main view and then click the connections tab on the Inspector window.

On the Inspector window, you can see the IBOutlet and IBAction you defined earlier.

11. Click on the plus button next to the label definition and drag it onto the label on the view.

12. Now drag the plus button next to the “button” definition on to the button in the view. A window will popup asking you when you want to perform this action… You can perform the action when the user touches the button and then lets up, touches the button, double taps the button, and a whole bunch of other things. We are going to use “Touch up Inside”, so select it.

13. Click File>Save or Command+S on your keyboard.

We now have our interface designed and our outlet and action linked up to our view. We can now start writing code.

14. Go the the “HelloWorldViewController.m” file (implementation file), this is where all the work gets done and is the place you write your code.

We are going to need to implement the IBAction we define earlier in our header file and give it some code.

15. Under the “@Implementation” line type:

-(IBAction)button {

}

This is called a method, and it is what’s called when the user presses the button (because we linked this IBAction to the button in interface builder).

This method is kinda boring, don’t you think? It doesn’t do anything…. Lets give it some life!

16. In the new method, type:

“label.text = @”Hello World!”;”

This line of code is assigning the text “Hello World!” to the label that we attached to our IBOutlet definition.

We are done!

17. Click File>Save or Command+S on your keyboard so that you don’t lose your progress.

18. Now you can click Build and Run at the top of the window to run your application in the simulator.

If you followed the instructions correctly you application should build and start up in the simulator with no errors or warnings.

You should see something like this:

If your app didn’t start up correctly or gave you errors, feel free to ask any question so that the community or I can help you.

We have learned a lot in this tutorial, hopefully I have explained everything well enough for you to understand…

Some key items you need to understand before moving on to the next tutorial are, the concepts of MVC and OOP. If you felt I didn’t explain these concepts very well you can leave a comment below or email me if you are needing help understanding them.