Java @WebFilter 排除 url-pattern
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31318397/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
@WebFilter exclude url-pattern
提问by user2492364
I use a filter to check URL patterns for the logged in user.
我使用过滤器来检查登录用户的 URL 模式。
But I have many URL patterns I need to filter.
但是我有很多需要过滤的 URL 模式。
{ "/table/*", "/user/*", "/contact/*", "/run/*", "/conf/*", ..., ..., ...}
It's becoming unmaintainable. It will be simpler just to exclude:
它变得无法维护。仅排除以下内容会更简单:
{ "/", "/login", "/logout", "/register" }
How can I achieve this?
我怎样才能做到这一点?
@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() {
}
}
回答by BalusC
The servlet API doesn't support an "exclude" URL pattern.
servlet API 不支持“排除”URL 模式。
Your best bet is to just map on /*
and compare the HttpServletRequest#getRequestURI()
against the set of allowed paths.
最好的办法是映射/*
并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");
}
}
// ...
}
回答by nacho4d
You can use initParam
to have some excluded patterns and implement your logic. This is basically the same as BalusC'sanswer except by using initParam
it can be written in the web.xml if you want/need to.
您可以使用initParam
一些排除模式并实现您的逻辑。这与BalusC 的答案基本相同,但initParam
如果您愿意/需要,可以将其写入 web.xml 中。
Below I am ignoring some binary (jpeg jpg png pdf) extensions:
下面我忽略了一些二进制(jpeg jpg png pdf)扩展名:
@WebFilter(urlPatterns = { "/*" },
initParams = { @WebInitParam(name = "excludedExt", value = "jpeg jpg png pdf") }
)
public class GzipFilter implements Filter {
private static final Set<String> excluded;
@Override
public void init(FilterConfig filterConfig) throws ServletException {
String excludedString = filterConfig.getInitParameter("excludedExt");
if (excludedString != null) {
excluded = Collections.unmodifiableSet(
new HashSet<>(Arrays.asList(excludedString.split(" ", 0))));
} else {
excluded = Collections.<String>emptySet();
}
}
boolean isExcluded(HttpServletRequest request) {
String path = request.getRequestURI();
String extension = path.substring(path.indexOf('.', path.lastIndexOf('/')) + 1).toLowerCase();
return excluded.contains(extension);
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
System.out.print("GzipFilter");
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
if (isExcluded(httpRequest)) {
chain.doFilter(request, response);
return;
}
// Do your stuff here
}
}