View RSS Feed

Struts

How to validate form in Struts 2's action

Rating: 1 votes, 1.00 average.
by , 12-10-2011 at 05:41 AM (6646 Views)
This article will guide you how to validate a form from Strutís action classes. We are going to develop a simple web application that allows user to enter email address and password to login. The email and password will be validated on the server side, in the action class.
You are assumed to be familiar with Java web development using Eclipse IDE and understand how a Struts application works at the fundamental level. You also know how to deploy a Java web application on Tomcat server.
Before getting started, make sure you have the following programs installed on your computer:

  • Java SE 1.6 or later.
  • Eclipse IDE version 3.3.2 or later.
  • Tomcat 6.0.


Setting up the project

Create a new Java web application by going to File -> New -> Project. In the New Project dialog, expand the Web branch, select Dynamic Web Project, click Next. In the New Dynamic Web Project dialog, type the project name as StrutsLoginForm, then click Finish.

Create a new package under src directory: com.struts.study. We will put our Java classes under this package name.

Add the following JAR files under WEB-INF/lib directory:


  • commons-fileupload-1.2.2.jar
  • commons-io-2.0.1.jar
  • commons-lang-2.5.jar
  • freemarker-2.3.16.jar
  • javassist-3.11.0.GA.jar
  • ognl-3.0.1.jar
  • struts2-core-2.2.3.jar
  • xwork-core-2.2.3.jar



Open the web.xml file under WEB-INF directory, type the following code to configure Struts framework intercepts all incoming requests to the application:

