这里是12.16随笔
代码留档:package come;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
@WebServlet("/DengluServlet")
public class DengluServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String name = request.getParameter("Name");
String role = request.getParameter("role");
String password = request.getParameter("password");
try {
// 加载数据库驱动(根据你的MySQL版本可能需要调整)
Class.forName("com.mysql.cj.jdbc.Driver");
// 建立数据库连接
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/ygkaoqin", "root", "12345");
String sql = "SELECT * FROM xinxi WHERE Name =? AND role =? AND password =?";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, name);
preparedStatement.setString(2, role);
preparedStatement.setString(3, password);
ResultSet resultSet = preparedStatement.executeQuery();
if (resultSet.next()) {
if ("员工".equals(role)) {
response.sendRedirect("EmployeeFunction.jsp");
} else if ("部门经理".equals(role)) {
response.sendRedirect("ManagerFunction.jsp");
} else if ("管理员".equals(role)) {
response.sendRedirect("AdminFunction.jsp");
}
} else {
response.sendRedirect("index.jsp?error=1");// 登录失败,返回登录页面并可以显示错误信息
}
resultSet.close();
preparedStatement.close();
connection.close();
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
}
一个登录的逻辑