Reputation: 31
I have an important question but firs sorry for my english, I only know the basic. Well my problem is that I have an error passing an ArrayList from a servlet to jsp page:
<% ArrayList<Usuario> u= (ArrayList<Usuario>)session.getAttribute("listado");%>
<table align="left" cellpadding="0" cellspacing="1">
<tr bgcolor="blue">
<td>Usuario</td><td>Nombre</td>
<td>Apellido</td><td>Clave</td>
</tr>
<% for(int i=0;i<u.size();i++){ %>
<% Usuario usuario = u.get(i); %>
<tr>
<td> <%= usuario.getUsuario() %></td>
<td> <%= usuario.getNombre() %></td>
<td> <%= usuario.getApellido() %></td>
<td> <%= usuario.getClave() %></td>
</tr>
<%} %>
</table>
That's how I'm doing this but I receive an error in:
<% for(int i=0;i<u.size();i++){ %>
What I'm doing wrong? also my servlet Method is like this:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
RequestDispatcher rd;
try {
Connection cn = MySQLConnection.obtenerConexion();
String sql = "select * from tb_usuario";
PreparedStatement ps = cn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
ArrayList<Usuario> listado = new ArrayList<Usuario>();
while (rs.next()){
Usuario usu = new Usuario(rs.getString(1),rs.getString(2),rs.getString(3),rs.getString(4));
listado.add(usu);
}
request.setAttribute("listado", listado);
request.getRequestDispatcher("/listado.jsp");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I hope you could help me!
Upvotes: 3
Views: 3216
Reputation: 46438
scriptlets
are discouraged to use in ajsp page, use JSTL tags
instead. use c-foreach tag
to iterate over your arrayList in your jsp page. and you are setting an attribute in a request scope and trying to get it in session scope in your jsp.
heres the link which explains c-foreach tag
Upvotes: 1
Reputation: 4886
you are setting the value in to request scope
request.setAttribute("listado", listado);
but then trying to access it in session scope.
session.getAttribute("listado");
due to this u might get a null pointer exception in
u.size()...
try to access it in request scope
request.getAttribute("xxxxxx")
try to avoid adding java code inside JSP whihc is a bad practice. use EL and JSTL instead. you can to the casting part inside the code too..
Upvotes: 1
Reputation: 34397
You are setting the variable in request
object while retrieving from session
, which is not present hence the issue.
You are setting the attribute in doPost
as below":
request.setAttribute("listado", listado);
You are retrieving the attribute in your JSP as below":
<% ArrayList<Usuario> u= (ArrayList<Usuario>)session.getAttribute("listado");%>
Please use the same scope session
or request
in both places.
Upvotes: 2
Reputation: 51030
You should not use scriptlets in your JSP. You should use EL and tags in your JSP.
e.g.
${listado}
Upvotes: 3