public class forumfilter implements filter { private static final string[] unlogin_uris = {"/index.jsp", "/index.do", "/login.jsp", "/login/ Dologin.do ","/register.jsp ", "/register.do", "/ board/listboardtopics-","/board/listtopicposts-"}; public void init ( Filterconfig filterconfig) throws ServletException { } public void dofilter (servletrequest servletrequest, servletresponse Servletresponse, filterchain fiLterchain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) servletRequest; user user = getsessionuser (Request); if (User==null && !isurilogin ( Request.getrequesturi (), request) { string tourl = request.getrequesturi (); if (! Stringutils.isempty (Request.getquerystring ())) { toUrl += "?" + request.getquerystring (); } &nBsp; request.getsession (). SetAttribute (Define.LOGIN_TO_ Url,tourl); Request.getrequestdispatcher ("/login.jsp"). Forward (Servletrequest,servletresponse); return; } filterchain.dofilter ( Servletrequest,servletresponse); } } protected user getsessionuser (httpservletrequest request) { return (User) request.getsession (). getattribute ( Define.userline); } public void destroy () { } protected&nbsP;boolean isurilogin (string requesturi,httpservletrequest request) { if (Request.getcontextpath () equalsignorecase (RequestUri) | | (Request.getcontextpath () + "/"). Equalsignorecase (RequestUri)) return true; for (String uri : unlogin_uris) { if (Requesturi != null && requesturi.indexof (URI) > = 0) { return true; } } return false; }}
Implement the filter interface, overriding the Dofilter method.
Turn ServletRequest into HttpServletRequest and get the user in session.
If there is a user or access to the URL can be accessed without logging in, that has been logged in successfully, then directly dofilter ();
If it does not exist, then save the current URL to access, and then jump to the login interface, if the login succeeds and then jumps back to the URL.
Getcontextpath (): Gets the current app's root directory
In some applications, users are prompted to log in when they request a resource that must be logged on, remembering the URL of the current page that the user accesses, and then jumping back to the page that the user last visited, based on the URL that is remembered after the login is successful:
String Lastaccessurl = Request.getrequesturi () + "?" + request.getquerystring ();
This article is from the "Red Xiao" blog, please be sure to keep this source http://cnslp.blog.51cto.com/11387491/1940184
Use filter to control URL access permissions