Sanitize your Spring MVC controller


Here’s a quick and easy way to protect all the strings coming in to your controller.  It’s simple, fool proof, and works for query strings and forms.  I can’t guarantee that it’ll protect from all attacks, but it’s easy to keep your strings squeaky clean!

The idea is to bind a PropertyEditor for all the incoming strings.  The InitBinder facility is normally used to convert incoming strings into custom classes.  My hero Mkyong has a good example of this in his post: MVC Form Handling Annotation Example.   The difference is we are going to use a WebDataBinder for cleaning up strings.

The other part that makes this work is the @ControllerAdvice annotation.  This allows us to inject an InitBinder function in all the controllers.  You can add this class inside a single controller or you can specify the controller class as a parameter in @ControllerAdvice.  But for this super cool trick, we’ll leave off the parameters and get every string coming into every controller!

I assume you’re using Spring MVC and have annotations enabled.  Now just add this class to your project.  If all your Spring controllers are in a single package, just drop this in the package and enjoy.  Spring initialization will find this while it is doing a component scan.

It’s almost freaky how well this works.  Every string object coming into your app will go through this code.  The Jsoup cleaner will remove tags like <script>, <div>, etc.  It also removes everything inside those tags.  For example,


That string could come in on a GET query string or a POST form item.  Doesn’t matter they all go thru our CleanStringAdvice class.

Here’s some ideas for fine tuning.

  • @ControllerAdvice allows you so specify exactly what controller classes or packages to apply to.
  • I used Jsoup.clean function and simpleText().  This allows people to use a few benign tags like <b>.  Jsoup has a variety of WhiteList cleaners to choose from.
  • If you want even better scrubbing, you can sanitize your strings with the OWASP library.



About Author


Steve works with successful software startups and tech companies throughout Silicon Valley. Most recently he has been developing content migration tools for large websites. He has a deep passion for all things software engineering, from design concepts, to team management, to final delivery.

1 Comment

  1. My answer to you is don’t try to. MVC provides structure. Build your application around this foundation but don’t expect it to fit perfectly. There will be deviations, it’s normal. Just watch to keep them under control.