Cannot find bean editUserBean in any scope

2 respostas
S

bom dia amigos, nao estou conseguindo resolver o problema do tutorial em que se fala sobre struts+framework em que se encontra no nosso forum, ele possui muitos bugs, mas eu fui consertando ate chegar onde cheguei, e agora so estou com este erro que nao sei mais o que faco, ele me envia o retorno do JSP com a mensagem:

JSP -----

HTTP Status 500 -

type Exception report

message

description The server encountered an internal error () that prevented it from fulfilling this request.

exception

javax.servlet.ServletException: Cannot find bean editUserBean in any scope

org.apache.jasper.runtime.PageContextImpl.doHandlePageException(PageContextImpl.java:848)

org.apache.jasper.runtime.PageContextImpl.handlePageException(PageContextImpl.java:781)

org.apache.jsp.EditUser_jsp._jspService(EditUser_jsp.java:355)

org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:97)

javax.servlet.http.HttpServlet.service(HttpServlet.java:802)

org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:322)

org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:291)

org.apache.jasper.servlet.JspServlet.service(JspServlet.java:241)

javax.servlet.http.HttpServlet.service(HttpServlet.java:802)

org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:362)

root cause

javax.servlet.jsp.JspException: Cannot find bean editUserBean in any scope

org.apache.struts.taglib.TagUtils.lookup(TagUtils.java:934)

org.apache.struts.taglib.html.BaseFieldTag.prepareValue(BaseFieldTag.java:121)

org.apache.struts.taglib.html.BaseFieldTag.renderInputElement(BaseFieldTag.java:102)

org.apache.struts.taglib.html.BaseFieldTag.doStartTag(BaseFieldTag.java:81)

org.apache.struts.taglib.html.HiddenTag.doStartTag(HiddenTag.java:75)

org.apache.jsp.EditUser_jsp._jspx_meth_html_hidden_0(EditUser_jsp.java:404)

org.apache.jsp.EditUser_jsp._jspService(EditUser_jsp.java:145)

org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:97)

javax.servlet.http.HttpServlet.service(HttpServlet.java:802)

org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:322)

org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:291)

org.apache.jasper.servlet.JspServlet.service(JspServlet.java:241)

javax.servlet.http.HttpServlet.service(HttpServlet.java:802)

org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:362)

note The full stack trace of the root cause is available in the Apache Tomcat/5.5.9 logs.
Apache Tomcat/5.5.9

FIM JSP -----

por favor me ajudem, se quiserem posto o projeto para que alguem analise que erro é este.

Grato
Kleber Gracia
Software Development

2 Respostas

B

Cara, parece que o JSP está tentando usar o bean editUserBean mas ele não está achando nem na sessão, nem no request.
Vc está colocando esse bean no momento q vc chama a aplicação?
Posta o codigo do JSP que está dando erro…

Abraços

S

Olá amigo, desculpe pela demora, o meu jsp esta assim:

