|
|
package com.yanzhen.controller;
|
|
|
|
|
|
import com.yanzhen.entity.Student;
|
|
|
import com.yanzhen.entity.User;
|
|
|
import com.yanzhen.framework.jwt.JWTUtil;
|
|
|
import com.yanzhen.service.StudentService学生管理;
|
|
|
import com.yanzhen.service.UserService用户管理;
|
|
|
import com.yanzhen.utils.Result;
|
|
|
import org.springframework.beans.factory.annotation.Autowired;
|
|
|
import org.springframework.web.bind.annotation.PostMapping;
|
|
|
import org.springframework.web.bind.annotation.RequestBody;
|
|
|
import org.springframework.web.bind.annotation.RestController;
|
|
|
|
|
|
import java.util.HashMap;
|
|
|
import java.util.Map;
|
|
|
|
|
|
@RestController // 声明这是一个控制器,并且返回的数据直接写入 HTTP 响应体中,而不是解析为跳转路径。
|
|
|
public class LoginController { // 定义一个名为 LoginController 的类,用于处理登录相关的请求。
|
|
|
|
|
|
@Autowired // 自动注入 UserService 实例,用于处理用户相关的业务逻辑。
|
|
|
private UserService用户管理 userService;
|
|
|
|
|
|
@Autowired // 自动注入 StudentService 实例,用于处理学生相关的业务逻辑。
|
|
|
private StudentService学生管理 studentService;
|
|
|
|
|
|
@PostMapping("/login") // 映射 HTTP POST 请求到 /login 路径上,用于处理登录请求。
|
|
|
public Result login(@RequestBody User user){ // 定义一个方法 login,接收一个 User 对象作为请求体。
|
|
|
if(user.getType() == 2){ // 如果用户类型是学生(假设类型为2表示学生)。
|
|
|
Student entity = studentService.login(user.getUserName(),user.getPassword()); // 调用 studentService 的 login 方法验证学生身份。
|
|
|
if(entity != null){ // 如果学生信息存在,即登录成功。
|
|
|
String token = JWTUtil.signForStudent(entity); // 生成针对学生的 JWT 令牌。
|
|
|
Map map = new HashMap(); // 创建一个 Map 对象存储返回数据。
|
|
|
map.put(JWTUtil.token,token); // 将 JWT 令牌放入 Map。
|
|
|
map.put("student",entity); // 将学生实体信息放入 Map。
|
|
|
return Result.ok("登陆成功",map); // 返回包含成功消息和数据的 Result 对象。
|
|
|
}else{ // 如果学生信息不存在,即登录失败。
|
|
|
return Result.fail("用户名或密码错误"); // 返回包含错误信息的 Result 对象。
|
|
|
}
|
|
|
}else{ // 如果用户类型不是学生(管理员或宿管员)。
|
|
|
User entity = userService.login(user.getUserName(),user.getPassword()); // 调用 userService 的 login 方法验证用户身份。
|
|
|
if(entity != null){ // 如果用户信息存在,即登录成功。
|
|
|
String token = JWTUtil.sign(entity); // 生成通用的 JWT 令牌。
|
|
|
Map map = new HashMap(); // 创建一个 Map 对象存储返回数据。
|
|
|
map.put(JWTUtil.token,token); // 将 JWT 令牌放入 Map。
|
|
|
map.put("user",entity); // 将用户实体信息放入 Map。
|
|
|
return Result.ok("登陆成功",map); // 返回包含成功消息和数据的 Result 对象。
|
|
|
}else{ // 如果用户信息不存在,即登录失败。
|
|
|
return Result.fail("用户名或密码错误"); // 返回包含错误信息的 Result 对象。
|
|
|
}
|
|
|
}
|
|
|
}
|
|
|
} |