无法使用Servlet中的setAttribute和getString()在jsp页面上显示数据库

时间:2016-10-12 14:24:54

标签: java database jsp servlets jstl

这是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页面上的所有内容都是null。

1 个答案:

答案 0 :(得分:0)

您需要将值设置为请求而不是会话 从     session.setAttribute(“thtr”,str);

request.setAttribute("thtr", str);

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