Array de Beans -> não roda na web ;-(

6 respostas
rfpsatin

Salve Pessoal...

Não estou conseguindo fazer rodar um array de beans, na verdade um vector.

Fiz um programinha simples, com um servlet controlador, 2 páginas jsp de visualização e
um bean onde armazeno dados nele p/ vosualização.

funciona da seguinte forma, acesso a url do meu servlet sem comandos adicionais e ele
me mostrara na tela todos os registros de uma tabela. Ao clicar neste registro eu faço
uma nova consulta no bd pegando todos os dados daquele registro e mostrando noutra jsp.

Bem, qdo tento rodar o servlet da o seguinte erro.

//---------------------------------------------------

HTTP Status 500 - 

--------------------------------------------------------------------------------

type Exception report

message 

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

exception 

org.apache.jasper.JasperException: Cannot create bean of class EmployeeBean
	at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:254)
	at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:295)
	at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:241)
	at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
	at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:684)
	at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:432)
	at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:356)
	at rfps.FetchEmployeeServlet.service(FetchEmployeeServlet.java:62)
	at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
	at org.apache.catalina.servlets.InvokerServlet.serveRequest(InvokerServlet.java:466)
	at org.apache.catalina.servlets.InvokerServlet.doGet(InvokerServlet.java:180)
	at javax.servlet.http.HttpServlet.service(HttpServlet.java:740)
	at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:247)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:193)
	at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:256)
	at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:643)
	at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480)
	at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995)
	at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
	at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:643)
	at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480)
	at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995)
	at org.apache.catalina.core.StandardContext.invoke(StandardContext.java:2416)
	at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:180)
	at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:643)
	at org.apache.catalina.valves.ErrorDispatcherValve.invoke(ErrorDispatcherValve.java:171)
	at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:641)
	at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:172)
	at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:641)
	at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480)
	at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995)
	at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:174)
	at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:643)
	at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480)
	at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995)
	at org.apache.coyote.tomcat4.CoyoteAdapter.service(CoyoteAdapter.java:223)
	at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:601)
	at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.processConnection(Http11Protocol.java:392)
	at org.apache.tomcat.util.net.TcpWorkerThread.runIt(PoolTcpEndpoint.java:565)
	at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:619)
	at java.lang.Thread.run(Thread.java:534)


root cause 

javax.servlet.ServletException: Cannot create bean of class EmployeeBean
	at org.apache.jsp.employee_jsp._jspService(employee_jsp.java:53)
	at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:137)
	at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
	at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:210)
	at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:295)
	at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:241)
	at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
	at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:684)
	at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:432)
	at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:356)
	at rfps.FetchEmployeeServlet.service(FetchEmployeeServlet.java:62)
	at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
	at org.apache.catalina.servlets.InvokerServlet.serveRequest(InvokerServlet.java:466)
	at org.apache.catalina.servlets.InvokerServlet.doGet(InvokerServlet.java:180)
	at javax.servlet.http.HttpServlet.service(HttpServlet.java:740)
	at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:247)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:193)
	at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:256)
	at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:643)
	at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480)
	at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995)
	at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
	at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:643)
	at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480)
	at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995)
	at org.apache.catalina.core.StandardContext.invoke(StandardContext.java:2416)
	at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:180)
	at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:643)
	at org.apache.catalina.valves.ErrorDispatcherValve.invoke(ErrorDispatcherValve.java:171)
	at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:641)
	at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:172)
	at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:641)
	at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480)
	at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995)
	at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:174)
	at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:643)
	at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480)
	at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995)
	at org.apache.coyote.tomcat4.CoyoteAdapter.service(CoyoteAdapter.java:223)
	at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:601)
	at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.processConnection(Http11Protocol.java:392)
	at org.apache.tomcat.util.net.TcpWorkerThread.runIt(PoolTcpEndpoint.java:565)
	at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:619)
	at java.lang.Thread.run(Thread.java:534)



--------------------------------------------------------------------------------

Apache Tomcat/4.1.27

//---------------------------------------------------

como podem ver, estou usando o tomcat 4.1.27 num winME.

