One approach is to sanitize user input using libraries like OWASP Java Encoder to escape special characters, ensuring that user-provided data is treated as data, not executable code, thus preventing XSS attacks.