【问题标题】:Use ResultSet object in JSP without JSTL在没有 JSTL 的 JSP 中使用 ResultSet 对象
【发布时间】:2012-10-06 17:05:22
【问题描述】:

我想将我的查询结果,即 ResultSet 传递给 JSP,只是为了显示,因为我正在使用 MVC 框架。

我的 Servlet 代码:

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


                   }
      }

我使用 ResultSupport.toResult() 将其转发到 JSP(由“我们”映射转发),但这需要 JSP 中的 JSTL 代码:

用户.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>

此外,如果我像 request.setAttribute("ResultSet",rs); 这样直接传递 ResultSet,我将无法在 JSP 中关闭连接。

此代码工作正常,但我不想使用 JSTL/EL 或 Lists,我想在 JSP 中使用可以处理来自 Servlet 的 Result 或 ResultSet 属性的脚本。

【问题讨论】:

  • 为什么。你为什么想这么做。 “因为我正在使用 MVC 框架?”但你只是想跳过M?呜呜呜。
  • 为什么,不能将表格的视图部分传输到 JSP 并使用简单的脚本吗??
  • 当然,这有点可能——这只是一个可怕的想法,在多个层面上。小脚本很糟糕。在 JSP 呈现期间保持 ResultSet 打开是不好的。结果我至少更好;不知道为什么不能在 scriptlet 中使用结果。也不知道你为什么想要,但这是一个不同的问题。

标签: model-view-controller jsp servlets resultset


【解决方案1】:

你可以这样解决你的问题:

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

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

2) 然后使用 List 来存储你的结果

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

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

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

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

ArrayList<Contacts> myList = (ArrayList<Contacts>) request.getAttribute("LIST");
for(Contacts obj: myList){
  out.print(obj.getMail());
  ....
  ....
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-01-21
    • 2019-08-14
    • 1970-01-01
    • 2018-08-06
    • 2017-07-22
    • 1970-01-01
    • 1970-01-01
    • 2013-02-23
    相关资源
    最近更新 更多