J'essaie de passer ArrayList qui contient un objet de servlet à JSP. Mais
Fichier de servlet:
request.setAttribute("servletName", categoryList); //categorylist is an arraylist contains object of class category
getServletConfig().getServletContext().getRequestDispatcher("/GetCategory.jsp").forward(request,response);
Fichier JSP:
//category class
<% Category category = new Category();
//creating arraylist object of type category class
ArrayList<Category> list = ArrayList<Category>();
//storing passed value from jsp
list = request.getAttribute("servletName");
for(int i = 0; i < list.size(); i++) {
category = list.get(i);
out.println( category.getId());
out.println(category.getName());
out.println(category.getMainCategoryId() );
}
%>
Dans le code de servlet, avec l'instruction request.setAttribute("servletName", categoryList)
, vous enregistrez votre liste dans l'objet de requête et utilisez le nom "nom_servlet" pour le référencer.
Au fait, utiliser ensuite le nom "servletName" pour une liste est assez déroutant, il vaut peut-être mieux l'appeler "liste" ou quelque chose de similaire: request.setAttribute("list", categoryList)
Quoi qu'il en soit, supposons que vous ne changiez pas votre code serlvet et que vous stockiez la liste sous le nom "servletName". Lorsque vous arrivez à votre JSP, il est nécessaire de récupérer la liste à partir de la demande. Pour cela, vous avez simplement besoin de la méthode request.getAttribute(...)
.
<%
// retrieve your list from the request, with casting
ArrayList<Category> list = (ArrayList<Category>) request.getAttribute("servletName");
// print the information about every category of the list
for(Category category : list) {
out.println(category.getId());
out.println(category.getName());
out.println(category.getMainCategoryId());
}
%>
La méthode request.getAttribute("servletName")
retournera Object
que vous devez transtyper en ArrayList
ArrayList<Category> list =new ArrayList<Category>();
//storing passed value from jsp
list = (ArrayList<Category>)request.getAttribute("servletName");
<html>
<%
ArrayList<Actor> list = new ArrayList<Actor>();
list = (ArrayList<Actor>) request.getAttribute("actors");
%>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Actor</title>
</head>
<body>
<h2>This is Actor Class</h2>
<table>
<thead>
<tr>
<th>Id</th>
<th>First Name</th>
<th>Last Name</th>
</tr>
</thead>
<tbody>
<% for(int i = 0; i < list.size(); i++) {
Actor actor = new Actor();
actor = list.get(i);
//out.println(actor.getId());
//out.println(actor.getFirstname());
//out.println(actor.getLastname());
%>
<tr>
<td><%=actor.getId()%></td>
<td><%=actor.getFirstname()%></td>
<td><%=actor.getLastname()%></td>
</tr>
<%
};
%>
</tbody>
</table>
</body>
les erreurs possibles seraient ...
1.vous définissez la liste de tableaux du servelt dans la session, pas celle de la requête.
2.le tableau que vous avez défini est nul.
3.vous redirigez la page au lieu de la transférer .
De plus, vous ne devriez pas initialiser les list
et category
dans jsp. essaye ça.
for(Category cx: ((ArrayList<Category>)request.getAttribute("servletName"))) {
out.println( cx.getId());
out.println(cx.getName());
out.println(cx.getMainCategoryId() );
}
public class myActorServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private String name;
private String user;
private String pass;
private String given_table;
private String tid;
private String firstname;
private String lastname;
private String action;
@Override
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
response.setContentType("text/html");
// connecting to database
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
PrintWriter out = response.getWriter();
name = request.getParameter("screenName");
user = request.getParameter("username");
pass = request.getParameter("password");
tid = request.getParameter("tid");
firstname = request.getParameter("firstname");
lastname = request.getParameter("lastname");
action = request.getParameter("action");
given_table = request.getParameter("tableName");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet JDBC</title>");
out.println("<link rel=\"stylesheet\" type=\"text/css\" href=\"style.css\">");
out.println("</head>");
out.println("<body>");
out.println("<h1>Hello, " + name + " </h1>");
out.println("<h1>Servlet JDBC</h1>");
/////////////////////////
// init connection object
String sqlSelect = "SELECT * FROM `" + given_table + "`";
String sqlInsert = "INSERT INTO `" + given_table + "`(`firstName`, `lastName`) VALUES ('" + firstname + "', '" + lastname + "')";
String sqlUpdate = "UPDATE `" + given_table + "` SET `firstName`='" + firstname + "',`lastName`='" + lastname + "' WHERE `id`=" + tid + "";
String sqlDelete = "DELETE FROM `" + given_table + "` WHERE `id` = '" + tid + "'";
//////////////////////////////////////////////////////////
out.println(
"<p>Reading Table Data...Pass to JSP File...Okay<p>");
ArrayList<Actor> list = new ArrayList<Actor>();
// connecting to database
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/javabase", user, pass);
stmt = con.createStatement();
rs = stmt.executeQuery(sqlSelect);
// displaying records
while (rs.next()) {
Actor actor = new Actor();
actor.setId(rs.getInt("id"));
actor.setLastname(rs.getString("lastname"));
actor.setFirstname(rs.getString("firstname"));
list.add(actor);
}
request.setAttribute("actors", list);
RequestDispatcher view = request.getRequestDispatcher("myActors_1.jsp");
view.forward(request, response);
} catch (SQLException e) {
throw new ServletException("Servlet Could not display records.", e);
} catch (ClassNotFoundException e) {
throw new ServletException("JDBC Driver not found.", e);
} finally {
try {
if (rs != null) {
rs.close();
rs = null;
}
if (stmt != null) {
stmt.close();
stmt = null;
}
if (con != null) {
con.close();
con = null;
}
} catch (SQLException e) {
}
}
out.println("</body></html>");
out.close();
}
}