Problemas com Struts

2 respostas
J

Pessoal,

Estou tentando fazer uns testes aqui com Struts e Hibernate, ainda nem comecei a persistir meus dados, só com Struts simples está dando erro e não sei o que pode ser, se alguem puder me ajudar, o erro é esse:

javax.servlet.ServletException: java.lang.IllegalArgumentException: No origin bean specified

Meu Action está assim:
package catalogo.controle.actions;

import catalogo.controle.forms.CadastroUsuarioForm;
import catalogo.modelo.Usuario;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

public class CadastroUsuarioAction extends org.apache.struts.action.Action {
     
    /**
     * This is the 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.
     * @throws java.lang.Exception
     * @return
     */
    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        
        CadastroUsuarioForm cadastroUsuarioForm = (CadastroUsuarioForm) form;
        //cadastroUsuarioForm.getNome()
        Usuario usuario = new Usuario();
        BeanUtils.copyProperties(usuario, cadastroUsuarioForm);
        request.setAttribute("usuario", usuario);
        return (mapping.findForward("sucesso"));
    }
}
O ActionForm:
package catalogo.controle.forms;

import javax.servlet.http.HttpServletRequest;

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

public class CadastroUsuarioForm extends org.apache.struts.action.ActionForm {
    
    private String _login, _senha, _nome;
    private int _tipo;

    public CadastroUsuarioForm() {
        super();
    }

    public String getLogin() {
        return _login;
    }

    public void setLogin(String _login) {
        this._login = _login;
    }

    public String getSenha() {
        return _senha;
    }

    public void setSenha(String _senha) {
        this._senha = _senha;
    }

    public String getNome() {
        return _nome;
    }

    public void setNome(String nome) {
        _nome = nome;
    }

    public int getTipo() {
        return _tipo;
    }

    public void setTipo(int _tipo) {
        this._tipo = _tipo;
    }

    /**
     * This is the action called from the Struts framework.
     * @param mapping The ActionMapping used to select this instance.
     * @param request The HTTP Request we are processing.
     * @return
     */
    public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {
        ActionErrors errors = new ActionErrors();
        if (getLogin() == null || getLogin().length() < 1) {
            errors.add("login", new ActionMessage("error.login.required"));
            // TODO: add 'error.nome.required' key to your resources
        }

        if (getSenha() == null || getSenha().length() < 1) {
            errors.add("senha", new ActionMessage("error.senha.required"));
            // TODO: add 'error.nome.required' key to your resources
        }
        return errors;
    }
}
Meu 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="CadastroUsuarioForm" type="catalogo.controle.forms.CadastroUsuarioForm"/>
    </form-beans>
    
    <global-exceptions>
    
    </global-exceptions>

    <global-forwards>

    </global-forwards>

    <action-mappings>
        <action path="/cadastroUsuario"
                input="/"
                name="CadastroUsuarioAction"
                scope="session"
                type="catalogo.controle.actions.CadastroUsuarioAction">
            <forward name="sucesso" path="/ok.jsp"></forward>
        </action>
        <action path="/Welcome" forward="/welcomeStruts.jsp"/>
    </action-mappings>
    
    <controller processorClass="org.apache.struts.tiles.TilesRequestProcessor"/>

    <message-resources parameter="catalogo/struts/ApplicationResource"/>    
    
    <!-- ========================= Tiles plugin ===============================-->
    <!--
    This plugin initialize Tiles definition factory. This later can takes some
    parameters explained here after. The plugin first read parameters from
    web.xml, thenoverload them with parameters defined here. All parameters
    are optional.
    The plugin should be declared in each struts-config file.
    - definitions-config: (optional)
    Specify configuration file names. There can be several comma
    separated file names (default: ?? )
    - moduleAware: (optional - struts1.1)
    Specify if the Tiles definition factory is module aware. If true
    (default), there will be one factory for each Struts module.
    If false, there will be one common factory for all module. In this
    later case, it is still needed to declare one plugin per module.
    The factory will be initialized with parameters found in the first
    initialized plugin (generally the one associated with the default
    module).
    true : One factory per module. (default)
    false : one single shared factory for all modules
    - definitions-parser-validate: (optional)
    Specify if xml parser should validate the Tiles configuration file.
    true : validate. DTD should be specified in file header (default)
    false : no validation

    Paths found in Tiles definitions are relative to the main context.
    -->
    <plug-in className="org.apache.struts.tiles.TilesPlugin" >
        <set-property property="definitions-config" value="/WEB-INF/tiles-defs.xml" />      
        <set-property property="moduleAware" value="true" />
    </plug-in>
    
    <!-- ========================= Validator plugin ================================= -->
    <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>

Se eu comentar o codigo que esta no metodo execute do Action, funciona, mostra a pagina certa

2 Respostas

J

Pessoal,

