单独在java程序里是可以和数据库交互的,怎么到了servlet里就报错了?
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.*;
public class Login extends HttpServlet {
private static final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";
private static final String DB_URL = "jdbc:mysql://localhost:3306/demo";
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
String username = req.getParameter("username");
String password = req.getParameter("password");
if(username.isEmpty() || password.isEmpty()){
System.out.println("用户名或密码不能为空,请重新输入!");
resp.sendRedirect("/index.jsp");
}else{//连接数据库对比
Connection conn = null;
Statement stmt = null;
try{
// 注册 JDBC 驱动
Class.forName(JDBC_DRIVER);
// 打开链接
System.out.println("连接数据库...");
conn = DriverManager.getConnection(DB_URL,"root","root");
// 执行查询
//System.out.println(" 实例化Statement对象...");
stmt = conn.createStatement();
String sql;
sql = "SELECT password FROM user where username = '"+username+"' ";
ResultSet rs = stmt.executeQuery(sql);
// 展开结果集数据库
System.out.println(rs);
System.out.println(password);
if(rs.equals(password)){
resp.sendRedirect("/success.jsp");
}
// 完成后关闭
rs.close();
stmt.close();
conn.close();
}catch(SQLException se){
// 处理 JDBC 错误
resp.sendRedirect("/failed.jsp");
se.printStackTrace();
}catch(Exception e){
// 处理 Class.forName 错误
resp.sendRedirect("/failed.jsp");
e.printStackTrace();
}finally{
// 关闭资源
try{
if(stmt!=null) stmt.close();
}catch(SQLException se2){
}// 什么都不做
try{
if(conn!=null) conn.close();
}catch(SQLException se){
resp.sendRedirect("/failed.jsp");
se.printStackTrace();
}
}
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
报错如下:
java.lang.ClassNotFoundException: com.mysql.cj.jdbc.Driver
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1407)
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1215)
at java.base/java.lang.Class.forName0(Native Method)
at java.base/java.lang.Class.forName(Class.java:332)
at com.carlos.jdbc.Login.doGet(Login.java:29)
at com.carlos.jdbc.Login.doPost(Login.java:79)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:681)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:764)