I want to create a jsp login filter.
The filter should:
- intercept requests to any page; verify whether the request is part of a logged-session
- if the session is not logged, redirect the client to a login page
- if the requested page is the login page, don't red开发者_开发百科irect, otherwise it will loop
thanks in advance
The filter's implementation scheme is outlined (no code; I'm assuming that you know that Servlet API, which is a prerequisite).
intercept requests to any page; verify whether the request is part of a logged-session
You ought to be creating the servlet filter, and map it against /*
, so that all requests to the application will be intercepted by this filter. Tracking of authenticated users is assumed to be done using a Session attribute. You can extract the session from the HttpServletRequest
object within the filter, and extract the attribute using the getAttribute()
method.
if the session is not logged, redirect the client to a login page
If the session or the attribute does not exist, or the attribute is false, then you'll need to redirect the user to the login page, using the sendRedirect()
method on the HttpServletResponse object.
if the requested page is the login page, don't redirect, otherwise it will loop
You can determine whether the request is to the login page using the getServletPath() method on the HttpServletRequest object. But this is unnecessary if you do the following:
- put the login page and other "public" content in the document root directory, i.e. in the
/ApplicationContext/
directory*. - put the protected content (including all servlet mappings) in the
/ApplicationContext/protected
directory. - Map the filter only to
/protected
instead of/*
. The filter will therefore intercept requests only to protected resources. Be careful when you map any resource to a different path.
* The ApplicationContext is your application's context path. If your web site is at http://example.com/App
then the context is usually App
. Your login page should therefore be http://example.com/App/login.jsp
, while a protected page would be accessed as http://example.com/App/protected/secret.jsp
Put the restricted pages in a specific folder, e.g. /secured
, /app
, /private
, /admin
, etc and map the filter (or the container managed security constraint) on an URL pattern which covers exactly that folder, e.g. /secured/*
, /app/*
, /private/*
, /admin/*
etc. Finally just put the login page outside that folder.
In our servlet filter wiki page you can find a code example which covers exactly this case.
精彩评论