<%@ taglib uri="/WEB-INF/struts-logic.tld" prefix="logic" %>
<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean"%>
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html"%>
<html:html locale="true">
    <head>
        <title><bean:message key="editUser.title"/></title>
    </head>
    <body>
        <font face="Comic Sans MS" size="3">
            <center>
                <h3><font color="blue"><bean:message key="editUser.title"/></font></h3>
                <html:form action="/saveEditUser.do"  method="post" focus="login">
                    <html:hidden property="idUsuario" name="editUserBean"/>
                    <table width="80%" border="0">
                        <tr>
                        <td width="30%"></td>
                        <td width="70%">
                            <%-- exibe os erros de validação --%>
                            <logic:messagesPresent>
                                <ul>
                                    <html:messages id="error">
                                        <li><bean:write name="error"/></li>
                                    </html:messages>
                                </ul>
                            </logic:messagesPresent>
                        </td>
                        <tr>
                        <tr>
                            <td align="right"><bean:message key="prompt.idUsuario"/>: </td>
                            <td align="left"><b><bean:write property="idUsuario" name="editUserBean"/></b></td>
                        </tr>

                        <tr>
                            <td align="right"><bean:message key="prompt.login"/>: </td>
                            <td align="left"><html:text property="login" name="editUserBean" size="20"/></td>
                        </tr>
                        <tr>
                            <td align="right"><bean:message key="prompt.nome"/></td>
                            <td align="left"><html:text property="nome" name="editUserBean" size="60"/></td>
                        </tr>

                        <tr>
                            <td align="right"><bean:message key="prompt.senhaAntiga"/>: </td>
                            <td align="left"><html:password property="senhaAntiga" size="16" maxlength="20" redisplay="false" value="zzzzz"/></td>
                        </tr>
                        <tr>
                            <td align="right"><bean:message key="prompt.novaSenha"/>: </td>
                            <td align="left"><html:password property="novaSenha" size="16" maxlength="20" redisplay="false" value="zzzzz"/></td>
                        </tr>
                        <tr>
                            <td align="right"><bean:message key="prompt.confirmacaoNovaSenha"/>: </td>
                            <td align="left"><html:password property="confirmacaoNovaSenha" size="16" maxlength="20" redisplay="false" value="zzzzz"/></td>
                        </tr>
                        <tr>
                            <td align="right"><bean:message key="prompt.faixaIdade"/>: </td>
                            <td align="left">
                                <html:select property="faixaIdade" name="editUserBean">
                                    <html:option value="1"><bean:message key="prompt.ate20"/></html:option>
                                    <html:option value="2"><bean:message key="prompt.de21a30"/></html:option>
                                    <html:option value="3"><bean:message key="prompt.de31a40"/></html:option>
                                    <html:option value="4"><bean:message key="prompt.de41a50"/></html:option>
                                    <html:option value="5"><bean:message key="prompt.de51a60"/></html:option>
                                    <html:option value="6"><bean:message key="prompt.acima60"/></html:option>
                                </html:select>
                            </td>
                        </tr>
                        <tr>
                            <td align="right"><bean:message key="prompt.sexo"/>: </td>
                            <td align="left">
                                <html:radio property="sexo" value="M" name="editUserBean"><bean:message key="prompt.Masculino"/></html:radio>
                                <html:radio property="sexo" value="F" name="editUserBean"><bean:message key="prompt.Feminino"/></html:radio>
                            </td>
                        </tr>
                        <tr>
                            <td align="right"><bean:message key="prompt.ativo"/>: </td>
                            <td align="left"><html:checkbox property="ativo" name="editUserBean" titleKey="prompt.ativo"/></td>
                        </tr>
                        <tr>
                            <td colspan="2" align="center">
                                <html:submit><bean:message key="button.send"/></html:submit> 
                                <html:reset><bean:message key="button.reset"/></html:reset>
                            </td>
                        </tr>
                    </table>
                </html:form>
                <br/>
                <html:link page="/listUsers.do">voltar</html:link>
            </center>
        </font>
    </body>
</html:html>

e minha classe action esta assim:

package strutsdemo.action;

import java.util.Iterator;
import java.util.LinkedList;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import strutsdemo.bean.AdminUsers;
import strutsdemo.bean.UserData;

public class EditUserAction extends Action {
    