fiz então um programinha simples para testar, pois pelo q percebo, ele não esta conseguindo criar os beans.

Bem, no programa deu tudo certo, ele roda e mostra no console os dados como era p/ ser. Bem, o fato é que não
estou conseguindo usar array com beans, ja tentei isso antes e deu o mesmo erro, na época desisti e parti p/
outra solução + agora é questão de honra rs...

Pessoal, se alguém puder dar uma olhada e me ajudar eu agradeço mesmo. muito obrigado desde já.

abaixo estão os fontes.
/---------------------------------- list.jsp
<%@ page import="java.util.*, rfps.EmployeeBean" %>
<jsp:useBean id="employee" class="EmployeeBean" />

<HTML>
<BODY>
<B>CURRENT EMPLOYEE</B>
<UL>
<%
  Vector v = (Vector)request.getAttribute("list");
  Iterator i = v.iterator();
  while (i.hasNext() ){
    employee = (EmployeeBean) i.next();
%>
<LI>
<a href="/servlet/FetchEmployeeServlet?cmd=get&id=
<jsp:getProperty name="employee" property="id" />" >
<jsp:getProperty name="employee" property="lastName" />
<jsp:getProperty name="employee" property="firstName" />
<% } %>

</BODY>
</HTML>
//-----------------------------------employee.jsp
<%@ page import="java.util.*, rfps.EmployeeBean" %>
<jsp:useBean id="employee" class="EmployeeBean" scope="request"/>

<HTML>

<head><title>employee record</title></head>
<body>
<table border="1" align="center">
<tr bgcolor="tan"><td colspan=2><font size=+3 face=arial><b>
<jsp:getProperty name="employee" property="lastName" />
<jsp:getProperty name="employee" property="firstName" />
</b></font></td></tr>

<tr><td align=left valign=top>
<img heigth="150"
src="<jsp:getProperty name="employee" property="image" />" ></td> 
<td align=left valign=top>
<table taborder=0>
<tr><td><b> full name: </b></td><td>
<jsp:getProperty name="employee" property="firstName" />
<jsp:getProperty name="employee" property="lastName" />
</td></tr>
<tr><td><b> departament: </b></td><td>
<jsp:getProperty name="employee" property="department" />
</td></tr>
<tr><td><b> e-mail: </b></td><td>
<jsp:getProperty name="employee" property="email" />
</td></tr>
</table>
</td>
</tr>
</table>
</body>
</HTML>
//--------------------------------- meu servlet

package rfps;

import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;

public class FetchEmployeeServlet extends HttpServlet{
	
    private final static String driver="sun.jdbc.odbc.JdbcOdbcDriver";
	private final static String url="jdbc:odbc:ponteOracle";
	private final static String user="scott";
	private final static String password="tiger";
	private final static String sql="select * from people_table where id=? ";
	private Connection connection = null;
	private PreparedStatement statement = null;
	private ServletContext context;
	
	public void init(ServletConfig config) throws ServletException{
		super.init(config);	
		
		context = config.getServletContext();
		try{
		  Class.forName(driver);
		  connection = DriverManager.getConnection(url,user,password);
		  statement=connection.prepareStatement(sql);
		}catch(ClassNotFoundException e){
			System.err.println("Unable to load database driver");			
			throw new ServletException("Unable to load database driver");
			
		}catch(SQLException e){
			System.err.println("Unable to connect to database");			
			throw new ServletException("Unable to connect to database");
		}
		
	}
	
	public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException{
	  String jsp;
	  String cmd = req.getParameter("cmd");	
	  String idString = req.getParameter("id");
	  int id;
	  try{
	  	id = Integer.parseInt(idString);
	  }catch(NumberFormatException e){
	  	id=0;
	  }
	  
	  if ("get".equals(cmd)){
	  	EmployeeBean bean = fetchEmployee(id);
	  	req.setAttribute("employee",bean);
	  	jsp="/employee.jsp";
	  }
	  else{
	  	Vector list = fetchAll();                                                                                
	  	req.setAttribute("list",list);
	  	jsp="/list.jsp";
	  }
	  RequestDispatcher dispatcher;
	  dispatcher = context.getRequestDispatcher(jsp);
	  dispatcher.forward(req,res);
	  
	}
	
