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:
...
Prevention:
DOM based XSS Prevention Cheat Sheet
Handling Untrusted JSON safely