    public ActionForward execute(
            ActionMapping mapping,
            ActionForm form,
            HttpServletRequest request,
            HttpServletResponse response)
            throws Exception {
        ActionErrors errors = new ActionErrors();
        try {
            HttpSession session = request.getSession();
            AdminUsers adminUsers = new AdminUsers();
            String idUsuario = request.getParameter("idUsuario");
            session.removeAttribute("editUserBean");
            LinkedList userList = (LinkedList)session.getAttribute("userListBean");
            Iterator iter = userList.iterator();
            while (iter.hasNext()) {
                UserData user = (UserData)iter.next();
                if (user.getIdUsuario() == Integer.parseInt(idUsuario)) {
                    session.setAttribute("editUserBean", user);
                    break;
                }
            }
            UserData user = (UserData)session.getAttribute("editUserBean");
            if (user == null) {
                errors.add(
                        ActionErrors.GLOBAL_ERROR,
                        new ActionError("error.user.notFound"));
            }
        } catch (Exception e) {
            errors.add(
                    ActionErrors.GLOBAL_ERROR,
                    new ActionError("error.get.user"));
            getServlet().log("Erro carregando o Usuário", e);
        }
        
        
        if (!errors.isEmpty()) {
            saveErrors(request, errors);
            return (mapping.findForward("failure"));
        } else {
            return (mapping.findForward("success"));
        }
    }
}

e meu struts-config.xml esta assim:

<?xml version="1.0" encoding="ISO-8859-1" ?>

<!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>

    <!-- ========== Data Source Configuration =============================== -->
    <data-sources>
        <!--
        <data-source key="org.apache.struts.action.DATA_SOURCE">
        <set-property property="autoCommit" value="false"/>
        <set-property property="description" value="Struts DataSource"/>
        <set-property property="driverClass" value="com.mysql.jdbc.Driver"/>
        <set-property property="url" value="java:comp/env/jdbc/strutsdemo"/>
        <set-property property="maxCount" value="4"/>
        <set-property property="minCount" value="2"/>
        <set-property property="user" value="root"/>
        <set-property property="password" value="solo23"/>
        </data-source>
        -->
    </data-sources>


    <!-- ========== Form Bean Definitions ================================== -->
    <form-beans>
        <form-bean dynamic="false" name="saveEditUserForm" type="strutsdemo.form.SaveEditUserForm" />
        <form-bean dynamic="false" name="editUserBean" type="strutsdemo.form.editUserBean" />
        <form-bean dynamic="true" name="editUserBean" type="strutsdemo.form.editUserBean" />

        <form-bean dynamic="true" name="saveInsertUserForm" type="org.apache.struts.validator.DynaValidatorForm">
            <form-property name="idUsuario" type="java.lang.String" />
            <form-property name="login" type="java.lang.String" />
            <form-property name="nome" type="java.lang.String" />
            <form-property name="faixaIdade" type="java.lang.String" />
            <form-property name="sexo" type="java.lang.String" />
            <form-property name="ativo" type="java.lang.String" />
            <form-property name="senha" type="java.lang.String" />
            <form-property name="confirmacaoSenha" type="java.lang.String" />
        </form-bean>
    </form-beans>

    <!-- ================================= Global Exception Definitions -->
    <global-exceptions>
        <!-- sample exception handler
        <exception key="expired.password" type="app.ExpiredPasswordException" path="/changePassword.jsp"/>
        end sample -->
    </global-exceptions>
	
    <!-- =================================== Global Forward Definitions -->
    <global-forwards>
        <forward 
        name="welcome" 
        path="/Welcome.do"/>
        <forward 
        name="failure" 
        path="/error.jsp"
        redirect="true" 
        contextRelative="false" />
        <forward 
        name="success" 
        path="/ListUsers.jsp"
        redirect="true" 
        contextRelative="false" />
        
    </global-forwards>
    
    <!-- =================================== Action Mapping Definitions -->
    <action-mappings>

        <action 
        path="/Welcome"
        type="org.apache.struts.actions.ForwardAction"
        parameter="/pages/Welcome.jsp"/>

        <action
            path="/listUsers"
            scope="session"
            type="strutsdemo.action.ListUsersAction"
            unknown="false"
            validate="false">
            <forward
            name="success"
            path="/ListUsers.jsp"
            redirect="false"
            contextRelative="false" />
            <forward
            name="failure"
            path="/error.jsp"
            redirect="false"
            contextRelative="false" />
        </action>
        <action
            path="/editUser"
            scope="session"
            type="strutsdemo.action.EditUserAction"
            unknown="false"
            validate="false">
            <forward
            name="success"
            path="/pages/EditUser.jsp"
            redirect="false"
            contextRelative="false" />
        </action>
        <action
            attribute="saveEditUserForm"
            input="/pages/EditUser.jsp"
            name="saveEditUserForm"
            path="/saveEditUser"
            scope="session"
            type="strutsdemo.action.SaveEditUserAction"
            unknown="false"
            validate="true">
            <forward
            name="success"
            path="/pages/ListUsers.jsp"
            redirect="false"
            contextRelative="false" />
        </action>
        <action
            path="/insertUser"
            scope="session"
            type="strutsdemo.action.InsertUserAction"
            unknown="false"
            validate="false">
            <forward
            name="success"
            path="/pages/insertUser.jsp"
            redirect="false"
            contextRelative="false" />
        </action>
        <action
            attribute="saveInsertUserForm"
            input="/pages/insertUser.jsp"
            name="saveInsertUserForm"
            path="/saveInsertUser"
            scope="session"
            type="strutsdemo.action.SaveInsertUserAction"
            unknown="false"
            validate="true">
            <forward
            name="success"
            path="/pages/ListUsers.jsp"
            redirect="false"
            contextRelative="false" />
            <forward
            name="error"
            path="/pages/insertUser.jsp"
            redirect="false"
            contextRelative="false" />
        </action>
        <action
            path="/deleteUser"
            scope="session"
            type="strutsdemo.action.DeleteUserAction"
            unknown="false"
            validate="false">
            <forward
            name="success"
            path="/pages/ListUsers.jsp"
            redirect="false"
            contextRelative="false" />
        </action>
		
    </action-mappings>
    
    <!-- ===================================== Controller Configuration -->
    <controller
    processorClass="org.apache.struts.tiles.TilesRequestProcessor"/>
    
    <!-- ==================== ============ Message Resources Definitions -->
    <message-resources parameter="com.myapp.struts.ApplicationResource" null="true" /> 
    <!-- ======================================= Plug Ins Configuration -->
    <!-- comment following if struts1.0.x -->
    <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" />
        <set-property property="definitions-parser-validate" value="true" />
    </plug-in>
    
    <!-- end comment if struts1.0.x -->
    <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>

