Sorry if this is a duplicated question (at least I haven't found it yet). I found a question which answer is well covered in the tag info example (it includes a good explanation as well). I just pointed out this but do not know how to vote it to close including the link since it can't be considered as duplicate question.
Question in fact: How do you create a simple user validation java filter?
Tag info which resolves the problem: http://stackoverflow.com/tags/servlet-filters/info (to be precise, this is covered in the Hello world example).