Struts In Action

Olá pessoal,

Blz?

Adquiri o livro Struts In Action recentemente depois de muita pesquisa no GUJ e em outros sites e fóruns, o livro realmente é muito bom. Porém ele não detalha muito os possíveis problemas na hora dos exercícios, o que acontece é o seguinte.
Crieu uma aplicação no Struts (AQUELA DO 1º EXERCÍCIO) que recebe um usuário e uma senha, quando faço o teste colocando o usuário, senha e confirmação da senha sou direcionado para a tela de falha e NUNCA para a tela de sucesso. No livro não menciona a criação de um banco de dados para consultar o usuário e a senha, será este o problema???

Se alguém já tiver experiência (ou não) com este livro e puder postar alguma dica, a comunidade Java agradece e eu também!

Detalhe uso o Eclipse e WinXP.

Abaixo seguem as configurações do Struts:

package app;

import org.apache.struts.action.*;

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;
};

}

package app;

import org.apache.struts.action.;
import javax.servlet.http.
;
import java.io.*;

public class RegisterAction extends Action {
public ActionForward perform(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("success");
		} catch (UserDirectoryException e) {
			return mapping.findForward("failure");
		}
	}
	return mapping.findForward("failure");
}

}

<?xml version="1.0" encoding="ISO-8859-1" ?> SUCCESS Registration succeeded!

try another?

FAILURE Registration failed!

try again?

<%@ taglib uri="/WEB-INF/struts-html.tld" prefix=“form” %>
<form:form action=“register.do”>
UserName:<form:text property=“username”/>

enter password:<form:password property=“password1”/>

re-enter password:<form:password property=“password2”/>

<form:submit value=“Register”/>
</form:form>

O acesso é feito neste caminho: http://localhost:XPTO/strutsInAction/register.jsp

Pelo que vejo na ActionServlet o direcionamento está correto. De qualquer forma acredito que algo pode ser corrigido para direcionar para a página SUCCESS!!!

Vlw.

Jingo.

Colega é o Struts 1?

Eu li o livro (faz muito tempo) e lembro que no primeiro exercicio você começa pelo exemplo que vem com Struts, acho que é o projeto Blank que vem com o Struts.
No caso do login e senha é direto no código, acho que tem uma collection de usuários. Um dos logins é o autor.
A versão do Struts é 1.0, 1.1 até a 1.3. do Ted Husted.

Espero que isto te ajude.

É o Struts 1.0 que é o inicio do livro e depois vai para o 1.1.
A senha não é o nome do autor. Mas onde ele valida?
Complementando existem duas classes que não estão no livro, segue:

package app;

import java.io.IOException;
import java.io.InputStream;
import java.io.FileOutputStream;
import java.util.Enumeration;
import java.util.Properties;
import java.net.URL;

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 {

	java.io.InputStream i = null;
	p = null;
	i = this.getClass().getClassLoader().getResourceAsStream(
			UserDirectoryFile);

	if (null == i) {
		throw new UserDirectoryException();
	}

	else {

		try {
			p = new Properties();
			p.load(i);
			i.close();
		}

		catch (java.io.IOException e) {
			p = null;
			System.out.println(e.getMessage());
			throw new UserDirectoryException();
		}

		finally {
			i = null;
		}

	} // end else

} // end UserDirectory

/** 
  * 
  */
public static UserDirectory getInstance() throws UserDirectoryException {

	if (null == userDirectory) {

		userDirectory = new UserDirectory();

	}

	return userDirectory;

}

/**
 * Transform id so that it will match any conventions used by user
 * directory. The default implementation forces the id to uppercase. Does
 * <b>not</b> expect the userId to be null and will throw a NPE if it is.
 * 
 * @exception Throws
 *                Null Pointer Exception if userId is null.
 */
public String fixId(String userId) {
	return userId.toUpperCase();
}

/** 
  * 
  */
public boolean isValidPassword(String userId, String password) {

	// no null passwords
	if (null == password)
		return false;

	// conform userId to uppercase
	String _userId = fixId(userId);

	// no passwords for non-users
	if (!isUserExist(_userId))
		return false;

	// does password match user's password
	return (password.equals(getPassword(_userId)));

}

/** 
  * 
  */
public boolean isUserExist(String userId) {

	// no null users
	if (null == userId)
		return false;

	// if not null, it's a user
	return !(null == p.getProperty(userId));

}

/** 
  * 
  */
public String getPassword(String userId) {
	return p.getProperty(userId);
}

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

/** 
  * 
  */
public void setUser(String userId, String password)
		throws UserDirectoryException {

	// no nulls
	if ((null == userId) || (null == password)) {
		throw new UserDirectoryException();
	}

	try {

		// conform userId to uppercase when stored
		p.put(fixId(userId), password);
		String o = this.getClass().getClassLoader().getResource(
				UserDirectoryFile).getFile();
		p.store(new FileOutputStream(o), UserDirectoryHeader);

	}

	catch (IOException e) {
		throw new UserDirectoryException();

	}
}

} // end UserDirectory

/*

  • $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 © 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.
    1. 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.
    1. 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.
    1. 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 apache@apache.org.
    1. 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
  • http://www.apache.org/.

*/

/**

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

public class UserDirectoryException extends Exception {

// ; Empty implementation

}

Já comparei com outro exercício da apostila do FJ21 que está funcionando. A única diferença é que no FJ21 ele valida com um banco de dados de usuários.

fica em um arquivo properties os usuários, o objeto UserDirectory lê o arquivo e carrega na memória.

usa a tag code no código

Tentei com o arquivo properties, sem sucesso.

http://www.roseindia.net/struts/struts-login-form.shtml

Boa noite,
Eu tenho dúvida sobre validação de struts que a validaçao parece sem preencher mensagem… estou utilizando action, validation.xml. Primeiramente, dar uma olhada meu site abaixo:

acessa: www.rafael-vasconcelos.com/contato.do

Erro está marcado como: é necessário nome.
é necessário e-mail.
é necessário assunto.
é necessário mensagem.

vc sabe motivo sobre erros?!

Espero sua ajuda!

que Deus te Abençõe ricamente e um abraços,
Rafael Vascomcelos