0

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.

Community
  • 1
  • 1
Antoine Martin
  • 1,903
  • 2
  • 16
  • 28
  • A filer also filters JSPs, HTML pages, static resources, etc. It allows using any base class for your servlets. It also allows using a single servlet (front controller) for all your requests. Why not put all the restricted resources under a specific path? – JB Nizet Mar 16 '14 at 22:33
  • I justly want to avoid to get url like www.mysite.com/restrained/emails I prefere www.mysite.com/emails instead. But I didn't think about using only one servlet. thanks – Antoine Martin Mar 17 '14 at 20:12

0 Answers0