I ran into a similar problem about a year ago. In our case, our front end developers were all familiar with JSP, and I really did not want to throw another templating engine into the mix. I wanted something that relied on the servlet container's JSP processor to generate e-mail content for me.
It's fairly straightforward:
- I had to have a JSP page in my application (you can put it in /WEB-INF if you don't want it externally accessible).
- I wrote a custom
HttpServletResponse
and ServletOutputStream
that captures content written by the servlet container and turns it into a String, and relied on RequestDispatcher.include(...)
to make a "request" to the template JSP (I also wrote a custom HttpServletRequest
to isolate the original request from mutation).
- Because this is a bit of a hack, and not the way the servlet API was intended to be used, I encapsulated all this in a utility class, so that all the client code has to do is pass in the path to the JSP template, and get back the processed content.