public?static?void?main(String[]?args)?throws?SQLException?{
UserDao?dao?=?new?UserDao()?;
List<User>?ls?=?new?ArrayList<User>();
ls?=?dao.query();
for(int?i=0?;?i<ls.size()?;?i++){
System.out.print("賬號:"+ls.get(i).getUsername()+"?,?");
System.out.println("密碼:"+ls.get(i).getPassword());
}
}以上代碼我用JAVA運行能在控制臺輸出我數據庫中的幾個數據public?void?doGet(HttpServletRequest?request,?HttpServletResponse?response)
throws?ServletException,?IOException?{
request.setCharacterEncoding("utf-8");
UserDao?dao?=?new?UserDao()?;
List<User>?ls?=?new?ArrayList<User>();
try?{
ls=dao.query();
}?catch?(SQLException?e)?{
//?TODO?Auto-generated?catch?block
e.printStackTrace();
}
String?name?=?request.getParameter("name");
String?password?=?request.getParameter("password");
for(int?i=0?;?i<ls.size()?;?i++){
if(ls.get(i).getUsername().equals(name)?&&?ls.get(i).getPassword().equals(password)){
request.getRequestDispatcher("/Success.jsp").forward(request,response);
}
else{
request.getRequestDispatcher("/Fail.jsp").forward(request,response);
}
}
}然后運行這個就報錯了我沒用數據庫的時候用if判斷就能跳轉頁面所以我感覺其他的代碼應該沒錯 就把這部分粘出來了 String?name?=?request.getParameter("name");
String?password?=?request.getParameter("password");
if("a".equals(name)?&&?"a".equals(password)){
request.getRequestDispatcher("/Success.jsp").forward(request,response);
}
else{
request.getRequestDispatcher("/Fail.jsp").forward(request,response);
}
}上面代碼是不用數據庫就可以正常跳轉 所以其他的代碼應該沒問題
5 回答

慕粉4208695
TA貢獻3條經驗 獲得超2個贊
public?class?UserDao?{ public?List<User>?query()?throws?SQLException{ Connection?conn?=?DBUtil.getConnection(); PreparedStatement?ptmt?=?null?; ResultSet?rs?=?null?; String?sql?=?"select?*?from?user?"; ptmt?=?conn.prepareStatement(sql); rs?=?ptmt.executeQuery()?; User?user?=?null?; List<User>?list?=?new?ArrayList<User>()?; while(rs.next()){ user?=?new?User()?; user.setUsername(rs.getString("username")); user.setPassword(rs.getString("password")); list.add(user); } rs.close(); ptmt.close(); conn.close(); return?list; } }
這是報錯的那個代碼 19行是ptmt = conn.prepareStatement(sql);

你好小Song
TA貢獻29條經驗 獲得超10個贊
目測是因為DBUtil里的getConnection()方法返回的connection是空.
將try{}catch(){}代碼放到getConnection()中試下,別用static{}代碼塊了.

慕粉4208695
TA貢獻3條經驗 獲得超2個贊
public?class?DBUtil?{ private?static?final?String?USER?=?"root"?; private?static?final?String?PASSWORD?=?"mj199609"?; private?static?final?String?URL?=?"jdbc:mysql://localhost:3306/reg"?; private?static?Connection?conn?=?null?; static{ try?{ Class.forName("com.mysql.jdbc.Driver"); conn?=?DriverManager.getConnection(URL,USER,PASSWORD); }catch?(ClassNotFoundException?e)?{ //?TODO?Auto-generated?catch?block e.printStackTrace(); }catch?(SQLException?e)?{ //?TODO?Auto-generated?catch?block e.printStackTrace(); } } public?static?Connection?getConnection(){ return?conn?; } }
添加回答
舉報
0/150
提交
取消