servlets - Displaying database result in JSP -


i have controller servlet forward request model servlet.now when model gets results database, forwarding jsp.i not sure write in jsp because need show table of customerlist.here part of model servlet:

protected void processrequest(httpservletrequest request, httpservletresponse response)         throws servletexception, ioexception {     connection connection = getdatabaseconnection();     request.setattribute("customerlist", getcustomerlist(connection));     closedatabaseconnection(connection); }  private vector<customer> getcustomerlist(connection con) {     string sqlstr =             "select * " +             "from customer " +             "order name";     preparedstatement stmt = null;     resultset rs = null;     vector<customer> customers = new vector<customer>();      try     {         stmt = con.preparestatement(sqlstr);         rs = stmt.executequery();          while (rs.next())         {             customer customer = new customer();             customer.setid(rs.getint("id"));             customer.setname(rs.getstring("name"));             customer.setaddress(rs.getstring("address"));              customers.add(customer);         }          rs.close();         stmt.close();     }     catch (sqlexception sqle)     {         sqle.printstacktrace();     }         {         return customers;     } 

use jstl c:foreach tag. if servletcontainer doesn't support (e.g. tomcat), need drop jstl-1.2.jar in /web-inf/lib. declare jstl core taglib in top of jsp page per documentation.

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> 

then can use of jstl core tags in jsp. you've put vector<customer> (eek, legacy class .. rather use list<customer> customers = new arraylist<customer>() instead) in request scope attribute name customerlist. it's available ${customerlist} in el. feed items attribute of <c:foreach> , render <table> accordingly.

<table>     <c:foreach items="${customerlist}" var="customer">         <tr>             <td><c:out value="${customer.id}" /></td>             <td><c:out value="${customer.name}" /></td>             <td><c:out value="${customer.address}" /></td>         </tr>     </c:foreach> </table> 

the <c:out> way not necessary, useful if concerns user-controlled input since prevents xss attacks.

that said, jdbc part can done better. it's still sensitive resource leaking in case of exceptions.

see also:


Comments

Popular posts from this blog

android - Spacing between the stars of a rating bar? -

html - Instapaper-like algorithm -

c# - How to execute a particular part of code asynchronously in a class -