I have a simple web application in which I make a call to a Java servlet using ajax from a jsp page (via post). In the servlet I take data from the database and formulate a JSON and retreive in the jsp page . I then use eval function to parse the JSON and display the data in the division using the innerHTML property. Somehow, this approach seems to be vulnerable to XSS attacks. Can someone provide some pointers on how XSS attack can be prevented in this use case?
This sounds like DOM Based XSS. There are a few ways of preventing DOM Based XSS. Either you have to html encode the data on the server or the client. HTML encoding data in the database should always be avoided because it changes the value of the data and will affect how the data is sorted, ect. XSS is an output problem so it should be solved by the code that is building the HTML, which in your case is JavaScript.