Preventing XSS attacks in a Spring MVC application controller One of the URL in my application is vulnerable to XSS attack, so I am handling it in the below way.

I created a util class:

import java.util.regex.Pattern;

public class HtmlUtils {
    public final static String tagStart = "\\&lt;\\w+((\\s+\\w+(\\s*\\=\\s*(?:\".*?\"|'.*?'|[^'\"\\&gt;\\s]+))?)+\\s*|\\s*)\\&gt;";

    public final static String tagEnd = "\\&lt;/\\w+\\&gt;";

    public final static String tagSelfClosing = "\\&lt;\\w+((\\s+\\w+(\\s*\\=\\s*(?:\".*?\"|'.*?'|[^'\"\\&gt;\\s]+))?)+\\s*|\\s*)/\\&gt;";

    public final static String htmlEntity = "&amp;[a-zA-Z][a-zA-Z0-9]+;";

    public final static Pattern htmlPattern = Pattern.compile("(" + tagStart + ".*" + tagEnd + ")|(" + tagSelfClosing
            + ")|(" + htmlEntity + ")", Pattern.DOTALL);

    public static boolean isHtml(String s) {
        boolean ret = false;
        if (s != null) {
            ret = htmlPattern.matcher(s).find();
        }
        return ret;
    }
}


And in the controller, I am throwing an exception if the requested value has an HTML script:

def isValidRequest(request){
    def htmlRequest = false
    def params = request.getParameterNames(); 

    while(params.hasMoreElements()){
      String paramName = (String)params.nextElement();
      def value = request.getParameter(paramName);
       htmlRequest = HtmlUtils.isHtml(value);
         if(BooleanUtils.isTrue(htmlRequest))
          break;        
      }

  if(BooleanUtils.isTrue(htmlRequest))
      throw new AccessDeniedException("Access Denied");
}


Does this look good or is there a better way to handle the XSS attack in the controller?
Don't use RegEx to prevent XSS attacks!
Why?

Regex is not a tool that can be used to correctly parse HTML.

There are much better ways to prevent XSS attacks.


An example, using your code, modified to use Spring HtmlUtils.
Please note that I changed names s to input and ret to isHtml, as these names indicate what the variable is intended for, rather than just what kind it is.
import org.springframework.web.util.HtmlUtils;

public class HtmlUtils {
    /**
     * Verify if a string contains any HTML characters by comparing its
     * HTML-escaped version with the original.
     * @param String input  the input String
     * @return boolean  True if the String contains HTML characters
     */
    public static boolean isHtml(String input) {
        boolean isHtml = false;
        if (input != null) {
            if (!input.equals(HtmlUtils.htmlEscape(input))) {
                isHtml = true;
            }
        }
        return isHtml;
    }
}

I'm sure there are other things to say about your code, but this is very important.
There is much more to truly preventing XSS attacks, depending on how critical your use case is. This page has a tremendous amount of useful information you may want to consider: XSS (Cross Site Scripting) Prevention Cheat Sheet