后台退出功能开发
一、需求分析
员工登录成功后,页面跳转到后台系统首页面(backend/index.html),此时会显示当前登录用户的姓名:管理员
如果员工需要退出系统,直接点击登录用户名右侧的按钮,即可退出系统,退出系统后页面应跳转回登录页面
此时单击按钮,系统会报404错误,因为我们在雇员控制器里尚未编写对应的退出处理方法
二、代码开发
二、代码分析
我们看看后台首页 - /backend/index.html
退出按钮绑定的单击事件处理函数logout()
在脚本文件/backend/api/login.js里查看logoutApi()函数
(二)编写代码
创建logout()方法,清除会话里的雇员信息,返回成功结果
● 查看雇员控制器源代码
package net.hw.controller;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import net.hw.common.R;
import net.hw.entity.Employee;
import net.hw.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
@Slf4j // 日志注解
@RestController // 交给Spring容器管理
@RequestMapping(“/employee”)
public class EmployeeController {
@Autowired
private EmployeeService employeeService;
@PostMapping("/login")
public R<Employee> login(HttpServletRequest request, @RequestBody Employee employee) {
// 1. 将页面提交的密码password进行md5加密处理
String password = employee.getPassword();
password = DigestUtils.md5DigestAsHex(password.getBytes());
// 2. 根据页面提交的用户名username查询数据库
LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>(); // 查询包装器
queryWrapper.eq(Employee::getUsername, employee.getUsername()); // 等值查询
Employee emp = employeeService.getOne(queryWrapper); // 按查询包装器进行查询
// 3. 如果没有查询到则返回登录失败结果
if (emp == null) {
return R.error("登录失败[用户名错误]");
}
// 4. 密码比对,如果不一致则返回登录失败结果
if (! emp.getPassword().equals(password)) {
return R.error("登录失败[密码错误]");
}
// 5. 查看员工状态,如果为已禁用状态,则返回员工已禁用结果
if (emp.getStatus() == 0) {
return R.error("登录失败[账号已禁用]");
}
// 6. 登录成功,将员工id存入Session并返回登录成功结果
HttpSession session = request.getSession(); // 通过请求对象获取会话
session.setAttribute("employee", emp.getId()); // 将雇员id保存到会话里
return R.success(emp); // 返回登录成功结果
}
@PostMapping("/logout")
public R<String> logout(HttpServletRequest request) {
// 清除雇员信息
request.getSession().removeAttribute("employee");
// 返回成功结果
return R.success("退出成功");
}
}
三、功能测试
重启应用,访问登录页面,成功登录之后,跳转到后台首页,单击按钮,成功退出,返回后台登录页面