【问题标题】:Not able to display data from database on jsp page using setAttribute and getString() in Servlet无法在 Servlet 中使用 setAttribute 和 getString() 在 jsp 页面上显示数据库中的数据
【发布时间】:2017-02-21 09:44:48
【问题描述】:

这里是 Servlet

public class displayServlet extends HttpServlet {
   protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    try (PrintWriter out = response.getWriter()) {
          Connection con = dbConnection.getConnection();
          String query = "SELECT theaterNames, FROM thtrname where id in(11,12)";
          try{
              PreparedStatement ps = con.prepareStatement(query);
              ResultSet rs = ps.executeQuery();
              String str = null;
              while(rs.next()){
                  str = rs.getString(1);
              }
              out.print(str);
              HttpSession session = request.getSession();
              session.setAttribute("thtr", str);
              RequestDispatcher rd = request.getRequestDispatcher("success.jsp");
              rd.forward(request, response);
              rs.close();
              ps.close();
              con.close();
          }catch(Exception ex){

          }

    }
}

这里是success.jsp

<%@page contentType="text/html" pageEncoding="UTF-8" session="true"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <font color="green">
            <%= request.getAttribute("thtr") %>
            <h1><c:out value="${sessionScope.thtr}" /></h1>
        </font>
    </body>
</html>

我只是不明白我哪里出错了。我同时使用 JSTL 和 Scriptlet,但我在 success.jsp 页面上得到的都是空的。

【问题讨论】:

  • String query = "SELECT theatreNames, FROM thtrname where id in(11,12)";不是有效的 SQL
  • 好的,现在我的查询就像 - String query = "SELECT TheaterNames FROM thtrname";但仍然为空。

标签: java database jsp servlets jstl


【解决方案1】:

您需要将值设置为 request 而不是 session 从 session.setAttribute("thtr", str);

request.setAttribute("thtr", str);

然后显示在 jsp 中使用 ${thtr}

【讨论】:

  • 然后检查您的选择。我认为 str 设置为 request 时为 NULL
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-11
  • 1970-01-01
相关资源
最近更新 更多