Web application security is a critical issue. Security concerns are often scattered through different parts of the system. Aspect oriented programming is a programming paradigm that provides explicit mechanisms to modularize these concerns. In this paper we present a technique for detecting and preventing common attacks in web applications like Cross Site Scripting (XSS) and SQL Injection using an aspect oriented approach by analyzing and validating user input strings. We use an aspect to capture input strings and compare them to predefined patterns. The intrusion detection aspect is implemented in AspectJ and is woven into the target system. The resulting system has the ability to detect malicious user input and prevent SQL Injection and Cross Site Scripting. We present an experimental evaluation by applying it to an insecure web application. The results of our tests show that our technique was able to detect all the attempted attacks without generating any false positives.