Input validation is essential to prevent untrusted input of getting executed, the use of encoding libraries available can assist on enforcing strict input control. 

Java Security Libraries:

Apache Shiro: authentication, access control, authorization, session management and cryptography

Spring Security: authentication, access control.

Encoding Libraries:

OWASP ESAPI

OWASP Java Encoder Project

DOMPurify

jPurify

MentalJS

Java HTML Sanitizer

OWASP JSON Sanitizer

OWASP Java HTML Sanitizer

OWASP Java Encoder Project

Prevention:

HTML5 XSS attack vectors

DOM based XSS Prevention Cheat Sheet

Handling Untrusted JSON safely

Testing:

Jacks Codiscope

Testing Checklist