【发布时间】:2019-12-15 11:44:48
【问题描述】:
我正在尝试在休息控制器的响应标头中发送会话 ID,但 excludepathpattern() 似乎不起作用
** 配置类未触发 **
我尝试过更改 sevlet 版本,但没有成功
上下文监听器
@Override
public void contextInitialized(ServletContextEvent sce) {
ServletContext context = sce.getServletContext();
Map<String, HttpSession> map = new HashMap<>();
context.setAttribute("activeUsers", map);
HttpSessionListener
ServletContext context = session.getServletContext();
Map<String, HttpSession> activeUsers = (Map<String, HttpSession>) context.getAttribute("activeUsers");
activeUsers.put(session.getId(), session);
处理程序拦截器
ServletContext context = request.getServletContext();
Map<String, HttpSession> activeUsers = (Map<String, HttpSession>) context.getAttribute("activeUsers");
String sessionId = request.getHeader("sessionId");
String requestUrl = request.getRequestURL().toString();
if (requestUrl.contains("/getOtp") || requestUrl.contains("/validateOtp")) {
return true;
} else {
if (activeUsers.containsKey(sessionId)) {
return true;
} else {
response.setStatus(401);
return false;
}
}
通过扩展 websecurityconfigure 进行拦截器配置
@Configuration
@EnableAutoConfiguration
public class SessionInterceptorConfig implements WebMvcConfigurer {
@Autowired
private SessionHanlderInterceptor sessionHandlerIntercepto;
@Override
public void addInterceptors(InterceptorRegistry registry) {
// List<String> paths = new ArrayList<String>();
// paths.add("/auth/*");
registry.addInterceptor(sessionHandlerIntercepto).excludePathPatterns("/auth/**");
}
@Bean
public ServletListenerRegistrationBean<CustomSessionListener> filterRegistrationBean() {
ServletListenerRegistrationBean<CustomSessionListener> registrationBean = new ServletListenerRegistrationBean<CustomSessionListener>();
CustomSessionListener customURLFilter = new CustomSessionListener();
registrationBean.setListener(customURLFilter);
registrationBean.setOrder(1); // set precedence
return registrationBean;
}
@Bean
public ServletListenerRegistrationBean<CustomServletContextListener> filterContextRregistration() {
ServletListenerRegistrationBean<CustomServletContextListener> registrationBean = new ServletListenerRegistrationBean<CustomServletContextListener>();
CustomServletContextListener customURLFilter = new CustomServletContextListener();
registrationBean.setListener(customURLFilter);
registrationBean.setOrder(1); // set precedence
return registrationBean;
}
Sprintboot 主类
@SpringBootApplication
public class CustomerApplication extends SpringBootServletInitializer {
我希望将会话 ID 添加到标头作为响应并检查请求中的会话 ID
【问题讨论】:
-
你为什么不直接使用过滤器,它更容易baeldung.com/spring-boot-add-filter
-
是的。我也使用过滤器来丰富自定义标头的响应。你的实现是什么样子的
-
请不要写“那也不行”。如果您需要帮助,请解释为什么它不起作用,以便我们提供帮助。如果您只是说“它不起作用”,您认为有人可以帮助您吗?
-
ohhh 感谢您对注册过滤器问题的响应,我尝试注册它并尝试调试相同但在配置类中设置断点但调试器从未将控制器带到该配置类
标签: spring-boot servlet-filters spring-rest servlet-listeners