Erro ao conectar JSP

22 respostas
S

Ola amigos estou tentando acessar minha primeira aplicacao de um tutorial sobre Struts e Framework utilizando java e jsp, mas nao to conseguindo concluir, o JSP me gera um erro que nao conheco ainda:

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 create redirect URL: java.net.MalformedURLException: Cannot retrieve ActionForward named error

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

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

org.apache.jsp.ListUsers_jsp._jspService(ListUsers_jsp.java:219)

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 create redirect URL: java.net.MalformedURLException: Cannot retrieve ActionForward named error

org.apache.struts.taglib.logic.RedirectTag.generateRedirectURL(RedirectTag.java:309)

org.apache.struts.taglib.logic.RedirectTag.doEndTag(RedirectTag.java:268)

org.apache.jsp.ListUsers_jsp._jspx_meth_logic_redirect_0(ListUsers_jsp.java:266)

org.apache.jsp.ListUsers_jsp._jspx_meth_logic_notPresent_0(ListUsers_jsp.java:242)

org.apache.jsp.ListUsers_jsp._jspService(ListUsers_jsp.java:84)

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

nao sei nem por onde comecar, ja acertei alguns erros anteriores mas agora nao estou conseguindo passar.

Grato.
Kleber

22 Respostas

L

Olá Kleber.
O Struts não está encontrando um mapeamento para a URL informada no seu struts-config.
Poste aqui o seu struts-config.xml.

Abraço.

P

Certifique que os nomes no strutsconfig estão corretos e o que tem nessa linha MonitorFilter.java:362?

S

Olá amigos, ele esta meio grandinho é este abaixo:

struts-config.xml

<?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="jdbc:mysql://192.168.10.68/strutsdemo "/>
        <set-property property="maxCount" value="4"/>
        <set-property property="minCount" value="2"/>
        <set-property property="user" value="root"/>
        <set-property property="password" value=""/>
        </data-source>
        -->
    </data-sources>


    <!-- ========== Form Bean Definitions ================================== -->
    <form-beans>
        <form-bean dynamic="false" name="saveEditUserForm" type="strutsdemo.form.SaveEditUserForm" />
        <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" />
    </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="/pages/ListUsers.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>

E MINHA JSP ESTA ASSIM

<%@ taglib uri="/WEB-INF/struts-logic.tld" prefix="logic" %>
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>

<logic:notPresent name="userListBean" scope="session">
  <logic:redirect forward="error"/>
</logic:notPresent>

<html:html locale="true">
<head>
  <title><bean:message key="users.title"/></title>
</head>
<body>
    <center>
        <font face="Comic Sans MS" size="3">
        <blockquote>
            <center>
                <h3><font color="blue"><bean:message key="users.title"/></font></h3>
                <table width="80%" border="1">
                    <tr>
                        <th width="10%"><bean:message key="prompt.idUsuario"/></th>
                        <th width="50%"><bean:message key="prompt.nome"/></th>
                        <th width="20%"><bean:message key="prompt.login"/></th>
                        <th width="10%"><bean:message key="prompt.ativo"/></th>
                        <th width="10%"> </th>
                    </tr>
                    <%-- loop que percorre a Collection de usuarios --%>
                    <logic:iterate name="userListBean" id="user" >
                        <tr>
                            <td align="center">
                                <bean:write name="user" property="idUsuario"/>
                            </td>
                            <td>
                                <html:link page="/editUser.do" paramId="idUsuario"
                                    paramName="user" paramProperty="idUsuario">
                                    <bean:write name="user" property="nome"/>
                                </html:link>
                            </td>
                            <td><bean:write name="user" property="login"/></td>
                            <td><bean:write name="user" property="descricaoStatus"/></td>
                            <td>
                                <html:link page="/deleteUser.do" paramId="idUsuario"
                                    paramName="user" paramProperty="idUsuario">
                                    <bean:message key="prompt.excluir"/>
                                </html:link>
                            </td>
                        </tr>
                    </logic:iterate>
                </table>
                <br/>
                <html:link page="/insertUser.do">incluir</html:link>
                <html:link page="/Welcome.do">Página Inicial</html:link>
            </center>
        </lockquote>
    </body>
</html:html>

nao sei mais o que faco, help

L

