【发布时间】:2012-03-12 14:20:27
【问题描述】:
我正在开发一个基于 jersey 和 freemarker 的小工具,这将使设计人员能够使用一些 mok 对象在本地测试 freemarker 模板。
很抱歉在这里写信,但是除了一些代码和 javadocs 之外,我找不到任何关于它的文档。
为此,我做了以下操作:
1 依赖:
<dependency>
<groupId>com.sun.jersey.contribs</groupId>
<artifactId>jersey-freemarker</artifactId>
<version>1.9</version>
</dependency>
2 开始 grizzly,告诉哪里可以找到 freemarker 模板:
protected static HttpServer startServer() throws IOException {
System.out.println("Starting grizzly...");
Map<String, Object> params = new HashMap<String, Object>();
params.put("com.sun.jersey.freemarker.templateBasePath", "/");
ResourceConfig rc = new PackagesResourceConfig("resource.package");
rc.setPropertiesAndFeatures(params);
HttpServer server = GrizzlyServerFactory.createHttpServer(BASE_URI, rc);
server.getServerConfiguration().addHttpHandler(
new StaticHttpHandler("/libs"), "/libs");
return server;
}
3 创建根资源并绑定freemarker文件:
@Context ResourceConfig resourceConfig;
@Path("{path: ([^\\s]+(\\.(?i)(ftl))$)}")
public Viewable renderFtl (@PathParam("path") String path) throws IOException {
Viewable view = new Viewable("/"+path);
return view;
}
一切正常,除了 freemarker 文件没有被渲染。我有一个空白页面,但是文件存在并且调试器在 renderFtl 方法中正确输入。
你知道我该怎么做吗?
我在这里和网络上阅读了很多文章,但只是旧帖子或谈论 Spring 集成的文章,我不想集成它,因为我不需要它。
我真的很喜欢 Jersey,我认为它是 Java 世界中最完整和最强大的框架之一,但是每当我尝试查找有关特定功能或贡献库的文档时,我都迷失了......无法从群组论坛中逃脱:)
我在哪里可以找到有关它的完整文档?
戴了很多坦克
更新:
试图解决我明白我不能使用内置的球衣支持,因为它需要使用放置在资源树中的文件。所以我所做的是构建freemarker配置,现在在测试中,直接@runtime并返回一个StreamingOutput对象:
@Path("{path: ([^\\s]+(\\.(?i)(ftl))$)}")
public StreamingOutput renderFtl (@PathParam("path") String path) throws Exception {
Configuration cfg = new Configuration();
// Specify the data source where the template files come from.
// Here I set a file directory for it:
cfg.setDirectoryForTemplateLoading(new File("."));
// Create the root hash
Map<String, Object> root = new HashMap<String, Object>();
Template temp = cfg.getTemplate(path);
return new FTLOutput(root, temp);
}
FTLOutput 在这里:
这不是一个好的代码,但仅用于测试......
class FTLOutput implements StreamingOutput {
private Object root;
private Template t;
public FTLOutput(Object root, Template t) {
this.root = root;
this.t = t;
}
@Override
public void write(OutputStream output) throws IOException {
Writer writer = new OutputStreamWriter(output);
try {
t.process(root, writer);
writer.flush();
} catch (TemplateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
我在调试时没有错误证据,freemarker 告诉我模板已找到并呈现,但球衣仍然没有给我结果...
我真的不知道为什么!
【问题讨论】:
-
# 发现错误我忘记了这里的@GET注解` @GET @Path("{path: ([^\\s]+(\\.(?i)(ftl))$) }") public StreamingOutput renderFtl (@PathParam("path") String path) throws Exception {...}`
-
如果您的目标是使用 Freemarker 作为 UI,我建议您查看 sparkjava.com,它是一个非常简单的框架,不需要服务器或配置。
标签: jersey freemarker