XML Code: The deployment descriptor file
<web-app id="WebApp_ID" version="2.4"
    xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
    <display-name>StrutsLoginForm</display-name>
   
    <filter>
      <filter-name>struts2</filter-name>
      <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
    </filter>
   
    <filter-mapping>
      <filter-name>struts2</filter-name>
       <url-pattern>/*</url-pattern>
    </filter-mapping>
       
    <welcome-file-list>
        <welcome-file>login.jsp</welcome-file>
    </welcome-file-list>
</web-app>

Configuring Struts

Create a struts.xml file under src directory with the following content:

XML Code: The Struts configuration file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
   "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
   "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
   
    <package name="main" extends="struts-default">
        <action name="doLogin" class="com.struts.study.LoginAction"
            method="doLogin">
            <result name="success">/result.jsp</result>
            <result name="input">/login.jsp</result>
        </action>
    </package>
   
</struts>
We define an action with name doLogin and we will create an action class LoginAction with method doLogin. We also define two views, success and input, and the corresponding JSP pages. The view success will be rendered if the user has typed both email and password. In case the user left either email field or password field blank, the login page will be re-rendered with validation error messages, as configured by the view input.

Creating the model class

Next, create a model class: User.java. This class contains two member variables and appropriate setters and getters, as following:


Java Code: The model class User.java
package com.struts.study;

public class User {
    private String email;
    private String password;
   
    public String getEmail() {
        return email;
    }
   
    public void setEmail(String email) {
        this.email = email;
    }
   
    public String getPassword() {
        return password;
    }
   
    public void setPassword(String password) {
        this.password = password;
    }
}


Creating the Struts 2's action class

Create a new Java class file, LoginAction under the package com.struts.study. The code of the class is as following:


Java Code: The Struts 2's action class
package com.struts.study;

import com.opensymphony.xwork2.ActionSupport;

public class LoginAction extends ActionSupport {
    private User userBean;
   
    public String doLogin() {
        return SUCCESS;
    }

    public void setUserBean(User userBean) {
        this.userBean = userBean;
    }

    public User getUserBean() {
        return userBean;
    }
   
    public void validateDoLogin() {
        if (userBean.getEmail().length() == 0) {
            addFieldError("userBean.email", "Email is required!");
        }
       
        if (userBean.getPassword().length() == 0) {
            addFieldError("userBean.password", "Password is required!");
        }
               
    }
}


There are some points which we are interested in this class:

  • Our action class extends ActionSupport class to inherit some common properties and methods of an action that the framework provides such as some predefined view constants, add error message methodÖ Although we are not forced to extend the ActionSupport class, it is better to inherit the defaults however.

  • We create a member variable:
    Java Code:
        private User userBean;
    with setter and getter:

    Java Code:
        public void setUserBean(User userBean) {
    
            this.userBean = userBean;
    
        }
    
        public User getUserBean() {
    
            return userBean;
    
        }
    The object userBean is the backing bean object for a form in the view, using the Strutsí form tag.

  • The doLogin method will be invoked when a request ends with /doLogin coming. The formís action of the view login.jsp which we will write later, will points to this URL pattern. This method simply returns a constant, SUCCESS, to tell the framework that it should find the actual JSP page from this logical name. And according to the struts.xml file we have configured, the result.jsp page will be picked up.

  • The validateDoLogin method does the validation stuff actually. The important point here, is the validation method name must start with validate, and followed by the actionís method name. We have the action method named doLogin, so we should write the validation method name as validateDoLogin. The validation method is always invoked before the action method. As you can see in the implementation of this method, the validation is performed against the bean object userBeanís getter methods:

    Java Code:
            if (userBean.getEmail().length() == 0)
    if the length of the email field equals to 0, add a validation error message using the statement:

    Java Code:
                addFieldError("userBean.email", "Email is required!");
    Upon exiting this validation method, the framework checks if any errors message added, it will re-render the form with error messages inserted above the field name. If there is no error message, the framework invokes the doLogin method and pick up the corresponding JSP page.


Creating the view

Letís create the login.jsp page under WebContent directory with the following content:

XML Code: The JSP page login.jsp
<%@ taglib prefix="s" uri="/struts-tags" %>
<%@ page language="java" contentType="text/html; charset=UTF-8"
   pageEncoding="UTF-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Login</title>
</head>
<body>
    <center>
        <h3>Please provide your email and password.</h3>
        <s:form action="doLogin">
            <s:textfield name="userBean.email" label="Email" />
            <s:password name="userBean.password" label="Password" />
            <s:submit value="Login" />
        </s:form>
    </center>
</body>
</html>
We declare to use the Strutsí tag library by the directive:

XML Code:
<%@ taglib prefix="s" uri="/struts-tags" %>
Then we use the tags: <s:form/>, <s:textfield/>, <s:password/>, <s:submit/> to render the login form. The action property of the form tag should match the name of the action we configured in the struts.xml file. The name of the field should match the pattern: beanName.propertyName. The bean object is created as a member variable of the action class, as you seen previously.

Next, we create the result.jsp page with the following content:

XML Code: The JSP file result.jsp
<%@ taglib prefix="s" uri="/struts-tags" %>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
   pageEncoding="ISO-8859-1"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Welcome</title>
</head>
<body>
<center>
    <h2>
        Welcome <s:property value="userBean.email" /> !
    </h2>
</center>
</body>
</html>
This JSP page will be displayed in case the user entered the fields, email and password. It uses the <s:property/> tag to display the email entered by the user.

Testing the validation

Now everything is ready, itís time to deploy the application on Tomcat server and test it. In Eclipse IDE, open the view Servers to add a new server, select Tomcat 6.0, and then add the application StrutsLoginForm as configured project on the server.

Start the server. Open a new browser window and type the following URL into the address bar:
http://localhost:9898/StrutsLoginForm/
Note that the port number maybe different with your Tomcat installation.

The login page should be displayed as follow:

Name:  screenshot1.PNG
Views: 2147
Size:  67.7 KB
Figure: The login page

Leave both fields blank and hit Enter, the error messages should be displayed as the following screenshot:

Name:  screenshot2.PNG
Views: 2127
Size:  69.2 KB
Figure: The validation error messages

Now type values into both fields and hit Enter, the following screen should be displayed:

Name:  screenshot3.PNG
Views: 2129
Size:  67.3 KB
Figure: Login successful screen

And thatís it! The application is working as expected. You have learnt to validate form fields in action class with Struts 2 framework.

Submit "How to validate form in Struts 2's action" to Facebook Submit "How to validate form in Struts 2's action" to Digg Submit "How to validate form in Struts 2's action" to del.icio.us Submit "How to validate form in Struts 2's action" to StumbleUpon Submit "How to validate form in Struts 2's action" to Google

Comments

  1. j2me64's Avatar
    • |
    • permalink
    Great example. But entering the above code in eclipse and then exporting the project as a war-file to the directory webapps of my tomcat 7 installation tomcat cat not start it. I have already successfully doployed other struts applications but I can't figure out what's going wrong here. If somebody could please analyse my war file from

    http://javapup.i-networx.de/StrutsLoginForm.war

    and point me to the errors? Inside eclipse not errors were displayed.
  2. JavaForums's Avatar
    • |
    • permalink
    j2me64, plese ask your questions to the appropriate forum (if you need you can give the ref for this post). You will have a better chance to get a reply there. Our authors are not get paid for answering blog posts yet ;) They can, but they most probably will not.

    Thanks for your understanding.

    P.S. We plan to close comments section for staff blogs..