Kleber, o Struts tentou fazer um redirecionamento para uma página mapeada no seu struts-config.xml, e não encontrou.
Isso pode ter ocorrido por estar com o nome errado, por exemplo.
No seu xml existem vários actions. Diga-me em qual página ocorreu o erro.

Abraço.

S

Olá amigo, ele gera o erro neste link:

http://192.168.10.68:8084/strutsdemo/ListUsers.jsp

em que é a pagina ListUsers.jsp

nao estou conseguindo mesmo, se quiser lhe envio o projeto, ele esta em netbeans 5.0

S

A mais uma coisa, meu codigo em java esta assim em que é minha classe

package strutsdemo.action;

import java.sql.SQLException;
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;

public class ListUsersAction extends Action {

	public ActionForward execute(ActionMapping mapping,
				 ActionForm form,
				 HttpServletRequest request,
				 HttpServletResponse response)
	throws Exception {
		
		LinkedList users = null;
		ActionErrors errors = new ActionErrors();
		try {
			AdminUsers adminUsers = new AdminUsers();
			users = adminUsers.getUserList();
			HttpSession session = request.getSession();
                        
			session.setAttribute("userListBean", users);
			
		}
		catch (SQLException e) {
			errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("error.user.list"));
			getServlet().log("Erro carregando a lista de usuários", e);
		}
		if (!errors.isEmpty()) {
			saveErrors(request, errors);
			return (mapping.findForward("failure"));
		}
		else {
			return (mapping.findForward("success"));	
		}
	}
}

nao sei se ajuda, mas eu ja olhei de cabo a rabo e nao consegui achar nada. Grato pela atencao.

Kleber Gracia

S

Help ae amigos.

L

Olá Kleber !
Seguinte, acho que identifiquei o ponto.
Veja que na sua classe, você pode ter um resultado "sucess" ou um "failure", para a action "listUser".
Porém, no seu struts-config.xml, você só diz qual o redirecionamento em caso de "sucess". Como a sua classe está retornando um "failure", o struts não encontra qual página ele deve chamar.
Resumindo, para corrigir, seu código que está assim no struts-config.xml :

action
             path="/listUsers"
             scope="session"
             type="strutsdemo.action.ListUsersAction"
             unknown="false"
             validate="false"&gt
             &lt;forward
             name="success"
             path="/pages/ListUsers.jsp"
             redirect="false"
             contextRelative="false" /&gt;
         &lt;/action&gt;

Você deve também colocar qual a página a ser chamada em caso de "failure", assim :

action
             path="/listUsers"
             scope="session"
             type="strutsdemo.action.ListUsersAction"
             unknown="false"
             validate="false"&gt
             &lt;forward
             name="success"
             path="/pages/ListUsers.jsp"
             name="failure"
             path="/pages/ListUsers.jsp" //--&gt; aqui coloque a página de falha
             redirect="false"
             contextRelative="false" /&gt
         &lt;/action&gt;

Teste e me fale !

Abraço.

S

Olá amigo, eu alterei so que dae nao sei a que cargas d´aguas esta dando este erro, acho que deve de ser algum BUG, nao este bug nao é referente a edicao que fiz nao, nem sei o que é, procurei na net e nao achei

ERRO

library-inclusion-in-manifest:
compile:
compile-jsps:
D:\pacote\java\Struts\strutsdemo\nbproject\build-impl.xml:375: java.lang.RuntimeException: data starting at 0 is in unknown format
BUILD FAILED (total time: 0 seconds)

O que vc acha que é???

L

Hum… nunca vi este erro.
Mas quando ele começou a ocorrer ?
Você está rodando pelo eclipse ?
Apague a pasta no diretório do tomcat, pare o tomcat, copie a pasta novamente e reinicie o tomcat novamente.

S

Boa tarde amigo, estou usando o NetBeans, mas ele comecou do nada, nao mexi em nada mais, acho que deve ser algun especie de bug, vou editar e reiniciar e ja posto para vc denovo. so uns instantes.

S

Olá amigo, editei e o erro ainda persiste, mas tive que fazer assim como o modelo abaixo pelo fato do XML nao permitor do jeito que vc editou, tive que por mais um <forward, este erro é muito chato, ele nao muda nunca, nao sei mais o que faço.

