java - @WebFilter exclude url-pattern -
i use filter check url patterns logged in user.
but have many url patterns need filter.
{ "/table/*", "/user/*", "/contact/*", "/run/*", "/conf/*", ..., ..., ...}
it's becoming unmaintainable. simpler exclude:
{ "/", "/login", "/logout", "/register" }
how can 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 null:"+request.getrequesturl()); response.sendredirect(request.getcontextpath()+"/login"); } } @override public void init(filterconfig arg0) throws servletexception { } @override public void destroy() { } }
the servlet api doesn't support "exclude" url pattern.
your best bet map on /*
, compare httpservletrequest#getrequesturi()
against set of allowed paths.
@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"); } } // ... }
Comments
Post a Comment