After the user sends the request, the server-side filter will remove all malicious characters from the parameter, avoiding cross-site script execution on client side and thereby sending a secured response to the client.

Filters are processed based on the declared order in their deployment descriptors. So, to declare a filter for the current example, you would place the following filter (crossSite) on top of all other filters in the deployment descriptor (web.xml) of web application.

A Custom Filter

The custom filter in Listing 1 will remove the untrusted characters from requests and cookies using the HttpServletRequestWrapper class, which is used to wrap the user's request (wrapped request object). Based upon the user's request to get the parameters or cookies, this wrapped request object removes the unsafe characters from the request and returns the response to the client. The wrapped request contains the trusted character for further processing.

Server-Side Protection: Implementing the Filter

The following steps implement the server-side filter in your web application.

Add the compiled RequestFilter class in the WEB-INF/classes folder of the web application.

Add the filter declaration in the deployment descriptor (web.xml).

With the techniques you have learned here (client-side validation and server-side filtering), you are ready to combat cross-site scripting in your Java-based web applications.

About the Authors

Sivakumar Kuppusamy is a product technical lead with product incubation engineering at Infosys, involved in the design and development of Java EE applications.

Ramasubramanian Thiyagarajan is a technology analyst with product incubation engineering at Infosys, involved in the design and development of Java EE applications.

Vijayasaradhi Paramakusum is a technology lead with product incubation engineering at Infosys, involved in the design and development of Java EE applications.