Following is a shame less copy and paste. Again just wanted to share what I read.
How to Protect Yourself
The primary defenses against XSS are described in the OWASP XSS Prevention Cheat Sheet.
The OWASP ESAPI project has produced a set of reusable security components in several languages, including validation and escaping routines to prevent parameter tampering and the injection of XSS attacks. In addition, the OWASP WebGoat Project training application has lessons on Cross-Site Scripting and data encoding.
And I guess you can get more ideas on the possible ways by which you can be exploited in http://ha.ckers.org/xss.html.
Hope this helps :)