struts-config.xml

[list]

<?xml version="1.0" encoding="ISO-8859-1" ?>
<!-- ========== 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="jdbc:mysql://192.168.10.68/strutsdemo"/>
    <set-property property="maxCount" value="4"/>
    <set-property property="minCount" value="2"/>
    <set-property property="user" value="root"/>
    <set-property property="password" value=""/>
    </data-source>
    -->
</data-sources>


<!-- ========== Form Bean Definitions ================================== -->
<form-beans>
    <form-bean dynamic="false" name="saveEditUserForm" type="strutsdemo.form.SaveEditUserForm" />
    <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" />
</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="/pages/ListUsers.jsp"
        redirect="false"
        contextRelative="false" />
        <forward
        name="failure"
        path="/pages/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>

[/list]

e meu JSP quando me retorna o erro faz:

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 create redirect URL: java.net.MalformedURLException: Cannot retrieve ActionForward named error

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

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

org.apache.jsp.ListUsers_jsp._jspService(ListUsers_jsp.java:219)

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 create redirect URL: java.net.MalformedURLException: Cannot retrieve ActionForward named error

org.apache.struts.taglib.logic.RedirectTag.generateRedirectURL(RedirectTag.java:309)

org.apache.struts.taglib.logic.RedirectTag.doEndTag(RedirectTag.java:268)

org.apache.jsp.ListUsers_jsp._jspx_meth_logic_redirect_0(ListUsers_jsp.java:266)

org.apache.jsp.ListUsers_jsp._jspx_meth_logic_notPresent_0(ListUsers_jsp.java:242)

org.apache.jsp.ListUsers_jsp._jspService(ListUsers_jsp.java:84)

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

e o meu arquivo de log ele gera este erro:

16/11/2006 08:04:31 org.apache.catalina.core.ApplicationContext log
SEVERE: action: Erro carregando a lista de usuários
org.apache.tomcat.dbcp.dbcp.SQLNestedException: Cannot create JDBC driver of class ‘’ for connect URL ‘null’
at org.apache.tomcat.dbcp.dbcp.BasicDataSource.createDataSource(BasicDataSource.java:780)

L

Retire este bloco aqui da sua JSP :

&lt;logic:notPresent name="userListBean" scope="session"&gt;
   &lt;logic:redirect forward="error"/&gt;
 &lt;/logic:notPresent&gt;

Faça o teste e vê se roda.

Abraço.

S

Ola amigo, o erro ficou diferente:

veja:
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 userListBean in any scope

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

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

org.apache.jsp.ListUsers_jsp._jspService(ListUsers_jsp.java:210)

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 userListBean in any scope

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

org.apache.struts.taglib.logic.IterateTag.doStartTag(IterateTag.java:232)

org.apache.jsp.ListUsers_jsp._jspService(ListUsers_jsp.java:132)

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

parece que ele nao esta achando o indice do Bean né, mas como ve o codigo é este ae. ? Juro que nao entendi agora.

L

Kleber, blz. Agora ele não está encontrando o “userListBean” na sua session.
Este erro já estava acontecendo. Aquele bloco que tiramos, tratava justamente isso.
Então o problema de verdade é que ele não está encontrando um “userListBean” na sua sessão.
Verifique quem está chamando esse seu JSP tem que fazer um session.setAtributte(“userListBean”,beanXXX), ou seja, adicionar o seu “userListBean” na sessão antes de chamar sua JSP.
Compreendeu ??

Abraço.

S

Ola amigo, na minha classe que tenho o session.setAttribute(“userListBean”, users); esta assim, so que o nome dela esta ListUserAction.java, veja como é a estrutura dela:

package strutsdemo.action;

import java.sql.SQLException;
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;

public class ListUsersAction extends Action {

	public ActionForward execute(ActionMapping mapping,
				 ActionForm form,
				 HttpServletRequest request,
				 HttpServletResponse response)
	throws Exception {
		
		LinkedList users = null;
		ActionErrors errors = new ActionErrors();
		try {
			AdminUsers adminUsers = new AdminUsers();
			users = adminUsers.getUserList();
			HttpSession session = request.getSession();
                        
			session.setAttribute("userListBean", users);
			
		}
		catch (SQLException e) {
			errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("error.user.list"));
			getServlet().log("Erro carregando a lista de usuários", e);
		}
		if (!errors.isEmpty()) {
			saveErrors(request, errors);
			return (mapping.findForward("failure"));
		}
		else {
			return (mapping.findForward("success"));	
		}
	}
}

