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

查看:26
本文介绍了直接从 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/等...)而不是 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 Container 并让它处理 JSP 解释.您的程序将向其提交 HTTP 请求并捕获输出.
2. 同上,但您可以运行嵌入式 Servlet Container(例如 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天全站免登陆