当前位置:网站首页>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;
}
}
边栏推荐
- Record the problem yaml file contains Chinese message 'GBK' error
- Summary of mobile terminal lightweight model data
- Clion installation + MinGW configuration + opencv installation
- MPC learning notes (I): push MPC formula manually
- Analysis of Yolo series principle
- 关于极客时间 | MySQL实战45讲的部分总结
- Trimming_ nanyangjx
- Intra class data member initialization of static const and static constexpr
- Euler function: find the number of numbers less than or equal to N and coprime with n
- 隐藏式列表菜单以及窗口转换在Selenium 中的应用
猜你喜欢

Stream analysis of hevc learning

Trimming_ nanyangjx

Exploration of webots and ROS joint simulation (II): model import

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

三菱PLC若想实现以太网无线通讯,需要具备哪些条件?

Bezier curve learning

Principle of playing card image segmentation

【云原生 | Kubernetes篇】深入万物基础-容器(五)

框架跳转导致定位失败的解决方法

Whale conference provides digital upgrade scheme for the event site
随机推荐
在同花顺开户证券安全吗,
SRv6----IS-IS扩展
FFmpeg音视频播放器实现
Slider verification - personal test (JD)
Leetcode notes: binary search simple advanced
opencv學習筆記三
Simulation of parallel structure using webots
Corn image segmentation count_ nanyangjx
隐藏式列表菜单以及窗口转换在Selenium 中的应用
Segmentation of structured light images using segmentation network
关于极客时间 | MySQL实战45讲的部分总结
Line detection_ nanyangjx
Torch model to tensorflow
Opencv learning notes 3
基于SSM的毕业论文管理系统
Yolov5进阶之一摄像头实时采集识别
Using transformers of hugging face to realize text classification
Yolov5进阶之五GPU环境搭建
The solution of positioning failure caused by framework jump
Convert verification code image to tfrecord file