There may be instances where you want to modify the response before it is written to the client. In this tutorial we will show how to write a regex to append to a html element.
Detailed Video Notes
I was working on a project where we wanted to replace the contents of a html heading element. We wanted to capture the html before the response was written and use a regular expression to swap out the contents. The approach taken was to modify the response using a J2EE filters. In order to perform this operation you need to create a HttpServletResponseWrapper class and pass it in the doFilter method which overrides the getWriter or getOutputStream method. Let's see it in action.
Since spring boot makes it easy to set and run a java project, lets generate a project from the spring initializer website by selecting web and velocity as a template engine. Next we can create a template to render, a @Controller to return the view, a filter and code to register the filter. One thing to note, the filter will be registered using servlet 3.0 and spring mechanisms. In the instance you are not using spring or servlet 3.0 to register your filter, you could register it within the web.xml. In our template our use case will be to append text to html heading elements.
Let's run the results to validate our set up is working.
The wrapper is then passed to the doFilter method of the filter chain which gives us the ability to modify capture the response as a string. Next we want to modify the filter to check capture the response as a string if the contentType is HTML. If it is we will execute a regex to find all the instances of <h2> and replace them with <h3> and append the text "HTML replaced".
While this is one approach to replacing values within your template, if you see repeated pattern you may want to consider a different approach as it could lead confusion and long term maintainability issues.
Thanks for joining in today's level up, have a great day!