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
提交
取消