Backport of pull request #540 on 2.5.x branch for [GEOS-6377]

Backported modifications from pull request https://github.com/geoserver/geoserver/pull/540.

Please look at the following JIRA https://jira.codehaus.org/browse/GEOS-6377.