这是我用来通过java中的servlet页面连接到MySQL数据库的代码,我试图将用户从注册页面转发到感谢页面或注册错误页面
// Get parameters from the request
String uname = request.getParameter("uname");
String pass = request.getParameter("pass");
String email = request.getParameter("email");
String country = request.getParameter("country");
// Check Mandatory Fields
if(pass == null||uname == null||email == null){
RequestDispatcher dispatcher =
request.getRequestDispatcher("regerror.jsp");
dispatcher.forward(request, response);
}
else{
//Establish connection to Database
Connection con = null;
Statement stmt = null;
String databaseURL = "jdbc:mysql://localhost:3306/account";
String driverName = "com.mysql.jdbc.Driver";
String user = "root";
String password = "root";
try {
Class.forName(driverName).newInstance();
con = DriverManager.getConnection(databaseURL, user, password);
stmt = con.createStatement();
} catch (Exception e) {
System.out.println("ERROR Connecting to DB: " + e);
return;
}
//Insert SQL statement
String insertStmt = "insert into account values ("
+ "'" + uname + "', "
+ "'" + pass + "', "
+ "'" + email + "',"
+ "'" + country + "'"
+ ")";
// Execute the insert statement
try {
stmt.executeUpdate(insertStmt);
} catch (Exception e) {
System.out.println("ERROR: Insert into DB: " + e);
return;
}
//Close the database connection
try {
stmt.close();
con.close();
} catch (SQLException e) {
System.out.println("ERROR: closing DB connection: " + e);
}
}
RequestDispatcher dispatcher3 =
request.getRequestDispatcher("thanks.jsp");
dispatcher3.forward(request, response);
}
当您单击“提交”按钮时,会有一个注册表单页面将您带到此servlet,但是当您单击“提交”按钮时,它只会显示一个空白页面,而不是将我带到" thanks.jsp&# 34;或者" regerror.jsp"页。当我删除if,else语句并在页面开头放置一个请求调度程序时,代码似乎有效,所以我知道寄存器jsp将你带到这个servlet。