Struts em Ação, dúvida sobre o forward failure

2 respostas
ricardospinoza

Pessoal,

Estou começando no struts 1.3.8, e no primeiro não entendi o porque o meu forward "sucess" não funciona.

Tenho um formulário com três campos: usuário, senha e confirmação da senha, quando digitado usuário e submetido, o action checa se os dados conferem com um arquivo de properties. se Tudo correr bem, a página sucess.htm é exibida, caso contrário a página failure.html

O problema é que só a página failure.html é exibida indiferente dos dados que eu digite no formulário, gostaria de entender por que ocorre isto.

segue o meu fonte.

register.jsp
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="form"%>
<form:form action="register.do">
		Username:<form:text property="username" />
		<br>		
		Enter password:&lt;form:password property="password1" /&gt;
		<br>
		re-enter password:&lt;form:password property="password2" /&gt;
		<br>
	&lt;form:submit value="Register" /&gt;
&lt;/form:form&gt;
success.html
&lt;html&gt;
&lt;head&gt;
&lt;meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"&gt;
&lt;title&gt;Sucess&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;center&gt;Sucesso - Regsitration suceeded !
<p><a >Try another?</a></p>
&lt;/center&gt;
&lt;/body&gt;
&lt;/html&gt;
failure.html
&lt;html&gt;
&lt;head&gt;
&lt;meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"&gt;
&lt;title&gt;failure&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;center&gt;Falha - Regsitration suceeded !
<p><a >Try again?</a></p>
&lt;/center&gt;
&lt;/body&gt;
&lt;/html&gt;
struts-config.xml
&lt;?xml version=&quot;1.0&quot; encoding=&quot;iso-8859-1&quot;?&gt;

&lt;!DOCTYPE struts-config PUBLIC
        "-//Apache Software Foundation//DTD Struts Configuration 1.3//EN"
        "http://struts.apache.org/dtds/struts-config_1_3.dtd"&gt;
&lt;struts-config&gt;
	&lt;data-sources&gt;
	&lt;/data-sources&gt;
	&lt;form-beans&gt;
		&lt;form-bean name="registerForm" type="app.RegisterForm" /&gt;
	&lt;/form-beans&gt;
	
	&lt;global-forwards&gt;
		&lt;forward type="app.RegisterForm" name="register" path="/register.do" /&gt;
	&lt;/global-forwards&gt;
	&lt;action-mappings&gt;
		&lt;action path="/register" name="registerForm" type="app.RegisterAction"&gt;
			&lt;forward name="success" path="/success.html" /&gt;
			&lt;forward name="failure" path="/failure.html" /&gt;
		&lt;/action&gt;
	&lt;/action-mappings&gt;

&lt;/struts-config&gt;
users.properties
#${user}=${password}
#Mon Aug 19 15:09:45 EDT 2002
CEDRIC=Dumoulin
GEORGE=Franciscus
DAVID=Winterfeldt
TED=Husted
CRAIG=McClanahan
RegisterForm
package app;

import org.apache.struts.action.ActionForm;

public class RegisterForm extends ActionForm {

	protected String username;

	protected String password1;

	protected String password2;

	public String getUsername() {
		return this.username;
	}

	public String getPassword1() {
		return this.password1;
	}

