servlet向jsp传值request.getAttribute()拿到的是Null

这是servlet
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/db_java?serverTimezone=GMT";
String username = "root";
String password = "root";
Connection conn = DriverManager.getConnection(url,username,password);
Statement stmt = conn.createStatement();
String sql = "select * from tb_servent";
ResultSet rs = stmt.executeQuery(sql);
List<Servent> list = new ArrayList<Servent>();
while(rs.next()){
Servent servent = new Servent();
servent.setId(rs.getInt("id"));
servent.setName(rs.getString("name"));
list.add(servent);
}
request.setAttribute("list", list);
rs.close();
stmt.close();
conn.close();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
request.getRequestDispatcher("index.jsp").forward(request, response);
}
这是jsp
List<Servent> list = (List<Servent>)request.getAttribute("list");
servlet页面运行是可以的,但jsp页面就是null
最新回答
怪味

2024-06-30 09:07:59

首先排查一下list的值本身是不是null。照道理是有值的。
追问
从servlet运行的话list是有值的,从jsp页面运行list是null
追答
那当然了,list的值是通过数据库进去的,你最好打断点跟踪一下代码
追问
跟踪了,结果就是刚才说的那样,从servlet运行会正常运行,转到index页面时list是有值的,但直接从index页面运行list就是null