![](/img/trans.png)
[英]Unable to retrive data from database and display in JSP using Servlet
[英]Not able to display data from database on jsp page using setAttribute and getString() in Servlet
这是 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 页面上获得的所有信息都是空的。
您需要将值设置为 request 而不是 session.setAttribute("thtr", str);
到
request.setAttribute("thtr", str);
然后在jsp中显示只使用${thtr}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.