	public String getPassword2() {
		return this.password2;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public void setPassword1(String password) {
		this.password1 = password;
	}

	public void setPassword2(String password) {
		this.password2 = password;
	}
}
RegisterAction
package 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 RegisterAction extends Action {

	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest req, HttpServletResponse res) {
		RegisterForm rf = (RegisterForm) form;

		String username = rf.getUsername();
		String password1 = rf.getPassword1();
		String password2 = rf.getPassword2();

		if (password1.equals(password2)) {

			try {
				UserDirectory.getInstance().setUser(username, password1);
				return mapping.findForward("sucess");
			} catch (UserDirectoryException e) {
				return mapping.findForward("failure");	
			}			
		}
		return mapping.findForward("failure");

	}
}
UserDirectoryException
/*
 * $Header: /home/cvspublic/jakarta-struts/src/example/org/apache/struts/example/LogoffAction.java,v 1.4 2000/09/23 22:53:53 craigmcc Exp $
 * $Revision: 1.4 $
 * $Date: 2000/09/23 22:53:53 $
 *
 * ====================================================================
 *
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 1999 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution, if
 *    any, must include the following acknowlegement:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowlegement may appear in the software itself,
 *    if and wherever such third-party acknowlegements normally appear.
 *
 * 4. The names "The Jakarta Project", "Tomcat", and "Apache Software
 *    Foundation" must not be used to endorse or promote products derived
 *    from this software without prior written permission. For written
 *    permission, please contact [email removido].
 *
 * 5. Products derived from this software may not be called "Apache"
 *    nor may "Apache" appear in their names without prior written
 *    permission of the Apache Group.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation.  For more
 * information on the Apache Software Foundation, please see
 * &lt;http://www.apache.org/&gt;.
 *
 */


/**
 * @author George Franciscus
 * @version $Revision: $ $Date: $
 */
package app;

public class UserDirectoryException extends Exception {

    // ; Empty implementation

}
UserDirectory
package app;

import java.io.*;
import java.util.*;

public class UserDirectory
{

    private static final String UserDirectoryFile = "resources/users.properties";
    private static final String UserDirectoryHeader = "${user}=${password}";
    private static UserDirectory userDirectory = null;
    private static Properties p;

    private UserDirectory()
        throws UserDirectoryException
    {
        InputStream inputstream = null;
        p = null;
        inputstream = getClass().getClassLoader().getResourceAsStream("resources/users.properties");
        if(inputstream == null)
        {
            throw new UserDirectoryException();
        }
        try
        {
            p = new Properties();
            p.load(inputstream);
            inputstream.close();
        }
        catch(IOException ioexception)
        {
            p = null;
            System.out.println(ioexception.getMessage());
            throw new UserDirectoryException();
        }
        finally
        {
            inputstream = null;
        }
    }

    public String fixId(String s)
    {
        return s.toUpperCase();
    }

    public static UserDirectory getInstance()
        throws UserDirectoryException
    {
        if(userDirectory == null)
        {
            userDirectory = new UserDirectory();
        }
        return userDirectory;
    }

    public String getPassword(String s)
    {
        return p.getProperty(s);
    }

    public Enumeration getUserIds()
    {
        return p.propertyNames();
    }

    public boolean isUserExist(String s)
    {
        if(s == null)
        {
            return false;
        } else
        {
            return p.getProperty(s) != null;
        }
    }

    public boolean isValidPassword(String s, String s1)
    {
        if(s1 == null)
        {
            return false;
        }
        String s2 = fixId(s);
        if(!isUserExist(s2))
        {
            return false;
        } else
        {
            return s1.equals(getPassword(s2));
        }
    }

    public void setUser(String s, String s1)
        throws UserDirectoryException
    {
        if(s == null || s1 == null)
        {
            throw new UserDirectoryException();
        }
        try
        {
            p.put(fixId(s), s1);
            String s2 = getClass().getClassLoader().getResource(UserDirectoryFile).getFile();
            p.store(new FileOutputStream(s2), UserDirectoryHeader);
        }
        catch(IOException _ex)
        {
            throw new UserDirectoryException();
        }
    }

}

2 Respostas

A

No struts-config.xml, você definiu como ‘success’, e na tua action definiu como ‘sucess’.

ricardospinoza

Obrigado pela resposta.

Eu entedi o que vc disse, mas como sou novato no struts não sei exatamente o que modificar pra funcionar…

Criado 3 de outubro de 2008
Ultima resposta 5 de out. de 2008
Respostas 2
Participantes 2