Explain how a Cross-Site Scripting (XSS) attack works and how you would prevent it in a modern web application.