springboot 拦截器与servlet的过滤器
// 注入spring容器
@Component
// 定义filterName 和过滤的url
@WebFilter(filterName = "my2Filter" ,urlPatterns = "/*")
public class My2Filter implements Filter {@Override
br/>@Override
}@Overridepublic void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { System.out.println("filter2");}@Overridepublic void destroy() {}
}
接下来实现一个springboot里面的拦截器的例子。
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.*;
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
@Overridepublic void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new GlobalInterceptor()).addPathPatterns("/**");}
}
import cn.vcinema.tool.security.session.SessionValidateResultEnum;
import cn.vcinema.tool.security.session.UserSessionInfo;
import cn.vcinema.tool.security.session.UserSessionUtils;
import com.pumpkin.conf.MallConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class GlobalInterceptor implements HandlerInterceptor {
private final static Logger LOGGER = LoggerFactory.getLogger(GlobalInterceptor.class);@Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { String userId = request.getHeader("user_id"); String sessionId = request.getHeader("session_id"); String deviceId = request.getHeader("device_id"); LOGGER.info("headers:user_id=" + userId + ",session_id=" + sessionId + ",device_id=" + deviceId); UserSessionInfo info = new UserSessionInfo(userId, sessionId, deviceId); SessionValidateResultEnum resultEnum = UserSessionUtils.validateSession(MallConfig.getRunMode(), info); return true;}
}
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。