Maison > Questions et réponses > le corps du texte
这是数据库
servlet代码那个currentUser怎么查都是null。。。
// 从request出获取要查询的数据并封装 String userName = request.getParameter("userName"); String password = request.getParameter("password"); if (userName == null || userName.length() == 0 || password == null || password.length() == 0) { request.setAttribute("error", "用户名或密码不能为空!"); request.getRequestDispatcher("userLogin.jsp").forward(request, response); } User user = new User(userName, password); // 查询并生成currentUser与currentStudent User currentUser = null; UserDao userDao = DaoFactory.createUserDao(); Student currentStudent = null; StudentDao studentDao = DaoFactory.createStudentDao(); try { currentUser = userDao.selectUser(user); // 验证 if (currentUser != null) { //currentUser不为空,查询对应的currentStudent currentStudent = studentDao.selectStudent(currentUser); // 在session中保存currentUser与currentStudent HttpSession session = request.getSession(); session.setAttribute("currentUser", currentUser); session.setAttribute("currentStudent", currentStudent); response.sendRedirect("userMain.jsp"); } else { // 提示错误信息,同时将错误信息返回,优化用户体验 request.setAttribute("error", "用户名或密码错误!"); request.setAttribute("userName", userName); request.getRequestDispatcher("userLogin.jsp").forward(request, response); } } catch (SQLException e) { e.printStackTrace(); } finally { userDao.closeConn(); studentDao.closeConn(); }
标题文字
// 查找用户public User selectUser(User user) throws SQLException {
User resultUser = null; String sql = "select * from t_user where userName = ? and password = ?"; PreparedStatement pstmt = conn.prepareStatement(sql); pstmt.setString(1, user.getUserName()); pstmt.setString(2, user.getPassword()); ResultSet rs = pstmt.executeQuery(); // 要找也只会找到一个,所以这边就用if了 //返回时带出id if (rs.next()) { resultUser = new User(); resultUser.setId(rs.getInt("id")); resultUser.setUserName(rs.getString("userName")); resultUser.setPassword(rs.getString("password")); } return resultUser;
debug模式截图
不开tomcat直接
测试代码
public static void main(String[] args) throws SQLException {
User user = new User("testUser1", "123456"); UserDao userDao = DaoFactory.createUserDao(); User currentUser = userDao.selectUser(user); System.out.println(currentUser.getId()); userDao.closeConn(); }
三叔2016-10-28 14:27:43
请思考下面的问题:
1.
request.getParameter("userName");你传参数的时候userName 是中间大写的?我看不像。name="username"?
2.
测试方法只是表示你DAO没有问题,你数据库没有连错地方,数据库的表是能取到数据的。
3.
问题往往出现在源头上,不要纠结于过程,你的过程代码很稳当。也许你第一步就没取到。直接被forward了,你关注了吗?forward完了 继续跑 userName="",当然取不到,你又没有及时return。
4.
你打几个断点跑一下不就完啦,尤其是取参数。。