开发者

Retrieving JSP content from a servlet within a single web application (under Tomcat)

First of all, I wanna apologize for not so clear description of the question. Let's consider we have some working mechanism for e-mail sending, and we also have some e-mail templates mechanism based on JSP processing engine. Let's say, these templates may be directly accessed like http://localhost/app/templates/template1.jsp?k1=v1&k2=v2 and always return an HTML that can be inserted into an e-mail for a certain user in the back-end code. Simply saying, the short-hand code might look like:

Map<String, String> parameters = new HashMap<String, String>() {{ ..puts.. }};
String message = readJsp("/templates/template1.jsp", parameters); // servlet-context?
sendEMail(recipient, subject, message)

Current开发者_运维问答ly I found two solutions for implementing the readJsp method. The first approach is to make a HTTP request from the servlet to the web-server where both servlet and JSP-template are put at. Well, I'm not a fan of this...

The second and much better way that really works is getting a request dispatcher from the servlet context and invoking its include() method with the response wrapper (this work around is described here). This method works perfect, but I don't know how I can use this approach if I cannot get a HttpServletRequest and HttpServletResponse instances (let's consider my sendEMail() method can be invoked both from servlet service method [it's easy to get the HttpServletRequest/Response instances here] and a thread that runs as a part of the web application [where HttpServletRequest/Response instance are never known and even cannot be passed to the thread]). I can suggest that I can create the HttpServletRequest/HttpServletResponse instances myself in a certain way, but I don't know how and whether it will be ok for that readJsp() method based on the second approach.

So, the question is basically about, perhaps, the 3rd (and even better) way of getting the JSP content from a thread that does not belong to a servlet but runs in the same web application. Or is it possible to create valid HttpServletRequest/HttpServletResponse instances from scratch to make the second approach work out of servlet service() method?

Any ideas? Thanks in advance.


You could try using Spring's MockHttpServletRequest/Response but from what I have heard, Tomcat's ServletDispatcher.include() does not work with those.

I would recommend not using JSP in the case where you don't have access to a request/response pair. Instead use Velocity or Freemarker to template your emails.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