当前位置:网站首页>2. login and exit function development
2. login and exit function development
2022-06-24 10:15:00 【xjhqre】
Login and exit function development
1、 Login function development
1.1、 establish MVC structure
Landing site :http://localhost:8080/backend/page/login/login.html
1、 Create an employee entity class Employee
package com.itheima.reggie.entity;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.TableField;
import lombok.Data;
import java.io.Serializable;
import java.time.LocalDateTime;
/** * @Author: xjhqre * @DateTime: 2022/6/15 16:45 */
@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; // Id card number
private Integer status;
private LocalDateTime createTime;
private LocalDateTime updateTime;
@TableField(fill = FieldFill.INSERT)
private Long createUser;
@TableField(fill = FieldFill.INSERT_UPDATE)
private Long updateUser;
}
2、 establish MVC Catalog :controller、service、service.impl、mapper
3、 establish EmployeeMapper
package com.itheima.reggie.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.itheima.reggie.entity.Employee;
import org.apache.ibatis.annotations.Mapper;
/** * @Author: xjhqre * @DateTime: 2022/6/15 16:47 */
@Mapper
public interface EmployeeMapper extends BaseMapper<Employee> {
}
4、 establish EmployeeService
package com.itheima.reggie.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.itheima.reggie.entity.Employee;
/** * @Author: xjhqre * @DateTime: 2022/6/15 16:48 */
public interface EmployeeService extends IService<Employee> {
}
5、 establish EmployeeServiceImpl
package com.itheima.reggie.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.mapper.EmployeeMapper;
import com.itheima.reggie.service.EmployeeService;
import org.springframework.stereotype.Service;
/** * @Author: xjhqre * @DateTime: 2022/6/15 16:48 */
@Service
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper, Employee> implements EmployeeService {
}
6、 establish EmployeeController
package com.itheima.reggie.controller;
import com.itheima.reggie.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/** * @Author: xjhqre * @DateTime: 2022/6/15 16:50 */
@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {
@Autowired
private EmployeeService employeeService;
}
1.2、 Create a return value class R
establish common Catalog , Create... In this directory R
Used to return information to the front end , Encapsulate all the information you need to transfer as R object
package com.itheima.reggie.common;
import lombok.Data;
import java.util.HashMap;
import java.util.Map;
/** * @Author: xjhqre * @DateTime: 2022/6/15 17:04 */
@Data
public class R<T> {
private Integer code; // code :1 success ,0 And other numbers are failures
private String msg; // error message
private T data; // data
private Map map = new HashMap(); // Dynamic data
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;
}
}
1.3、 stay controller Create login method in
establish login Method , route :com/itheima/reggie/controller/EmployeeController.java
/** * Employee login * @param request * @param employee * @return */
@PostMapping("/login")
public R<Employee> login(HttpServletRequest request, @RequestBody Employee employee) {
// 1. Submit the password of the page password Conduct md5 Encryption processing , The same string goes through MD5 The encrypted result is the same
String password = employee.getPassword();
password = DigestUtils.md5DigestAsHex(password.getBytes());
// 2. According to the user name submitted on the page username Query the database
LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(Employee::getUsername, employee.getUsername());
Employee emp = employeeService.getOne(queryWrapper); // username Field uniqueness
// 3. If there is no query, the login failure result will be returned
if (emp == null) {
return R.error(" Login failed ");
}
// 4. Password comparison . If not, the login failure result will be returned
if (!emp.getPassword().equals(password)) {
// If the password in the database is different from the passed in parameter password
return R.error(" Login failed ");
}
// 5. View employee status , If it is disabled , The disabled employee result is returned
if (emp.getStatus() == 0) {
return R.error(" Account has been disabled ");
}
// 6. Login successful , Staff id Deposit in session And return the login success result
request.getSession().setAttribute("employee", emp.getId());
return R.success(emp); // Look up the data from the database emp Deposit in R in
}
1.4、 Debug timeout resolution
modify request.js In the file timeout Parameters , route :backend/js/request.js