aonde eu tenho que por o session.setAttribute(“userListBean”, users);, eu reparei que tem um nome diferente do seu que é ,users, na minha classe, na realidade eu nao compreendi muito nao. Se tiver como vc explicar detalhadamente eu lhe agradeco.

S

a mais uma coisa, eu adicionei isto no JSP no lugar do outro logic e passou, so que nao sei ao certo o que vai em USER:

veja como ficou:

<logic:iterate id="users" name="userListBean" type="java.lang.String">
    <bean:message key="users.title" />
</logic:iterate>

este codigo é do form ListUsers.jsp, so estou nesta dúvida, o que é que vai no id="" eu acrescentei user que é o segundo parametro da classe na parte em que esta assim: session.setAttribute(“userListBean”, users); coloquei este user final ae. O que vc acha?

L

Kleber, não estou encontrando mais problemas. Retire este último bloco que colocou onde tiramos o bloco.
Em seguida, faça o deploy completo de novo. Apague o diretório do Tomcat. Dê um build no projeto, reinicie o Tomcat e tente de novo.

Não estou encontrando o que pode ser o erro.
Tá tudo certo agora.

Abraço.

S

Olá amigo, bom dia, agora so tenho mais este problema que é referente ao banco de dados, veja o codigo, acho que é por isso que o erro ainda peresiste.

codigo gerado pelo meu LOG

16/11/2006 08:04:31 org.apache.catalina.core.ApplicationContext log
SEVERE: action: Erro carregando a lista de usuários
org.apache.tomcat.dbcp.dbcp.SQLNestedException: Cannot create JDBC driver of class '' for connect URL 'null'
        at org.apache.tomcat.dbcp.dbcp.BasicDataSource.createDataSource(BasicDataSource.java:780)

agora acho que este é o ultimo erro, so que nao estou conseguindo arrumar.

L

Kleber, deve haver algum problema na sua conexão com o banco.
Me passe a sua classe de conexão.
O outro erro então agora está ok ?

Abraço.

S

Olá amigo desculpe-me pela demora, é que estavamos sem internet, segue minha conexao que nao esta dando certo:

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.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();
                DataSource dataSource = (DataSource) ic.lookup("java:comp/env/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();
            }
        }
    }
}

ai estou tentando implementar uma conexao direta, veja se esta correta ela desta dando erro em alguns trechos mas acho que ir por este tipo de conexao é bem melhor.:

package strutsdemo.bean;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.DriverManager;
import java.sql.ResultSetMetaData;

import java.util.LinkedList;

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



public class AdminUsers {
    
    static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
    static final String DATABASE_URL = "jdbc:mysql://192.168.10.68";
    
    protected static DataSource dataSource;
    
    public AdminUsers() throws Exception {
        
        Connection conn = null;
        Statement stm = null;
        
        if (dataSource == null) {
            
            Class.forName( JDBC_DRIVER );
            //estabelece um conexao com o banco de dados
            conn = DriverManager.getConnection( DATABASE_URL, "root", "solo23");
            
            //cria Statement para consultar
            
            
            
            
            
            
/*
                InitialContext ic = new InitialContext();
                DataSource dataSource = (DataSource) ic.lookup("java:comp/env/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) {
            }
        }
    }
    */
            try {
                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;
                }catch(SQLException e){
                    
                }
                    throw e;
                }
            }
        }
        
        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();
                }
            }
            
        }

por favor se tiver como vc implementala pra mim eu dar as dicas eu lhe agradeco.

L

Kleber, a conexão usando DataSources do Java deve funcionar perfeitamente, deve haver algo errado na configuração do DataSource, ou o Driver do banco.
Faz o seguinte, cria outro tópico no fórum, com o tema “Erro com DataSource”, alguma coisa assim, e coloca a mensagem de erro que você está recebendo.
Não precisa implementar a conexão manual.

Abraço.

Criado 16 de novembro de 2006
Ultima resposta 17 de nov. de 2006
Respostas 22
Participantes 3