首先给出这篇博客讲的功能前端所调用的接口:
/employee/login ------登陆
/employee/logout ------退出
一、登陆功能
分析:我们可以拿到用户输入的账号和密码,封装成Employee对象,然后进行md5加密,接着根据用户名查找数据库,若找到,则继续校验密码,若找不到,用响应类返回账号不存在;若密码正确,则继续下一步,若密码错误,则提示密码错误。若密码正确之后,需要判断账号的当前状态,若为1则登陆系统,并且把id存到session中;若为0则提示账号被禁用。
Employee类
package com.itgeima.entity;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.TableField;
import lombok.Data;
import java.io.Serializable;
import java.time.LocalDateTime;
@Data
public class Employee implements Serializable {
private static final long serialVersionUID = 1L;
private Long id;
private String username;
private String name;
private String password;
private String phone;
private String sex;
private String idNumber;
private Integer status;
private LocalDateTime createTime;
private LocalDateTime updateTime;
@TableField(fill = FieldFill.INSERT)
private Long createUser;
@TableField(fill = FieldFill.INSERT_UPDATE)
private Long updateUser;
}
响应类R
package com.itgeima.entity.result;
import lombok.Data;
import java.util.HashMap;
import java.util.Map;
@Data
public class R<T> {
private Integer code; //编码:1成功,0和其它数字为失败
private String msg; //错误信息
private T data; //数据
private Map map = new HashMap(); //动态数据
public static <T> R<T> success(T object) {
R<T> r = new R<T>();
r.data = object;
r.code = 1;
return r;
}
public static <T> R<T> error(String msg) {
R r = new R();
r.msg = msg;
r.code = 0;
return r;
}
public R<T> add(String key, Object value) {
this.map.put(key, value);
return this;
}
}
根据上述描述我们可以写代码实现controller,注意请求路径,一定写对!代码注释很详细!
package com.itgeima.controller;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.itgeima.entity.Employee;
import com.itgeima.entity.result.R;
import com.itgeima.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
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.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
@RestController
@Slf4j
@RequestMapping("/employee")
public class EmployeeController {
@Resource
private EmployeeService employeeService;
@PostMapping("/login")
public R<Employee> login(HttpServletRequest request, @RequestBody Employee employee) {
//首先把密码进行md5加密
String password = employee.getPassword();
password = DigestUtils.md5DigestAsHex(password.getBytes());
//mybatis-plus提供
QueryWrapper<Employee> queryWrapper = new QueryWrapper<>();
//eq相当于sql语句中的 == 第一个参数是数据库的列名,第二个是传过来的参数,意思就是
// select * from employee where username = employee.getUsername()
queryWrapper.eq("username", employee.getUsername());
//获取一个查到的结果,封装成employee对象
Employee emp = employeeService.getOne(queryWrapper);
if (emp == null) {
log.error("没有该用户,登陆失败!");
return R.error("没有该用户,登陆失败!");
}
if (!password.equals(emp.getPassword())) {
log.error("请检查密码是否正确");
return R.error("请检查密码是否正确");
}
if (emp.getStatus() != 1) {
log.error("抱歉,该账户已被禁用");
return R.error("抱歉,该账户已被禁用");
}
request.getSession().setAttribute("employee", emp.getId());
log.info("登陆成功!");
log.info("已经把xxx写入session");
return R.success(emp);
}
}
二,退出
这个功能实现起来比较简单,只要把session信息清除即可
package com.itgeima.controller;
import com.itgeima.entity.Employee;
import com.itgeima.entity.result.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
@RestController
@Slf4j
@RequestMapping("/employee")
public class EmployeeController {
@Resource
private EmployeeService employeeService;
@PostMapping("/logout")
public R<String> logout(HttpServletRequest request) {
request.getSession().removeAttribute("employee");
return R.success("退出成功!");
}
}
三,登陆拦截器
package com.itgeima.filter;
import com.alibaba.fastjson.JSON;
import com.itgeima.entity.result.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* 实现登陆拦截器
*/
@Slf4j
@WebFilter(filterName = "loginCheckFilter",urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
private static final AntPathMatcher ANT_PATH_MATCHER = new AntPathMatcher();
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
//获取本次请求的URI
String requestURI = request.getRequestURI();
String[] uris = new String[]{
"/employee/login",
"/employee/logout",
"/backend/**",
"/front/**"
};
boolean check1 = check(uris, requestURI);
if (check1) {
log.info("check方法被调用,放行");
log.info("拦截的请求 {}",requestURI);
filterChain.doFilter(request, response);
return;
}
if (request.getSession().getAttribute(("employee")) != null) {
filterChain.doFilter(request, response);
return;
}
if (request.getSession().getAttribute(("employee")) == null) {
//如果未登录,通过输出流方式向客户端响应数据
response.getWriter().write(JSON.toJSONString(R.error( "NOTLOGIN")));
log.error("未登录,拦截页面 {}",requestURI);
}
}
public boolean check(String[] urls, String requestURI) {
for (String url : urls) {
boolean match = ANT_PATH_MATCHER.match(url, requestURI);
if (match){
return true;
}
}
return false;
}
}