当前位置:网站首页>Code de mise en œuvre de l'intercepteur et du filtre
Code de mise en œuvre de l'intercepteur et du filtre
2022-06-26 08:56:00 【La voie de l'architecture】
Code d'implémentation de l'intercepteur et du filtre
Intercepteur
1.Créer un nouveauinterceptorSac
LoginInterceptor.java
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/** Définir l'intercepteur du processeur */
public class LoginInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if (request.getSession().getAttribute("uid") == null) {
response.sendRedirect("/web/login.html");
return false;
}
return true;
}
}
2. Nouveau paquet de configuration config
LoginInterceptorConfigurer.java
import com.cy.store.interceptor.LoginInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.util.ArrayList;
import java.util.List;
/** Enregistrez L'intercepteur de processeur */
@Configuration
public class LoginInterceptorConfigurer implements WebMvcConfigurer {
/** Configuration de l'intercepteur */
@Override
public void addInterceptors(InterceptorRegistry registry) {
// Créer un objet intercepteur
HandlerInterceptor interceptor = new LoginInterceptor();
// Liste blanche
List<String> patterns = new ArrayList<>();
patterns.add("/bootstrap3/**");
patterns.add("/css/**");
patterns.add("/images/**");
patterns.add("/js/**");
patterns.add("/web/register.html");
patterns.add("/web/login.html");
patterns.add("/web/index.html");
patterns.add("/web/product.html");
patterns.add("/users/reg");
patterns.add("/users/login");
patterns.add("/districts/**");
patterns.add("/products/**");
// Ajouter un intercepteur par l'outil d'enregistrement
registry.addInterceptor(interceptor).addPathPatterns("/**").excludePathPatterns(patterns);
}
}
Filtre
1.Construire unfilterSac
LoginCheckFilter.java
import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
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;
/** * Vérifier si l'utilisateur a terminé la connexion */
@WebFilter(filterName = "loginCheckFilter",urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter implements Filter{
//Pathmatcher,Prise en charge des jokers
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、Obtenir cette demandeURI
String requestURI = request.getRequestURI();// /backend/index.html
log.info("Interception des demandes:{}",requestURI);
// Définir un chemin de requête qui n'a pas besoin d'être traité
String[] urls = new String[]{
"/employee/login",
"/employee/logout",
"/backend/**",
"/front/**",
"/common/**",
"/user/sendMsg",
"/user/login"
};
//2、 Déterminer si cette demande doit être traitée
boolean check = check(urls, requestURI);
//3、 Si ce n'est pas nécessaire ,Alors laissez passer directement
if(check){
log.info("Cette demande{}Pas besoin de traitement",requestURI);
filterChain.doFilter(request,response);
return;
}
//4-1、Déterminer l'état de connexion,Si vous êtes connecté,Alors laissez passer directement
if(request.getSession().getAttribute("employee") != null){
log.info("Utilisateur connecté,UtilisateursidPour:{}",request.getSession().getAttribute("employee"));
Long empId = (Long) request.getSession().getAttribute("employee");
BaseContext.setCurrentId(empId);
filterChain.doFilter(request,response);
return;
}
//4-2、Déterminer l'état de connexion,Si vous êtes connecté,Alors laissez passer directement
if(request.getSession().getAttribute("user") != null){
log.info("Utilisateur connecté,UtilisateursidPour:{}",request.getSession().getAttribute("user"));
Long userId = (Long) request.getSession().getAttribute("user");
BaseContext.setCurrentId(userId);
filterChain.doFilter(request,response);
return;
}
log.info("L'utilisateur n'est pas connecté");
//5、 Si vous n'êtes pas connecté, retournez les résultats non connectés , Répondre aux données de la page client par le biais du flux de sortie
response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
return;
}
/** * Correspondance des chemins, Vérifier si la mainlevée est requise pour cette demande * @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;
}
}
边栏推荐
- Addition of attention function in yolov5
- Leetcode notes: binary search simple advanced
- uniapp用uParse实现解析后台的富文本编辑器的内容及修改uParse样式
- Fast construction of neural network
- OpenCV Learning notes iii
- Opencv learning notes 3
- 1.27 pytorch learning
- Relation extraction model -- spit model
- Two ways to realize time format printing
- Intra class data member initialization of static const and static constexpr
猜你喜欢

Exploration of webots and ROS joint simulation (I): software installation

Install Anaconda + NVIDIA graphics card driver + pytorch under win10_ gpu

深度学习论文阅读目标检测篇(七)中文版:YOLOv4《Optimal Speed and Accuracy of Object Detection》

Detailed explanation of traditional image segmentation methods

Yolov5进阶之四训练自己的数据集

【MATLAB GUI】 键盘回调中按键识别符查找表

pgsql_ UDF01_ jx

Playing card image segmentation

WBC learning notes (II): practical application of WBC control

Yolov5进阶之二安装labelImg
随机推荐
OpenGL display mat image
[已解决]setOnNavigationItemSelectedListener()被弃用
Formula understanding in quadruped control
Yolov5进阶之三训练环境
yolov5进阶之零环境快速创建及测试
Install Anaconda + NVIDIA graphics card driver + pytorch under win10_ gpu
Realizing sequence annotation with transformers
力扣399【除法求值】【并查集】
1.21 study gradient descent and normal equation
Pytorch neural network
Speckle denoising method for ultrasonic image
深度学习论文阅读目标检测篇(七)中文版:YOLOv4《Optimal Speed and Accuracy of Object Detection》
在同花顺开户证券安全吗,
Text to SQL model ----irnet
Selenium builds cookies pool to bypass authentication and anti crawl login
远程工作的一些命令
Optimize quiver function in MATLAB to draw arrow diagram or vector diagram (1) -matlab development
Opencv learning notes 3
Checkerboard generation + camera calibration + stereo matching
三菱PLC若想实现以太网无线通讯,需要具备哪些条件?