Nao sei se este erro é alguma configuração do DataSource, onde tbm gera no meu log um erro de jdbc, mas tenho tudo cetado so que nao esta indo, minha classe que conecta e faz as transacoes estao assim:

package strutsdemo.bean;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedList;
import javax.naming.Context;

import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

public class AdminUsers {
    
    protected static DataSource dataSource;
    
    public AdminUsers() throws Exception {
        if (dataSource == null) {
            try {
                //InitialContext ic = new InitialContext();
                //dataSource = (DataSource) ic.lookup("java:comp/env/jdbc/StrutsDemoDS");
                Connection conn = null;
                InitialContext ic = new InitialContext();
                //para conexao com o tomcat use
                dataSource = (DataSource) ic.lookup("java:comp/env/jdbc/strutsdemo");
                
                //para conexao com o jboss use
                //dataSource = (DataSource) ic.lookup("java:jdbc/StrutsDemoDS");
                
                if (dataSource != null) {
                    conn = dataSource.getConnection();
                }
                
            } catch (NamingException ex) {
                System.out.println(ex.getMessage());
                throw ex;
            }
        }
    }
    
    protected Connection getConnection() throws SQLException {
        Connection conn = null;
        try {
            conn = dataSource.getConnection();
        } catch (SQLException e) {
            throw e;
        }
        return conn;
    }
    
    
    protected void closeConnection(
            Connection conn,
            PreparedStatement stmt,
            ResultSet rs) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
            }
        }
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException e) {
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
            }
        }
    }
    
    public LinkedList getUserList() throws SQLException {
        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;
        LinkedList users  = new LinkedList();
        try {
            conn = getConnection();
            stmt = conn.prepareStatement("select * from usuario");
            rs = stmt.executeQuery();
            while (rs.next()) {
                UserData user = new UserData();
                user.setIdUsuario(rs.getInt("id_usuario"));
                user.setNome(rs.getString("nome"));
                user.setLogin(rs.getString("login"));
                user.setSenha(rs.getString("senha"));
                user.setSexo(rs.getString("sexo"));
                user.setAtivo(rs.getBoolean("ativo"));
                user.setFaixaIdade(rs.getInt("faixa_idade"));
                users.add(user);
            }
        } catch (SQLException e) {
            throw e;
        } finally {
            closeConnection(conn, stmt, rs);
        }
        return users;
    }
    
    public void insertUser(UserData user) throws SQLException {
        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;
        try {
            conn = getConnection();
            stmt = conn.prepareStatement(
                    "insert into usuario \n" +
                    "(id_usuario, nome, login, senha, sexo, ativo, faixa_idade) \n" +
                    "values (?, ?, ?, ?, ?, ?, ?)");
            stmt.setInt(1, user.getIdUsuario());
            stmt.setString(2, user.getNome());
            stmt.setString(3, user.getLogin());
            stmt.setString(4, user.getSenha());
            stmt.setString(5, user.getSexo());
            stmt.setBoolean(6, user.getAtivo());
            stmt.setInt(7, user.getFaixaIdade());
            stmt.executeUpdate();
        } catch (SQLException e) {
            throw e;
        } finally {
            if (rs != null) {
                rs.close();
            }
            if (stmt != null) {
                stmt.close();
            }
        }
    }
    
    public void updateUser(UserData user) throws SQLException {
        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;
        try {
            conn = getConnection();
            stmt = conn.prepareStatement(
                    "update usuario set \n" +
                    "nome = ?, login = ?, senha = ?, sexo = ?, ativo = ?, faixa_idade = ? \n" +
                    "where id_usuario = ?");
            stmt.setString(1, user.getNome());
            stmt.setString(2, user.getLogin());
            stmt.setString(3, user.getSenha());
            stmt.setString(4, user.getSexo());
            short ativo = (short) (user.getAtivo()? 1: 0);
            stmt.setShort(5, ativo);
            stmt.setInt(6, user.getFaixaIdade());
            stmt.setInt(7, user.getIdUsuario());
            stmt.executeUpdate();
        } catch (SQLException e) {
            throw e;
        } finally {
            if (rs != null) {
                rs.close();
            }
            if (stmt != null) {
                stmt.close();
            }
        }
    }
    
    public void deleteUser(int idUsuario) throws SQLException {
        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;
        try {
            conn = getConnection();
            stmt = conn.prepareStatement(
                    "delete from usuario where id_usuario = ?");
            stmt.setInt(1, idUsuario);
            stmt.executeUpdate();
        } catch (SQLException e) {
            throw e;
        } finally {
            if (rs != null) {
                rs.close();
            }
            if (stmt != null) {
                stmt.close();
            }
        }
    }
}

E jsp retorna o erro de cima ainda e meu log retorna o erro abaixo:

erro das tags

SEVERE: Servlet.service() for servlet jsp threw exception
javax.servlet.jsp.JspException: Cannot find bean editUserBean in any scope
        at org.apache.struts.taglib.TagUtils.lookup(TagUtils.java:934)

ERRO DO DATASOURCE

javax.naming.NameNotFoundException: Name jdbc: is not bound in this Context
        at org.apache.naming.NamingContext.lookup(NamingContext.java:769)

se tiver como vc me ajudar eu lhe agradeco.

Criado 16 de novembro de 2006
Ultima resposta 20 de nov. de 2006
Respostas 2
Participantes 2