Struts Validation Not Working
843836Oct 16 2004 — edited Jan 27 2005Hello,
I am using JDeveloper to develop a Struts 1.1 application that makes use of the Validator Plug-in and the Tiles Plug-in.
I am new to using the Validator plug-in and feel that I may be missing a step in order to get validation to work. My application has a form (LoginForm) with 2 fields (username and password) and when either of the fields is left blank, I would like a message of the failed validation to appear on my form. I have followed many tutorials online and read a book on struts and still cannot get my validation to work. Here is what I have done thus far:
STRUTS-CONFIG.XML:
<?xml version = '1.0' encoding = 'windows-1252'?>
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.1//EN" "http://jakarta.apache.org/struts/dtds/struts-config_1_1.dtd">
<struts-config>
<form-beans>
<form-bean name="LoginForm" type="org.apache.struts.validator.DynaValidatorActionForm">
<form-property name="username" type="java.lang.String"/>
<form-property name="password" type="java.lang.String"/>
<form-property name="languageFilter" type="java.lang.String"/>
</form-bean>
</form-beans>
<action-mappings>
<action name="LoginForm" path="/login" input="/index.jsp" scope="session" type="Oct5_TestApp.view.LoginAction" validate="true">
<forward name="success" path="msk.home" redirect="true"/>
<forward name="failure" path="/index.jsp" redirect="true"/>
</action>
<action path="/logout" type="Oct5_TestApp.view.LogoutAction">
<forward name="success" path="/index.jsp" redirect="true"/>
<forward name="failure" path="/index.jsp" redirect="true"/>
</action>
</action-mappings>
<controller processorClass="org.apache.struts.tiles.TilesRequestProcessor" locale="true"/>
<message-resources parameter="Oct5_TestApp.view.ApplicationResources"/>
<plug-in className="org.apache.struts.tiles.TilesPlugin">
<set-property property="definitions-config" value="/WEB-INF/tiles-msk.xml"/>
<set-property property="definitions-parser-validate" value="true"/>
<set-property property="moduleAware" value="true"/>
</plug-in>
<plug-in className="org.apache.struts.validator.ValidatorPlugIn">
<set-property property="pathnames" value="/WEB-INF/validator-rules.xml,/WEB-INF/validation.xml"/>
</plug-in>
</struts-config>
VALIDATOR-RULES.XML:
<form-validation>
<global>
<validator name="required"
classname="org.apache.struts.validator.FieldChecks"
method="validateRequired"
methodParams="java.lang.Object,
org.apache.commons.validator.ValidatorAction,
org.apache.commons.validator.Field,
org.apache.struts.action.ActionErrors,
javax.servlet.http.HttpServletRequest"
msg="errors.required">
<javascript><![CDATA[
function validateRequired(form) {
var isValid = true;
var focusField = null;
var i = 0;
var fields = new Array();
oRequired = new required();
for (x in oRequired) {
var field = form[oRequired[x][0]];
if (field.type == 'text' ||
field.type == 'textarea' ||
field.type == 'file' ||
field.type == 'select-one' ||
field.type == 'radio' ||
field.type == 'password') {
var value = '';
// get field's value
if (field.type == "select-one") {
var si = field.selectedIndex;
if (si >= 0) {
value = field.options[si].value;
}
} else {
value = field.value;
}
if (trim(value).length == 0) {
if (i == 0) {
focusField = field;
}
fields[i++] = oRequired[x][1];
isValid = false;
}
}
}
if (fields.length > 0) {
focusField.focus();
alert(fields.join('\n'));
}
return isValid;
}
// Trim whitespace from left and right sides of s.
function trim(s) {
return s.replace( /^\s*/, "" ).replace( /\s*$/, "" );
}
]]>
</javascript>
</validator>
VALIDATION.XML:
<form-validation>
<formset>
<form name="LoginForm">
<field property="username" depends="required">
<arg0 key="error.LoginForm.username"/>
</field>
<field property="password" depends="required">
<arg0 key="error.LoginForm.password"/>
</field>
</form>
</formset>
</form-validation>
APPLICATIONRESOURCES.PROPERTIES:
#Tue Oct 05 11:12:20 EDT 2004
errors.prefix=<li>
errors.suffix=</li>
errors.header=<h3><font color\="red">Validation Error</font></h3>You must correct the following error(s) before proceeding\:<ul>
errors.footer=</ul><hr>
error.LoginForm.username=Username required
error.LoginForm.password=Password required
# Struts Validator Error Messages
errors.required={0} is required.
errors.minlength={0} can not be less than {1} characters.
errors.maxlength={0} can not be greater than {1} characters.
errors.invalid={0} is invalid.
errors.byte={0} must be a byte.
errors.short={0} must be a short.
errors.integer={0} must be an integer.
errors.long={0} must be a long.
errors.float={0} must be a float.
errors.double={0} must be a double.
errors.date={0} is not a date.
errors.range={0} is not in the range {1} through {2}.
errors.creditcard={0} is an invalid credit card number.
errors.email={0} is an invalid e-mail address.
LOGINACTION.JAVA:
package Oct5_TestApp.view;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionErrors;
import java.io.IOException;
import javax.servlet.ServletException;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.struts.validator.DynaValidatorActionForm;
public class LoginAction extends Action
{
/**
* This is the main action called from the Struts framework.
* @param mapping The ActionMapping used to select this instance.
* @param form The optional ActionForm bean for this request.
* @param request The HTTP Request we are processing.
* @param response The HTTP Response we are processing.
* @return
* @throws java.io.IOException
* @throws javax.servlet.ServletException
*/
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
DynaValidatorActionForm LoginForm = (DynaValidatorActionForm) form;
HttpSession session = request.getSession();
try
{
//variable declarations
String username = (String) PropertyUtils.getSimpleProperty(LoginForm, "username");
String password =(String) PropertyUtils.getSimpleProperty(LoginForm, "password");
//username and password verification
if(username != null && username.equals("test") &&
password != null && password.equals("demo") ) {
//successful username and password
return mapping.findForward("success");
}
// Goes into this else if username and password entered are invalid
else {
//clear mapping and request
clean(mapping, request);
System.out.println( "Cleaning ...." );
//failed username and password
return mapping.findForward("failure");
}
}catch (Exception ex)
{
ex.printStackTrace();
}
//failed username and password
return mapping.findForward("failure");
}
//function to clear mapping and request
private void clean(ActionMapping mapping, HttpServletRequest request )
{
//variable declaration to hold session information
HttpSession session = request.getSession();
//mapping verification
if( mapping != null && mapping.getAttribute() != null )
{
//request verification
if ("request".equals(mapping.getScope()))
{
request.removeAttribute(mapping.getAttribute());
System.out.println( "Remove content in request" );
}
else{
session.removeAttribute(mapping.getAttribute());
}
}
//declares session as invalid
session.invalidate();
}
}
INDEX.JSP:
<%@ page language="java" contentType="text/html" %>
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
<%@ taglib uri="/WEB-INF/struts-logic.tld" prefix="logic" %>
<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
<%@ taglib uri="/WEB-INF/struts-tiles.tld" prefix="tiles" %>
<html:html>
<head>
<title>Oct5_TestApp</title>
<html:base/>
</head>
<strong>Oct5_TestApp</strong>
<body>
<html:errors />
<div align="center">
<html:form action="/login" focus="username" onsubmit="return validateForm(this);">
<table width="60%" border="1" cellpadding="3" cellspacing="1" align="center">
<tr>
<td align="left" width="10%">Username: </td>
<td align="left" width="20%"><html:text property="username" size="15"/></td>
<td align="left" width="20%">Select a Language: </td>
<td align="left" width="10%">
<html:select property="languageFilter">
<html:option value="English"></html:option>
<html:option value="Spanish"></html:option>
<html:option value="French"></html:option>
</html:select>
</td>
</tr>
<tr>
<td align="left" width="10%">Password: </td>
<td align="left" width="20%"><html:password property="password" size="15"/></td>
</tr>
<tr>
<td><html:submit/></td>
<td><html:reset/></td>
</tr>
</table>
</html:form>
</div>
</body>
</html:html>
PLEASE HELP!!!
-Christine