当前位置:网站首页>Realize the function of verifying whether the user has completed login when browsing the page
Realize the function of verifying whether the user has completed login when browsing the page
2022-07-05 21:04:00 【Endless silence】
One . Realization principle
Implementation steps :
1、 Create custom filters LoginWebFilter.java
2、 Add annotations to the startup class @ServletComponentScan, To scan web Related notes
3、 Improve the processing logic of the filter
Two . Code implementation
First, in the main/java/ Next create a filter Folders are used to store all filter files , Create a... In this folder LoginWebFilter.java
Next, add annotations to the startup class @ServletComponentScan, To scan web Related notes
Last Improve the processing logic of the filter
Filter processing logic
LoginWebFilter class
package com.itheima.regiee.filter;
import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.annotation.JsonAlias;
import com.itheima.regiee.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;
/**
* Check whether the employee logs in
*/
@WebFilter(filterName = "loginWebFilter",urlPatterns = "/*")
@Slf4j
public class LoginWebFilter implements Filter {
private static AntPathMatcher pathMatcher=new AntPathMatcher(); //uri Automatic matching
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request=(HttpServletRequest) servletRequest; // Cast to Httpservlet
HttpServletResponse response=(HttpServletResponse) servletResponse;
/**
* 1、 Get this request's URI
* 2、 Judge whether this request needs to be processed
* 3、 If it doesn't need to be dealt with , Then direct release
* 4、 Determine login status , If you are logged in , Then direct release
* 5、 If you are not logged in, the result of not logging in will be returned
*/
//1、 Get this request's URl
String requestUrl=request.getRequestURI();
// It is necessary to define the release request
String[] uris=new String[]{ // These requests need to be released
"/employee/login",
"/employee/logout",
"/backend/**",
"/front/**"
};
//2、 Judge whether this request needs to be processed
boolean flag=check(uris,requestUrl);
if(flag){ // This request for direct release
filterChain.doFilter(request,response);
return; // If this request is not intercepted , There is no need to go to the following code
}
//long id = (long)request.getSession().getAttribute("employee");
//4、 Determine login status , If you are logged in , Then direct release , This attribute Is to record whether you have logged in
if(request.getSession().getAttribute("employee")!=null){ // Indicates that you are logged in
filterChain.doFilter(request,response);
return;
}
//5、 If you are not logged in, the result of not logging in will be returned
// Set back json Format , You can see res.data.msg Is the output stream returned
response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
return;
}
/**
* Path matching , If you check whether this request needs to be released
* @param uris
* @param requestUrl
* @return
*/
public boolean check(String[] uris,String requestUrl){
for (String s : uris) { // Requested url Address to see if it needs to be released , among urlis All resources in need of release
boolean flag=pathMatcher.match(s,requestUrl);
if(flag){ // Match up , Explain that the requested resources need to be released
return true;
}
}
return false; // Explain that the requested address cannot be released
}
}
R Tool class of
package com.itheima.regiee.common;
import lombok.Data;
import java.util.HashMap;
import java.util.Map;
/*
* General return result , The data responded by the server will eventually be encapsulated into this object
* */
@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;
}
}
front end vue.js
边栏推荐
- @Validated基础参数校验、分组参数验证和嵌套参数验证
- vant 源码解析 之深层 合并对象 深拷贝
- 从架构上详解技术(SLB,Redis,Mysql,Kafka,Clickhouse)的各类热点问题
- 序列联配Sequence Alignment
- vant 源码解析 event.ts 事件处理 全局函数 addEventListener详解
- 【日常训练】729. 我的日程安排表 I
- What are the requirements of UL 2043 test for drive housing in the United States?
- Analyze the knowledge transfer and sharing spirit of maker Education
- LeetCode_哈希表_困难_149. 直线上最多的点数
- Determine the best implementation of horizontal and vertical screens
猜你喜欢
Analysis of steam education mode under the integration of five Education
Clion-MinGW编译后的exe文件添加ico图标
示波器探头对信号源阻抗的影响
How to make ERP inventory accounts of chemical enterprises more accurate
ClickHouse 复制粘贴多行sql语句报错
MySQL deep paging optimization with tens of millions of data, and online failure is rejected!
Pytoch practice -- MNIST dataset handwritten digit recognition
研學旅遊實踐教育的開展助力文旅產業發展
2. < tag hash table, string> supplement: Sword finger offer 50 The first character DBC that appears only once
Five layer network protocol
随机推荐
SYSTEMd resolved enable debug log
Clear app data and get Icon
EN 438-7建筑覆盖物装饰用层压板材产品—CE认证
Influence of oscilloscope probe on signal source impedance
Dictionary tree simple introductory question (actually blue question?)
XML建模
PVC plastic sheets BS 476-6 determination of flame propagation properties
LeetCode: Distinct Subsequences [115]
SQL series (basic) - Chapter 2 limiting and sorting data
Binary search
Aitm 2-0003 horizontal combustion test
启牛2980有没有用?开户安全吗、
shell编程100例
PHP反序列化+MD5碰撞
Implementation of redis unique ID generator
The development of research tourism practical education helps the development of cultural tourism industry
js常用方法封装
Clion configures Visual Studio (MSVC) and JOM multi-core compilation
Add ICO icon to clion MinGW compiled EXE file
Duchefa cytokinin dihydrozeatin (DHZ) instructions