Struts 1 Form validation using ActionForm’s validate() method

In this article, we will display a login form to the user to provide userid and password and validate them using ActionForm’s validate() method to display any validation errors on the input page.

For this, we will be modifying the Hello World application we created earlier. You can refer details on the same here :

Struts Hello World
 

Here are the changes :

Actionform

In addtion to holding the properties and getters and setters, the Form can also perform simple validations. For this, we need to override the ActionFrom’s validate() method in our Form.

The validate() method returns an ActionErrors instance. If its not null, then the validation fails, and Struts redisplays the form to the user along with any error messages.

package com.topjavatutorial.app;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;

public class HelloForm extends ActionForm {

  private String userId;
  private String password;

  public String getUserId() {
    return userId;
  }
  public void setUserId(String userId) {
    this.userId = userId;
  }
  public String getPassword() {
    return password;
  }
  public void setPassword(String password) {
    this.password = password;
  }
  
  public ActionErrors validate(ActionMapping mapping,
      HttpServletRequest request) {
    ActionErrors errors = new ActionErrors();

    if (userId == null || userId.length() == 0) {
      errors.add("userId", new ActionMessage("userId.not.entered"));
    }
    
    if (password == null || password.length() == 0) {
      errors.add("password", new ActionMessage("password.not.entered"));
    }

    return errors;
  }
  public void reset(ActionMapping mapping, HttpServletRequest request) {
    userId="";
    password="";
  }
}

The ActionMessages added in ActionErrors instance contain keys to messages stored in properties file as shown below :

 

Input JSP

To display any validation error messages for the input fields, we can add a html:errors tag next to the form field.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
  pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%>
<%@ taglib uri="http://struts.apache.org/tags-html" prefix="html"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Hello world</title>
</head>
<body>
  <html:form action="helloWorld.do">
    <table>
      <tr>
        <td>UserId:</td>
        <td><html:text property="userId"></html:text></td>
        <td><html:errors property="userId" /></td>
      </tr>
      <tr>
        <td>Password:</td>
        <td><html:text property="password"></html:text></td>
        <td><html:errors property="password" /></td>
      </tr>
      <tr>
        <td colspan="2" align="center">
          <html:submit value="Submit" />
        </td>
      </tr>
    </table>
  </html:form>
</body>
</html>

 

Action class

If the validation is successful, the execute() method in Action class is executed and control is forwatded to the success page(Hello.jsp).

package com.topjavatutorial.app;

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 HelloAction extends Action {

  public ActionForward execute(ActionMapping mapping, ActionForm form,
      HttpServletRequest request, HttpServletResponse response)
      throws Exception {

    return mapping.findForward("success");
  }
}

 

Hello.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
  pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%>
<%@ taglib uri="http://struts.apache.org/tags-html" prefix="html"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Hello world</title>
</head>
<body>Welcome
</body>
</html>

 

struts-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 1.3//EN"
"http://jakarta.apache.org/struts/dtds/struts-config_1_3.dtd">

<struts-config>

  <form-beans>
    <form-bean name="helloForm" type="com.topjavatutorial.app.HelloForm" />
  </form-beans>

  <action-mappings>
    <action path="/helloWorld" type="com.topjavatutorial.app.HelloAction"
      name="helloForm" validate="true" input="/index.jsp">
      <forward name="success" path="/Hello.jsp" />
    </action>
  </action-mappings>
  <message-resources parameter="com/topjavatutorial/app/ApplicationResources" />
</struts-config>

Deploy and Test

Now, if you deploy the web application on the server and test the following url in the browser, you can verify if the validation is working correctly.

http://localhost:8080/StrutsHello/
 

If you click on the submit button without entering userid and password, you should see following screen :

Now if you enter userid & pwd, you should get the success page.

Here is the final project structure for this:

Common error messages and questions

  • Where does Struts a controller redirect when a form validation fails?

    If there are any validation errors, the “execute” method of the action class will not get called; instead the control will get redirected to the value in the “input” attribute in the “action” element of “struts-config.xml”.

  •  

  • javax.servlet.ServletException: java.lang.NullPointerException with struts validate method

    Make sure that the input page and success page have properties that are populated when control is redirected.

  •  

  • Forwarding to input page fails in struts validate() method

    Check your properties file to make sure that you put the related error message value there. Also make sure you have referred it in your struts-config.xml.

    Also check that your From extends the ActionForm and you are overriding the validate() method properly.

    It might help to add breakpoints in the ActionForm for debugging.

  •  

  • Page doesn’t resubmit after fixing validation errors

    The issue could be in the struts-config.xml file. Please check to make sure you have correct forwards there.

  •  

  • Is validate() called before Struts populates the ActionForm or after ?

    Struts populates the ActionForm subclass with the data first and then calls validate() to perform any validations needed.

 

© 2017, https:. All rights reserved. On republishing this post, you must provide link to original post

Leave a Reply.. code can be added in <code> </code> tags