	public EmployeeBean makeBean(ResultSet results)throws SQLException{
		EmployeeBean bean = new EmployeeBean(results.getInt("id"));
		bean.setFirstName(results.getString("fname"));
		bean.setLastName(results.getString("lname"));		
		bean.setEmail(results.getString("email"));
		bean.setDepartment(results.getString("department"));
		bean.setImage(results.getString("image"));
		return bean;
	}
	
	public EmployeeBean fetchEmployee(int id){
		try{
			ResultSet results;
			synchronized(statement){
				statement.clearParameters();
				statement.setInt(1,id);
				results = statement.executeQuery();				
			}
			EmployeeBean bean = null;
			if (results.next()){
				bean = makeBean(results);
			}
			if (results != null)
				results.close();
				
			return bean;
		}catch(SQLException se){
			return null;
		}
	}
	
	public Vector fetchAll(){
		try{
			Vector list = new Vector();
			ResultSet results;
			Statement st = connection.createStatement();
			results = st.executeQuery("select * from people_table");
			while(results.next())
			   list.add(makeBean(results));
			return list;
		}catch(SQLException se){
			return null;
		}
	}
	
	public void destroy(){
		try{
			if (connection != null)
			  connection.close();
		}catch(SQLException e){
			
		}
	}
}
//------------------------------------- meu bean
package rfps;

public class EmployeeBean{
     private int id;
     private String firstName;	
     private String lastName;
     private String image;
     private String email;
     private String department;
     
     public EmployeeBean(int id){
     	this.id=id;
     	this.firstName="";
     	this.lastName="";
     	this.image="";
     	this.email="";
     	this.department="";     	
     }
     
     public EmployeeBean(){
        this	(0);//procura outro construtor passando valor 0     	
     }
     
     public int getId(){
       return this.id;	
     }
     
	 public void setFirstName(String firstName){
       this.firstName=firstName;
     }     
     public String getFirstName(){
     	return this.firstName;
     }
     
	 public void setLastName(String LastName){
       this.lastName=lastName;
     }     
     public String getLastName(){
     	return this.lastName;
     }
          
     public void setImage(String image){
       this.image=image;
     }     
     public String getImage(){
     	return this.image;
     }
     
     public void setEmail(String email){
       this.email=email;
     }     
     public String getEmail(){
     	return this.email;
     }
     
     public void setDepartment(String department){
       this.department=department;
     }     
     public String getDepartment(){
     	return this.department;
     }

}
//----------------------------------------------- meu teste que rodou

package rfps;

import java.io.*;
import java.sql.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;


public class testaBean{
	
    private final static String driver="sun.jdbc.odbc.JdbcOdbcDriver";
	private final static String url="jdbc:odbc:ponteOracle";
	private final static String user="scott";
	private final static String password="tiger";
	private final static String sql="select * from people_table where id=? ";
	private Connection connection = null;
	private PreparedStatement statement = null;	
	
	public testaBean(){
	try{
		  Class.forName(driver);
		  connection = DriverManager.getConnection(url,user,password);
		  statement=connection.prepareStatement(sql);
		}catch(ClassNotFoundException e){
			System.err.println("Unable to load database driver");			
			//throw new ServletException("Unable to load database driver");
			
		}catch(SQLException e){
			System.err.println("Unable to connect to database");			
			//throw new ServletException("Unable to connect to database");
		}			
	}
	
   public EmployeeBean makeBean(ResultSet results)throws SQLException{
		EmployeeBean bean = new EmployeeBean(results.getInt("id"));
		bean.setFirstName(results.getString("fname"));
		bean.setLastName(results.getString("lname"));		
		bean.setEmail(results.getString("email"));
		bean.setDepartment(results.getString("department"));
		bean.setImage(results.getString("image"));
		return bean;
	}	
	
	public Vector fetchAll(){
		try{
			Vector list = new Vector();
			ResultSet results;
			Statement st = connection.createStatement();
			results = st.executeQuery("select * from people_table");
			while(results.next())
			   list.add(makeBean(results));
			return list;
		}catch(SQLException se){
			return null;
		}
	}	
	