Na minha classe CadastroUsuarioAction eu mudei o metodo execute, fiz o seguinte, só para testar:

public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        
        CadastroUsuarioForm cadastroUsuarioForm = (CadastroUsuarioForm) form;
        //cadastroUsuarioForm.getNome()
        Usuario usuario = new Usuario();
        usuario.setLogin(cadastroUsuarioForm.getLogin());
        usuario.setSenha(cadastroUsuarioForm.getLogin());
        usuario.setNome(cadastroUsuarioForm.getNome());
        usuario.setTipo(cadastroUsuarioForm.getTipo());

        //BeanUtils.copyProperties(usuario, cadastroUsuarioForm);
        request.setAttribute("usuario", usuario);
        return (mapping.findForward("sucesso"));
    }

O erro agora é esse:

javax.servlet.ServletException: java.lang.NullPointerException

Alguem pode me ajudar?

J

Pessoal,

Refiz algumas coisas aqui e parou de dar erros, o redirecionamento acontece, porém na pagina de exibição dos dados fica tudo em branco, parece que não esta atribuindo os parametros da classe usuario, ou da classe CadastroUsuarioForm, sei la. Se alguem puder me ajudar, como disse está tudo ok agora, sem erros, porém os dados vindo do formulario nao sao mostrados na pagina de destino, fica em branco.

index.jsp
<%@page contentType="text/html"%>
<%@page pageEncoding="UTF-8"%>

<%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean" %>
<%@ taglib uri="http://struts.apache.org/tags-html" prefix="html" %>
<%@ taglib uri="http://struts.apache.org/tags-logic" prefix="logic" %>

<html:html lang="true">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title><bean:message key="catalogo.titulo"/></title>
        <html:base/>
    </head>
    <body>
        <logic:notPresent name="org.apache.struts.action.MESSAGE" scope="application">
            <div  style="color: red">
                ERROR:  Application resources not loaded -- check servlet container
                logs for error messages.
            </div>
        </logic:notPresent>

        <p><bean:message key="catalogo.boasvindas"/></p>

        <form action="cadastroUsuario.do" method="post" name="cadastroUsuario">
            Login: <input type="text" name="login" /><br />
            Senha: <input type="text" name="senha" /><br />
            Nome: <input type="text" name="nome" /><br />
            Tipo: <input type="text" name="tipo" /><br />
            <html:submit><bean:message key="catalogo.submit.enviar"/></html:submit>
        </form>
    </body>
</html:html>
CadastroUsuarioAction
package catalogo.controle.actions;

import catalogo.controle.forms.CadastroUsuarioForm;
import catalogo.modelo.Usuario;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

public class CadastroUsuarioAction extends org.apache.struts.action.Action {
    
    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        CadastroUsuarioForm usuarioForm = new CadastroUsuarioForm();
        Usuario usuario = new Usuario();
        BeanUtils.copyProperties(usuario, usuarioForm);
        request.setAttribute("usuario", usuario);

        return mapping.findForward("sucesso");
    }
}
CadastroUsuarioForm
package catalogo.controle.forms;

public class CadastroUsuarioForm extends org.apache.struts.action.ActionForm {
    
    private String login, senha, nome;
    private int tipo;

    public CadastroUsuarioForm() {
        super();
    }

    public String getLogin() {
        return login;
    }

    public void setLogin(String login) {
        this.login = login;
    }

    public String getSenha() {
        return senha;
    }

    public void setSenha(String senha) {
        this.senha = senha;
    }

    public String getNome() {
        return nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }

    public int getTipo() {
        return tipo;
    }

    public void setTipo(int tipo) {
        this.tipo = tipo;
    }

}
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="CadastroUsuarioForm" type="catalogo.controle.forms.CadastroUsuarioForm"/>
    </form-beans>
    
    <global-exceptions>
    
    </global-exceptions>

    <global-forwards>
        
    </global-forwards>

    <action-mappings>
        <action input="/" name="CadastroUsuarioAction" path="/cadastroUsuario" scope="session" type="catalogo.controle.actions.CadastroUsuarioAction">
            <forward name="sucesso" path="/dadosUsuario.jsp"></forward>
        </action>
        <action path="/Welcome" forward="/welcomeStruts.jsp"/>
    </action-mappings>
    
    <controller processorClass="org.apache.struts.tiles.TilesRequestProcessor"/>

    <message-resources parameter="catalogo/struts/ApplicationResource"/>    
    
    <plug-in className="org.apache.struts.tiles.TilesPlugin" >
        <set-property property="definitions-config" value="/WEB-INF/tiles-defs.xml" />      
        <set-property property="moduleAware" value="true" />
    </plug-in>
    
    <!-- ========================= Validator plugin ================================= -->
    <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>
Criado 10 de fevereiro de 2010
Ultima resposta 10 de fev. de 2010
Respostas 2
Participantes 1