By reading this answer, I noted that the given exemple :
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
if (((HttpServletRequest) request).getSession().getAttribute("user") == null) {
// User is not logged in. Redirect to login page.
((HttpServletResponse) response).sendRedirect("login");
} else {
// User is logged in. Just continue with request.
chain.doFilter(request, response);
}
}
make us having to write in web.xml something like :
<filter>
<filter-name>RestrictionFilter</filter-name>
<filter-class>com.myproject.filters.RestrictionFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>RestrictionFilter</filter-name>
<url-pattern>/restrained/*</url-pattern>
</filter-mapping>
But I want to be totally free to choose which url have to be restrained to loged members (it's a bit annoying to specify, for each url-pattern, the filter which have to be activated).
I used to create a Servlet who inherits HttpServlet and surcharges service() in order to check if the session contains a member instance, and then, calls the "true" service() method :
public abstract class MembreHttpServletProjet1 extends HttpServlet{
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
if(req.getSession().getAttribute("membre") == null){
resp.sendRedirect(req.getContextPath() + "/accueil");
return;
}
super.service(req, resp);
}
}
By this way, if a servlet needs to be used only if the user is loged as a member, I make inherit this servlet by MembreHttpServletProjet1.
Is this way wrong ? I understood the utility of filters in some case but I still confused for this exemple. Thank you.