2、 Exit function development
After clicking the exit button , Send request to backend , Back end cleanup session Users in id And back to success
2.1 Create exit method
stay EmployeeController Created in logout Method , route :com/itheima/reggie/controller/EmployeeController.java
/** * The employee exits the current account * @param request * @return */
@PostMapping("/logout")
public R<String> logout(HttpServletRequest request) {
request.getSession().removeAttribute("employee");
return R.success(" Quit successfully ");
}
3、 Block unlisted users
If the employee is not logged in, it is forbidden to access index home page , Return to the login page .
Implementation method :
- Create custom filters
LoginCheckFilter - Add annotations to the startup class
@ServletComponentScan - Improve the processing logic of the filter
3.1、 establish Filter
Create directory filter, Create... In this directory LoginCheckFilter class
On the front end request.js The response interceptor in the file is based on res.data.code and res.data.msg Determine whether you need to return to the login page , So if the interceptor in the back end intercepts a request, it needs to write back one R Pass it to the front end for judgment .

package com.itheima.reggie.filter;
import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.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;
/** * @Author: xjhqre * @DateTime: 2022/6/16 20:45 */
@Slf4j
@WebFilter(filterName = "loginCheckFilter", urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
// Path matcher , Support for wildcards
public static final AntPathMatcher 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;
// 1. Get this request's URI
String requestURI = request.getRequestURI();
log.info(" Intercept request :{}", requestURI);
String [] urls = new String[]{
// Define the request path that does not need to be processed
"/employee/login",
"/employee/logout",
"/backend/**",
"/front/**"
};
// 2. Judge whether this request needs to be processed
boolean check = check(urls, requestURI);
// 3. If it doesn't need to be dealt with , Then direct release
if (check) {
log.info(" This request {} No need to deal with :", requestURI);
filterChain.doFilter(request, response);
return;
}
// 4. Judge whether you have logged in , If you have already logged in, you can release it directly
if (request.getSession().getAttribute("employee") != null) {
log.info(" The user has logged in , user id by :{}", request.getSession().getAttribute("employee"));
filterChain.doFilter(request, response);
return;
}
// 5. If you are not logged in, you will directly return the result of not logging in
log.info(" The user is not logged in ");
response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
}
/** * Match path , Check whether this request needs to be released * @param urls * @param requestURI * @return */
public boolean check(String[] urls, String requestURI) {
for (String url : urls) {
boolean match = PATH_MATCHER.match(url, requestURI);
if (match) {
return true;
}
}
return false;
}
}
3.2、 Add... In the main startup class @ServletComponentScan

3.3、 Test the interceptor
Home address :http://localhost:8080/backend/index.html
Login address :http://localhost:8080/backend/page/login/login.html
边栏推荐
- 静态链接库和动态链接库的区别
- web网站开发,图片懒加载
- NVIDIA's CVPR 2022 oral is on fire! 2D images become realistic 3D objects in seconds! Here comes the virtual jazz band!
- 二叉树第一部分
- 学习使用phpstripslashe函数去除反斜杠
- 分布式 | 如何与 DBLE 进行“秘密通话”
- SQL Server AVG函数取整问题
- YOLOv6:又快又准的目标检测框架开源啦
- Why is JSX syntax so popular?
- How to manage massive network infrastructure?
猜你喜欢

Tutorial (5.0) 08 Fortinet security architecture integration and fortixdr * fortiedr * Fortinet network security expert NSE 5

Programming questions (continuously updated)

411-栈和队列(20. 有效的括号、1047. 删除字符串中的所有相邻重复项、150. 逆波兰表达式求值、239. 滑动窗口最大值、347. 前 K 个高频元素)

YOLOv6:又快又准的目标检测框架开源啦

Three ways to use applicationcontextinitializer

413-二叉树基础

Use of vim

线程池的状态

numpy.linspace()

uniapp实现点击拨打电话功能
随机推荐
Get the QR code of wechat applet with parameters - and share the source code of modifying the QR code logo
YOLOv6:又快又准的目标检测框架开源啦
SQL Server AVG function rounding
NVIDIA's CVPR 2022 oral is on fire! 2D images become realistic 3D objects in seconds! Here comes the virtual jazz band!
Array seamless scrolling demo
SQL Server AVG函数取整问题
canvas管道动画js特效
Regular matching mailbox
机器学习——主成分分析(PCA)
416 binary tree (first, middle and last order traversal iteration method)
port 22: Connection refused
Top issue tpami 2022! Behavior recognition based on different data modes: a recent review
二叉树第一部分
学习使用KindEditor富文本编辑器,点击上传图片遮罩太大或白屏解决方案
机器学习——感知机及K近邻
413 binary tree Foundation
p5.js千纸鹤动画背景js特效
Getting user information for applet learning (getuserprofile and getUserInfo)
被困英西中学的师生安全和食物有保障
Programming questions (continuously updated)