Package com.filter;
Import java.io.ioexception;
Import Javax.servlet.filter;
Import Javax.servlet.filterchain;
Import Javax.servlet.filterconfig;
Import javax.servlet.servletexception;
Import Javax.servlet.servletrequest;
Import Javax.servlet.servletresponse;
Import Javax.servlet.http.httpservletrequest;
Import Javax.servlet.http.httpservletresponse;
Import javax.servlet.http.httpsession;
Public class AuthFilter implements filter {
public static final String login_page = "/login.jsp";
public static final String logout_page = "/administrator/public/logout.jsp";
public static final string[] Except_page = {"logincheck.jsp"};
public void Destroy () {
}
public void Dofilter (ServletRequest servletrequest, Servletresponse servletresponse,
Filterchain Filterchain) throws IOException, Servletexception {
HttpServletRequest request = (httpservletrequest) servletrequest;
/**
* If HTTP requests are processed and you need access to servletrequest such as GetHeader or getcookies
* methods that cannot be obtained, the request object must be constructed into a httpservletrequest
*/
HttpServletResponse response = (httpservletresponse) servletresponse;
String currenturl = Request.getrequesturi (); Obtain the absolute path for the root directory:
HttpSession session = Request.getsession (false);
boolean bool = false;
for (int i = 0; i< except_page.length; i++) {
if (Currenturl.indexof (Except_page[i]) >=0) {
BOOL = true;
Break
}
}
if (Currenturl.indexof (login_page) = =-1 && currenturl.indexof (logout_page) = =-1 && currenturl.indexof (". JSP") >-1 &&!bool) {
Determines whether the current page is a redirect after the login page, if it is not to do the session of judgment, to prevent the death of the loop
String ref = Request.getheader ("Referer"); Is the address entered directly from the address bar?
if (session = = NULL | | Session.getattribute ("username") = = NULL | | Session.getattribute ("username"). Equals ("") | | (ref==null) | | (Ref.equals (""))) {
Response.sendredirect (Request.getcontextpath ()
+ logout_page);
Return
}
}
Join the filter chain to continue execution down
Filterchain.dofilter (request, response);
}
public void init (Filterconfig arg0) throws Servletexception {
}
}
-------------------------------------------------------------------------------------------------------
The following settings are set in Web. xml:
<!--login Check Begin--
<filter>
<filter-name>authfilter</filter-name>
<filter-class>com.filter.authfilter</filter-class>
</filter>
<filter-mapping>
<filter-name>authfilter</filter-name>
<url-pattern>/administrator/*</url-pattern>
</filter-mapping>
<!--login Check end-->