Create Your own Filter in JSF

You may have to restrict access to some pages of your website in JSF and redirect the user to a specific page. For example, if the user is not logged in, he can not access the admin page, and You would like to redirect him to the login page. To do so, You can create Your own filters, and guess what : it’s not tough 🙂
Let’s see some example.

First of all, You have to implements javax.servlet.Filter. So far away, just create the class, and You’ll have to define three methods : init(),  doFilter() and destroy(). So here we go :

Filter example

Once we have our filter, we have to set it up 🙂 So we do it now.
So go to your web.xml file, and first set the filter markup :
Image 4

Give a name to your filter, and indicates  the class that represents Your filter, typically the class You’ve created and which implements Filter.
And then, You have to indicates on which request this filter is applied to :
Image 5
Note that we use the same name (case sensitive) that we used in the “declaration” of our filter.

It’s done 🙂 Nothing more, nothing less. Feel free to customize this example by defining your rules of restriction 🙂
Enjoy 🙂


6 Responses to Create Your own Filter in JSF

  1. bguiz says:

    Hi Thierry, great post – I wish I had come across this several months back. I’ve written my own covering similar ground:

  2. Melinda says:

    The code section in the doFilter() is cut-off and cannot be viewed. Can you fix that on this site or make the font smaller so that it can be viewed?

    It would be appreciated. Regards.

  3. Tom says:

    Nice post, thanks

  4. Marcos Morais says:

    This post is quite simple and EXTREMELY USEFUL!!!!


  5. Florian says:

    Thanks a lot for this great post!

    Good job!

  6. Eddy says:

    Thanks for this article, was very useful for me 🙂

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: