Serverside validation to block or restrict special / bad characters of all input fields of a web page in Java Example

 XSS (Cross-site Scripting) is one of the most common attack on web application. One of the solution for this XSS vulnerability is client and server side validation to block the special (bad) characters like < > ! {} , etc and keywords like script , xp_ , truncate , etc. As Javascript/ client side validation may be bypassed, server side validation is mandatory. So how to block bad characters for the whole web application? It is easy to write a method (in our example checkSplChrs(String str)) to check whether a field contains bad characters or not. But web application may have lot of pages and each page may have lot of input fields. So it is better to create a servlet filter class to call the above method so that each parameters in the request can be validated.

Now let us write code for servlet filter class and checkSplChrs method.

Filter Class (

Don’t forget to add the following lines in web.xml for filter class


JSPs for Input, Result and Error Page:

The below page contains two input fields that accept name and address

This below servlet  ( and result page (result.jsp) are called when all the  input fields in the input page does not contain any bad/special characters



If any input field contains bad/special character, then the below  error page is  called.

For running the application for eg. TestWeb

call the URL


server validation input

Submitting the above input page results the error page as given below because the address field in the input page contains special characters (<>)

server validation error




You may also like

Leave a Reply