Learn Servlet-JSP By Building A Social Network Website — Part VI

Sera Ng.
Tech Training Space
3 min readOct 28, 2020

Learn how to use the Filter technique to validate incoming requests

Task 9: Using Filter for Validation

If we take a look at the processRequest() method in the RegisterController servlet, we see the code is quite long, especially for the validation code:

In large-scale applications, the controller may perform much more business logic than the one we currently have.

In order to make our application easy to scale and maintain, we should move the validation tasks to another servlet, but not a normal one, rather a Servlet Filter.

Servlet Filters can be used to intercept requests before reaching servlets or JSP or interact with the response before reaching the web browser.

Here are some common tasks that can be achieved with Filters:

  • Authenticating and authorizing incoming requests
  • Logging request information
  • Converting images
  • Compressing data

And any things that you can think of.

Filter Model

In our case, we will use a Filter to handle validation tasks:

  • If the information is valid, the Filter forward the request to the RegisterController for further processing
  • If the information is invalid, the Filter forward to the registering page

Step 1:

Create a new package called net.learnbyproject.filters

Step 2:

In this package, create a new Java class called RegisterFormFilter with the following implementation:

Just like servlet configuration, we don’t need to add to the web.xml to have filter mapping. We can use annotation for the same result:

@WebFilter(urlPatterns = {“/register”})

That means if the request with the URL pattern /register is sent to the web application, that request will be intercepted by the filter RegisterFormFilter.

To make a Java class works as a filter, we need to implement the interface javax.servlet.Filter.

As you can see in the code, this interface requires to override the three methods:

  • init(): is called when the Filter is first started
  • doFilter(): is used to process requests or responses. This is the one we will mostly work with
  • destroy(): is invoked when the filter is destroyed

We might have as many filters in combination as a chain as we see fit.

In our case, we only need one filter for the validation tasks.

Step 3:

Move the validation code in the RegisterController in the RegisterFormFilter.doFilter() method

The input validation parts are the same as previously.

And if all the inputs are correct, we keep forwarding to the RegisterController by calling:

chain.doFilter(request, response);

And the RegisterController now is much cleaner:

If you clean and build your web application and run again, you should have the same results as before.

--

--