Java 在泽西岛注册Thymeleaf Templateengine
我正在尝试将Thymeleaf模板引擎与Jersey REST服务器结合起来 我已经找到了ThymeleafViewProcessor()的示例,但我不知道如何将处理器绑定到jersey服务器Java 在泽西岛注册Thymeleaf Templateengine,java,jersey,thymeleaf,Java,Jersey,Thymeleaf,我正在尝试将Thymeleaf模板引擎与Jersey REST服务器结合起来 我已经找到了ThymeleafViewProcessor()的示例,但我不知道如何将处理器绑定到jersey服务器 @Provider public class ThymeleafViewProcessor implements ViewProcessor<String> { @Context ServletContext servletContext; @Context ThreadLo
@Provider
public class ThymeleafViewProcessor implements ViewProcessor<String> {
@Context
ServletContext servletContext;
@Context
ThreadLocal<HttpServletRequest> requestInvoker;
@Context
ThreadLocal<HttpServletResponse> responseInvoker;
TemplateEngine templateEngine;
public ThymeleafViewProcessor() {
TemplateResolver templateResolver = new ServletContextTemplateResolver();
templateResolver.setPrefix("/WEB-INF/templates/");
templateResolver.setSuffix(".html");
templateResolver.setTemplateMode("HTML5");
templateResolver.setCacheTTLMs(3600000L);
templateEngine = new TemplateEngine();
templateEngine.setTemplateResolver(templateResolver);
}
@Override
public String resolve(final String path) {
return path;
}
@Override
public void writeTo(final String resolvedPath, final Viewable viewable,
final OutputStream out) throws IOException {
// Commit the status and headers to the HttpServletResponse
out.flush();
WebContext context = new WebContext(requestInvoker.get(),
responseInvoker.get(), servletContext, requestInvoker.get().getLocale());
Map<String, Object> variables = new HashMap<>();
variables.put("it", viewable.getModel());
context.setVariables(variables);
templateEngine.process(viewable.getTemplateName(), context, responseInvoker
.get().getWriter());
}
Hello来源:
@Path("/hello")
public class HelloResource {
@GET
@Path("/{n}")
@Produces(MediaType.TEXT_HTML)
public Viewable sayHello(@PathParam("n") String name) {
return new Viewable("sample", "Hello " + name + "!");
}
@GET
@Produces(MediaType.TEXT_HTML)
public Viewable sayHello() {
return new Viewable("sample",
new SampleModel("Good morning", "my friends"));
}
public static class SampleModel {
public String greeting;
public String name;
public SampleModel(String greeting, String name) {
this.greeting = greeting;
this.name = name;
}
}
}
我现在要做什么才能将ViewProcessor绑定到Jersey。我在web上找不到任何示例,其他解决方案(freemarker)的工作方式似乎有所不同。我通过将视图处理器绑定为渴望的singleton解决了这个问题:
public class TemplateModule extends AbstractModule {
@Override
protected void configure() {
// bind thymeleaf processor as eager singleton
bind(ThymeleafViewProcessor.class).asEagerSingleton();
}
}
然后将其添加到喷油器中。这应该行得通
public class TemplateModule extends AbstractModule {
@Override
protected void configure() {
// bind thymeleaf processor as eager singleton
bind(ThymeleafViewProcessor.class).asEagerSingleton();
}
}