Normally you put the secured pages in a common URL path, such as /app/*
, /secured/*
, /private/*
, etc. This way you can use a single entry point to control the access. If you're using container managed security, it's then a matter of specifying the proper URL pattern:
<security-constraint>
<web-resource-collection>
<web-resource-name>Restricted pages</web-resource-name>
<url-pattern>/secured/*</url-pattern>
</web-resource-collection>
<auth-constraint>
<role-name>*</role-name>
</auth-constraint>
</security-constraint>
If you are however using homegrown security, then you need to implement a Filter
for that instead:
@WebFilter("/secured/*")
public class AuthorizationFilter implements Filter {
// ...
}
or when you're still not on Servlet 3.0 yet, then register it as follows instead of using @WebFilter
:
<filter>
<filter-name>authorizationFilter</filter-name>
<filter-class>com.example.AuthorizationFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>authorizationFilter</filter-name>
<url-pattern>/secured/*</url-pattern>
</filter-mapping>
Inside the doFilter()
method you need to write code which checks if the user is logged in or not and then continues the chain or redirects the response to the login page (which is by itself of course not covered by the same URL pattern).
See also: