Servlet vs Filter

JavaServletsServlet Filters

Java Problem Overview

What is the difference between a Servlet and Filter? What do you recommend to use for authorization to pages?

Java Solutions

Solution 1 - Java

Use a Filter when you want to filter and/or modify requests based on specific conditions. Use a Servlet when you want to control, preprocess and/or postprocess requests.

The Java EE tutorial mentions the following about filters:

> A filter is an object that can transform the header and content (or both) of a request or response. Filters differ from web components in that filters usually do not themselves create a response. Instead, a filter provides functionality that can be “attached” to any kind of web resource. Consequently, a filter should not have any dependencies on a web resource for which it is acting as a filter; this way it can be composed with more than one type of web resource. > > The main tasks that a filter can perform are as follows: > > * Query the request and act accordingly. > * Block the request-and-response pair from passing any further. > * Modify the request headers and data. You do this by providing a customized version of the request. > * Modify the response headers and data. You do this by providing a customized version of the response. > * Interact with external resources.

For authorization, a Filter is the best suited. Here's a basic kickoff example of how a filter checks requests for the logged-in user:

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);

Solution 2 - Java

Filters are best suited for authorization. This is because they can be configured to run for all pages of a site. So you only need one filter to protect all your pages.

Solution 3 - Java

Using filter we can improve servlet performance-- when request comes we can perform preprocessing on request, if request satisfies then we can forward to servlet otherwise give message to client provide appropriate information in request..


All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDejellView Question on Stackoverflow
Solution 1 - JavaBalusCView Answer on Stackoverflow
Solution 2 - JavakgiannakakisView Answer on Stackoverflow
Solution 3 - JavaNavnath AdsulView Answer on Stackoverflow