gpt4 book ai didi

java - @WebFilter 排除 url 模式

转载 作者:太空狗 更新时间:2023-10-29 22:51:23 28 4
gpt4 key购买 nike

我使用过滤器检查登录用户的 URL 模式。

但是我有很多 URL 模式需要过滤。

{ "/table/*", "/user/*", "/contact/*", "/run/*", "/conf/*", ..., ..., ...}

它变得无法维护。只是排除会更简单:

{ "/", "/login", "/logout", "/register" }

我怎样才能做到这一点?

@WebFilter(urlPatterns = { "/table/*","/user/*", "/contact/*","/run/*","/conf/*"})
public class SessionTimeoutRedirect implements Filter {

protected final Logger logger = LoggerFactory.getLogger("SessionFilter");

@Override
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
if (request.getSession().getAttribute("Id") != null) {
chain.doFilter(req, res);
} else {
logger.debug("session is null:"+request.getRequestURL());
response.sendRedirect(request.getContextPath()+"/login");
}
}

@Override
public void init(FilterConfig arg0) throws ServletException {

}

@Override
public void destroy() {

}

}

最佳答案

servlet API 不支持“排除”URL 模式。

你最好的选择是只映射到 /* 并比较 HttpServletRequest#getRequestURI()针对一组允许的路径。

@WebFilter("/*")
public class LoginFilter implements Filter {

private static final Set<String> ALLOWED_PATHS = Collections.unmodifiableSet(new HashSet<>(
Arrays.asList("", "/login", "/logout", "/register")));

@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
HttpSession session = request.getSession(false);
String path = request.getRequestURI().substring(request.getContextPath().length()).replaceAll("[/]+$", "");

boolean loggedIn = (session != null && session.getAttribute("Id") != null);
boolean allowedPath = ALLOWED_PATHS.contains(path);

if (loggedIn || allowedPath) {
chain.doFilter(req, res);
}
else {
response.sendRedirect(request.getContextPath() + "/login");
}
}

// ...
}

关于java - @WebFilter 排除 url 模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31318397/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com