1

I want to pass my query's result i.e ResultSet to JSP just for the display as i am using MVC framework.

My Servlet Code:

Connection c=Connectivity.dbConnect();
       PreparedStatement ps=c.prepareStatement("select role from login where userid=? and password=?");
       ps.setString(1,userid);
       ps.setString(2,pass);
       ResultSet rs=ps.executeQuery();

     if(rs.next())
     {

          if(rs.getString(1).equals("admin"))
                   {

           ps=c.prepareStatement("select * from user where userid=?");
           ps.setString(1,userid);
           rs=ps.executeQuery();   
           Result r=ResultSupport.toResult(rs);          
           request.setAttribute("res",r);       

           rs.close();
           c.close();
           return mapping.findForward("us");//to User.jsp


                   }
      }

I've used ResultSupport.toResult() to forward it to JSP (forwarded by 'us' mapping) but that requires JSTL code in JSP :

User.jsp -

<c:forEach var="data" items="${requestScope.res.rows}">
      <h1>${data.userid}</h1>
               <h2>${data.name}</h2>
               <h2>${data.password}</h2>
               <h2>${data.emailid}</h2>
  </c:forEach>

Moreover if i directly pass ResultSet like request.setAttribute("ResultSet",rs); i wouldn't be able to close the connection in JSP.

This Code works fine but i do NOT want to use JSTL/EL or Lists , i want to use scriplets in JSP that can handle Result or ResultSet attribute from Servlet.

4

1 回答 1

0

你可以像这样克服你的问题:

1) 在您的数据库操作类中,使用 POJO 从 ResultSet 添加结果。

Contacts myContact = new Contacts();
myContact.setOffice(rs.getString("office1"));
myContact.setMail(rs.getString("xx@xx.com"));

2)然后使用列表来存储您的结果

List<Contacts> myList = new ArrayList<Contacts>();
myList.add(myContact);

3)将列表传递给您的请求/会话对象并在那里关闭 ResultSet/Connection

request.setAttribute("LIST",myList);
rs.close(); 
conn.close()

4) 在 JSP 中获取列表并随心所欲地对其进行迭代

ArrayList<Contacts> myList = (ArrayList<Contacts>) request.getAttribute("LIST");
for(Contacts obj: myList){
  out.print(obj.getMail());
  ....
  ....
}
于 2012-10-17T06:34:03.717 回答