当前位置:网站首页>Implementation code of interceptor and filter
Implementation code of interceptor and filter
2022-06-26 08:56:00 【Shuai dada's structural road】
Implementation code of interceptor and filter
Interceptor
1. Create a new one interceptor package
LoginInterceptor.java
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/** Define processor interceptors */
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. Create a new configuration package 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;
/** Register processor interceptors */
@Configuration
public class LoginInterceptorConfigurer implements WebMvcConfigurer {
/** Interceptor configuration */
@Override
public void addInterceptors(InterceptorRegistry registry) {
// Create interceptor object
HandlerInterceptor interceptor = new LoginInterceptor();
// White list
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/**");
// Add interceptors through the registration tool
registry.addInterceptor(interceptor).addPathPatterns("/**").excludePathPatterns(patterns);
}
}
filter
1. To build a filter package
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;
/** * Check whether the user has finished logging in */
@WebFilter(filterName = "loginCheckFilter",urlPatterns = "/*")
@Slf4j
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();// /backend/index.html
log.info(" Intercept request :{}",requestURI);
// Define the request path that does not need to be processed
String[] urls = new String[]{
"/employee/login",
"/employee/logout",
"/backend/**",
"/front/**",
"/common/**",
"/user/sendMsg",
"/user/login"
};
//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-1、 Determine login status , If you are logged in , Then direct release
if(request.getSession().getAttribute("employee") != null){
log.info(" User logged in , user id by :{}",request.getSession().getAttribute("employee"));
Long empId = (Long) request.getSession().getAttribute("employee");
BaseContext.setCurrentId(empId);
filterChain.doFilter(request,response);
return;
}
//4-2、 Determine login status , If you are logged in , Then direct release
if(request.getSession().getAttribute("user") != null){
log.info(" User logged in , user id by :{}",request.getSession().getAttribute("user"));
Long userId = (Long) request.getSession().getAttribute("user");
BaseContext.setCurrentId(userId);
filterChain.doFilter(request,response);
return;
}
log.info(" The user is not logged in ");
//5、 If you are not logged in, the result of not logging in will be returned , Response data to the client page through output stream
response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
return;
}
/** * Path matching , 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;
}
}
边栏推荐
- Remote centralized control of distributed sensor signals using wireless technology
- pgsql_ UDF01_ jx
- Zlib static library compilation
- 1.26 pytorch learning
- Fast construction of neural network
- Matlab function foundation (directly abandon version)
- [unity mirror] use of networkteam
- Pytorch build progression
- Yolov5进阶之一摄像头实时采集识别
- Convex optimization of quadruped
猜你喜欢

唯品会工作实践 : Json的deserialization应用

反爬之验证码识别登录 (OCR字符识别)

Opencv learning notes 3

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

Whale conference provides digital upgrade scheme for the event site

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

Relationship extraction -- casrel

基于SSM的毕业论文管理系统

爬虫 对 Get/Post 请求时遇到编码问题的解决方案

Selenium builds cookies pool to bypass authentication and anti crawl login
随机推荐
【云原生 | Kubernetes篇】深入万物基础-容器(五)
Koa_ mySQL_ Integration of TS
【IVI】15.1.2 系统稳定性优化篇(LMKD Ⅱ)PSI 压力失速信息
Exploration of webots and ROS joint simulation (I): software installation
软件工程-个人作业-提问回顾与个人总结
Analysis of Yolo series principle
Drawing with MATLAB (2) -- color ring
Corn image segmentation count_ nanyangjx
远程工作的一些命令
深度学习论文阅读目标检测篇(七)中文版:YOLOv4《Optimal Speed and Accuracy of Object Detection》
Stream analysis of hevc learning
Machine learning (Part 2)
Relation extraction model -- spit model
20220623 Adobe Illustrator入门
Machine learning (Part 1)
Record the problem yaml file contains Chinese message 'GBK' error
opencv學習筆記三
Summary of common instructions for arm assembly
Isinstance() function usage
Realizing sequence annotation with transformers