title: Globally rewrite outbound links in a Thymeleaf / Spring MVC / Tomcat stack?
body: <p>I need to globally rewrite all links to CSS / JS / Images, adding a prefix which will depend on deployment details and is the same across the entire application.</p>
  
  <p>There are hundreds of links on dozen of source HTML templates so modifying at the source (as suggested <a href="https://stackoverflow.com/questions/3197624/servlets-development-and-a-cdn-for-static-files">here</a> for a similar problem) is too error-prone and unsightly.</p>
  
  <p>So I would like to do this programmatically, parsing the outbound HTML, and dynamically replacing each link before the HTML is returned out of the server.</p>
  
  <p>Where to do it?</p>
  
  <ul>
  <li>In Thymeleaf can I intercept the DOM and modify it before it is serialized to HTML?</li>
  <li>In Spring MVC can I capture the view output (HTML), parse it, and re-serialize it?</li>
  <li>Should I stay "close to the wire" and write a ServletFilter?</li>
  <li>Or is it better to write a Tomcat Valve? </li>
  <li>How about stepping out of the JVM altogether and have Apache mod_proxy added in front of tomcat just to parse and rewrite?</li>
  </ul>
  
  <p>My initial hunch is that the best place to do it would be Thymeleaf, where there is more context available and it avoids an additional parse/serialize. Why generate wrong data in one layer to have it patched in another, when you could just generate the right data at the outset? Unfortunately the Thymeleaf maintainers don't agree, according to this <a href="https://github.com/thymeleaf/thymeleaf/issues/247" rel="nofollow noreferrer">closed Issue</a>.</p>
  
  <p>I also have this uneasy feeling that I might be reinventing the wheel. Isn't there a generic config option I can set somewhere in one of these layers?</p>
  
  <p>So, to re-state the question objectively, what is the simplest solution - with the fewest lines of code written, and least number of files touched - to globally rewrite all CSS/JS/IMG links in a web application at run-time based on an application-specific algorithm?</p>