  public static void main (String[] args)	{
   testaBean B = new testaBean();
   EmployeeBean employee = new EmployeeBean();
   Vector v = new Vector();
   v=B.fetchAll();
   Iterator i = v.iterator();
    while (i.hasNext() ){
      employee = (EmployeeBean) i.next();
      System.out.println(employee.getFirstName());
   } 
  }
}

6 Respostas

cancao

Onde vc está fazendo:

<jsp:useBean id="employee" class="EmployeeBean" />
Use:

<jsp:useBean id="employee" class="rfps.EmployeeBean" />
Ou seja, coloque o nome completo da classe. O import não resolve porque o bean não é instanciado apenas fazendo assim:

EmployeeBean employee = new EmployeeBean();

E sim:

rfps.EmployeeBean employee = null;
...
employee = (rfps.EmployeeBean)
java.beans.Beans.instantiate(this.getClass().getClassLoader(), "rfps.EmployeeBean");

Rola reflection… veja os .java no work do Tomcat para entender melhor como o parse é feito.

Até.

rfpsatin

Salve colega, vou testar a noite e qq coisa volto ao tópico.

abraço

Deus abençoe.

rfpsatin

salve pessoal,

Bem, um dos erros realmente era aquilo q o colega me ajudou, agora estou com outro problema.

O servlet esta pegando os dados corretamente e colocando no bean, vector de bean, perfeitamente,
porém qdo na página jsp tento listar os dados aparece tudo em branco. tipo, tenho
4 registro neste array, ele lista os 4 registros + vazio. não entendo.

eis o c’'odigo q gera tudo em branco

<HTML>
<BODY>

<%@ page import="java.util.*, rfps.EmployeeBean" %>
<jsp:useBean id="employee" class="rfps.EmployeeBean" />

<B>CURRENT EMPLOYEE</B>
<UL>
<%
  Vector v = (Vector)request.getAttribute("list");
  Iterator i = v.iterator();
  while (i.hasNext() ){
    employee = (rfps.EmployeeBean) i.next();
%>
<LI>
<a href="http://localhost:8080/ola2/servlet/rfps.FetchEmployeeServlet?cmd=get&id=
<jsp:getProperty name="employee" property="id" />" >
<jsp:getProperty name="employee" property="lastName" />
<jsp:getProperty name="employee" property="firstName" />
<% } %>


</BODY>
</HTML>

eis o q gera saída corretamente, contudo, “matei” o bean :wink:

<HTML>
<BODY>

<%@ page import="java.util.*, rfps.EmployeeBean" %>
<jsp:useBean id="employee" class="rfps.EmployeeBean" />

<B>CURRENT EMPLOYEE</B>
<UL>
<%
  Vector v = (Vector)request.getAttribute("list");
  Iterator i = v.iterator();
  while (i.hasNext() ){
    employee = (rfps.EmployeeBean) i.next();
%>
<LI>
<a href="http://localhost:8080/ola2/servlet/rfps.FetchEmployeeServlet?cmd=get&id=
<%= employee.getId() %>" >
<%= employee.getFirstName() %>
<%= employee.getLastName() %>
<% } %>


</BODY>
</HTML>

valeu pessol, um grande abraço

Ricardo

cancao

Ué, mas era isso que vc devia fazer mesmo: Mostrar os valores recuperados da iteração sobre o Vector! E no fim das contas, o bean “não morreu”. :smiley:

Até.

rfpsatin

certo, certo…

  • vc viu como eu tive q fazer e como eu gostaria de ter feito?

de fato o bean não morreu rs… foi exagero de linguagem rs…

então, não to conseguindo acessar as propriedades daquela forma, to tendo que usar scriptlets e acessar direto os métodos, não quero fazer assim.

Será que é alguma configuração do tomcat?

abração.

Ricardo

rfpsatin

Pessoal, desculpem voltar ao tema novamente…

  • alguém aqui já teve este problema antes?

q q eu faço?

abraço

Ricardo

Criado 24 de novembro de 2003
Ultima resposta 27 de nov. de 2003
Respostas 6
Participantes 2