11.4总结
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
private UserService userService = new UserServiceImpl();
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
String userId = request.getParameter("userId");
String password = request.getParameter("password");
String userType = request.getParameter("userType");
// 验证用户身份
Object user = userService.login(userId, password, userType);
if (user != null) {
// 存储用户信息到Session
request.getSession().setAttribute("user", user);
request.getSession().setAttribute("userType", userType);
// 跳转对应功能页
if ("admin".equals(userType)) {
response.sendRedirect(request.getContextPath() + "/admin/index.jsp");
} else if ("teacher".equals(userType)) {
response.sendRedirect(request.getContextPath() + "/teacher/index.jsp");
} else if ("student".equals(userType)) {
response.sendRedirect(request.getContextPath() + "/student/index.jsp");
}
} else {
request.setAttribute("errorMsg", "账号或密码错误");
request.getRequestDispatcher("/login.jsp").forward(request, response);
}
}
}

浙公网安备 33010602011771号