Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 4070008
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 20, 20262026-05-20T16:34:22+00:00 2026-05-20T16:34:22+00:00

I’m hoping someone has already written this: A servlet filter that can be configured

  • 0

I’m hoping someone has already written this:

A servlet filter that can be configured with regular expression search/replace patterns and applies them to the HTML output.

Does such a thing exist?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-20T16:34:23+00:00Added an answer on May 20, 2026 at 4:34 pm

    I couldn’t find one, so I wrote one:

    RegexFilter.java

    package com.example;
    
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.util.ArrayList;
    import java.util.Enumeration;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    import java.util.regex.Pattern;
    
    import javax.servlet.Filter;
    import javax.servlet.FilterChain;
    import javax.servlet.FilterConfig;
    import javax.servlet.ServletException;
    import javax.servlet.ServletRequest;
    import javax.servlet.ServletResponse;
    import javax.servlet.http.HttpServletResponse;
    
    /**
     * Applies search and replace patterns. To initialize this filter, the
     * param-names should be "search1", "replace1", "search2", "replace2", etc.
     */
    public final class RegexFilter implements Filter {
        private List<Pattern> searchPatterns;
        private List<String> replaceStrings;
    
        /**
         * Finds the search and replace strings in the configuration file. Looks for
         * matching searchX and replaceX parameters.
         */
        public void init(FilterConfig filterConfig) {
            Map<String, String> patternMap = new HashMap<String, String>();
    
            // Walk through the parameters to find those whose names start with
            // search
            Enumeration<String> names = (Enumeration<String>) filterConfig.getInitParameterNames();
            while (names.hasMoreElements()) {
                String name = names.nextElement();
                if (name.startsWith("search")) {
                    patternMap.put(name.substring(6), filterConfig.getInitParameter(name));
                }
            }
            this.searchPatterns = new ArrayList<Pattern>(patternMap.size());
            this.replaceStrings = new ArrayList<String>(patternMap.size());
    
            // Walk through the parameters again to find the matching replace params
            names = (Enumeration<String>) filterConfig.getInitParameterNames();
            while (names.hasMoreElements()) {
                String name = names.nextElement();
                if (name.startsWith("replace")) {
                    String searchString = patternMap.get(name.substring(7));
                    if (searchString != null) {
                        this.searchPatterns.add(Pattern.compile(searchString));
                        this.replaceStrings.add(filterConfig.getInitParameter(name));
                    }
                }
            }
        }
    
        public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
            // Wrap the response in a wrapper so we can get at the text after calling the next filter
            PrintWriter out = response.getWriter();
            CharResponseWrapper wrapper = new CharResponseWrapper((HttpServletResponse) response);
            chain.doFilter(request, wrapper);
    
            // Extract the text from the completed servlet and apply the regexes
            String modifiedHtml = wrapper.toString();
            for (int i = 0; i < this.searchPatterns.size(); i++) {
                modifiedHtml = this.searchPatterns.get(i).matcher(modifiedHtml).replaceAll(this.replaceStrings.get(i));
            }
    
            // Write our modified text to the real response
            response.setContentLength(modifiedHtml.getBytes().length);
            out.write(modifiedHtml);
            out.close();
        }
    
        public void destroy() {
            this.searchPatterns = null;
            this.replaceStrings = null;
        }
    }
    

    CharResponseWrapper.java

    package com.example;
    
    import java.io.CharArrayWriter;
    import java.io.PrintWriter;
    
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpServletResponseWrapper;
    
    /**
     * Wraps the response object to capture the text written to it.
     */
    public class CharResponseWrapper extends HttpServletResponseWrapper {
        private CharArrayWriter output;
    
        public CharResponseWrapper(HttpServletResponse response) {
            super(response);
            this.output = new CharArrayWriter();
        }
    
        public String toString() {
            return output.toString();
        }
    
        public PrintWriter getWriter() {
            return new PrintWriter(output);
        }
    }
    

    Example web.xml

    <web-app>
        <filter>
          <filter-name>RegexFilter</filter-name>
          <filter-class>com.example.RegexFilter</filter-class>
          <init-param><param-name>search1</param-name><param-value><![CDATA[(<\s*a\s[^>]*)(?<=\s)target\s*=\s*(?:'_parent'|"_parent"|_parent|'_top'|"_top"|_top)]]></param-value></init-param>
          <init-param><param-name>replace1</param-name><param-value>$1</param-value></init-param>
        </filter>
        <filter-mapping>
          <filter-name>RegexFilter</filter-name>
          <url-pattern>/*</url-pattern>
        </filter-mapping>
    </web-app>
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I've got a string that has curly quotes in it. I'd like to replace
This could be a duplicate question, but I have no idea what search terms
I know there's a lot of other questions out there that deal with this
Does anyone know how can I replace this 2 symbol below from the string
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I want to count how many characters a certain string has in PHP, but
For some reason, after submitting a string like this Jack’s Spindle from a text

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.