11.28
- Controller 层(LoginServlet.java):处理登录请求
创建com.student.daily.controller.LoginServlet.java,继承HttpServlet,处理前端登录请求:
java
运行
package com.student.daily.controller;
import com.student.daily.entity.User;
import com.student.daily.service.UserService;
import com.student.daily.service.impl.UserServiceImpl;
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 javax.servlet.http.HttpSession;
import java.io.IOException;
/**
-
登录Servlet(处理登录请求)
-
班级:2023级XX班
-
作者:XXX
-
学号:2023XXXX
-
日期:2024-12-27
*/
@WebServlet("/login") // 配置Servlet访问路径
public class LoginServlet extends HttpServlet {
private UserService userService = new UserServiceImpl();@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 1. 设置请求编码(解决中文乱码)
request.setCharacterEncoding("UTF-8");
// 2. 获取前端传递的参数(账号、角色)
String userId = request.getParameter("userId"); // 对应登录页输入框name="userId"
String userCategoryStr = request.getParameter("userCategory"); // 角色(0/1/2)
Integer userCategory = Integer.parseInt(userCategoryStr); // 转换为整数// 3. 调用Service层登录方法 User user = userService.login(userId, userCategory); // 4. 处理登录结果 if (user != null) { // 登录成功:将用户信息存入Session(用于后续权限判断) HttpSession session = request.getSession(); session.setAttribute("loginUser", user); // 根据角色跳转至对应功能页 if (userCategory == 0) { // 学生 response.sendRedirect(request.getContextPath() + "/student/index.jsp"); } else if (userCategory == 1) { // 小组长 response.sendRedirect(request.getContextPath() + "/leader/index.jsp"); } else if (userCategory == 2) { // 教师 response.sendRedirect(request.getContextPath() + "/teacher/index.jsp"); } } else { // 登录失败:返回登录页,提示错误信息 request.setAttribute("errorMsg", "账号或角色错误,请重新选择!"); request.getRequestDispatcher("/login.jsp").forward(request, response); }}
// 处理GET请求(默认跳转登录页)
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
}
- 前端登录页面(login.jsp):用户交互界面
在webapp目录下创建login.jsp,设计登录表单(包含账号输入框、角色下拉框、登录按钮):
jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>

浙公网安备 33010602011771号