直接从Java执行JSP [英] Execute JSP directly from Java

查看:565
本文介绍了直接从Java执行JSP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要执行JSP。但我需要直接从Java,而不使用Tomcat或任何其他servlet容器。编译JSP也是一件好事,但不是必需的。我想也许org.apache.jasper包可以做到这一点,但我找不到任何好的示例或在线教程。

I need to execute a JSP. But I need to directly from Java, without using Tomcat or any other servlet container. Compiling JSPs would be a good thing too, but not necessary. I think maybe org.apache.jasper package is good for doing this, but I can't find any good example or tutorial online.

我需要的东西:

Class compiledJSP = compileJSP(new File("helloWorld.jsp"));
String html = executeJSP(compiledJSP, httpServletRequest, httpServletResponse, ...);

html --> "Hello World, John!"

谢谢!

推荐答案

如果你需要将JSP的输出捕获为字符串,那么从内的 Servlet容器中,它是相当简单的(尽管从设计的角度来看远非理想):

1 。扩展javax.servlet.HttpServletResponseWrapper并覆盖getWriter()/ getOutputStream()方法以提供自己的缓冲版本(例如StringWriter)

2.调用RequestDisparcher的include()方法,包装原始响应你自己的。

3.抓住缓冲区的内容。

If you need to capture JSP's output as string it's reasonably straightforward (although far from ideal from the design point of view) from within Servlet Container:
1. Extend javax.servlet.HttpServletResponseWrapper and override getWriter() / getOutputStream() methods to provide your own buffered versions (e.g. StringWriter)
2. Invoke "include()" method of RequestDisparcher, wrapping original response in your own.
3. Grab buffer's content.


现在如果你需要做同样的事情外面 Servlet容器,你真的需要问自己为什么?。也许您应该使用模板引擎(FreeMarker / Velocity / StringTemplate / etc ...)而不是JSP?如果您的JSP是格式良好的XML文件并且没有使用任何Java代码插入,那么将它们转换为FreeMarker模板(FreeMarker支持自定义JSP标记库)可能相当简单,这将极大地简化您的任务。

Now if you need to do the same thing outside Servlet Container, you really need to ask yourself "why?". Perhaps you should be using a template engine (FreeMarker / Velocity / StringTemplate / etc...) instead of JSPs? If your JSPs are well-formed XML files and are not using any java code inserts it may be reasonably trivial to convert them to FreeMarker templates (FreeMarker supports custom JSP tag libraries) which would greatly simplify your task.

尽管如此,如果这是绝对的硬性要求,您最直接的选择是:

1.运行外部Servlet容器并让它处理JSP解释。您的程序将向其提交HTTP请求并捕获输出。

2.与上面相同,但您可以运行嵌入式Servlet容器(例如Jetty)。

Nevertheless, if it's an absolute hard requirement your most straightforward options are:
1. Run an external Servlet Container and let it handle JSP interpretation. Your program would submit HTTP requests to it and capture the output.
2. Same as above, but you can run embedded Servlet Container (e.g. Jetty).

如果您的JSP在构建时可用,您可以按照其他答案中的建议通过Jasper预编译它们。

If your JSPs are available at build-time you can precompile them via Jasper as suggested in other answers.

我会强烈反对尝试实现自己的servlet容器的建议 - 你将走进一个受伤的世界。

I would strongly advice against trying to implement your own servlet container - you'll be walking into a world of hurt.

这篇关于直接从Java执行JSP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