从Servlet输出SoyTemplates的最佳方式

时间:2013-06-11 10:38:26

标签: java servlets google-closure-templates

将大豆模板从封闭模板渲染或输出到浏览器的最佳方法是什么?

目前我有以下内容:     包de.envisia.erp.web.servlet;

import java.io.File;
import java.io.IOException;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.template.soy.SoyFileSet;

import com.google.template.soy.tofu.SoyTofu;
/**
 * Servlet implementation class EntryPoint
 */
@WebServlet("/EntryPoint")
public class EntryPoint extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
 * @see HttpServlet#HttpServlet()
 */
public EntryPoint() {
    super();
    // TODO Auto-generated constructor stub
}

/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 */
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    ServletContext servletContext = this.getServletContext();
    String pathContext = servletContext.getRealPath("/WEB-INF/");
    //response.getWriter().println(pathContext);

    SoyFileSet sfs = new SoyFileSet.Builder().add(new File(pathContext + "\\templates\\hello.soy")).build();
    SoyTofu tofu = sfs.compileToTofu();
    String out = tofu.newRenderer("hello.world").render();
    response.getWriter().println(out);
}

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    }

}

但我不认为使用响应对象的println甚至print()方法是一种好习惯,还有更好的方法吗?

1 个答案:

答案 0 :(得分:2)

看看https://github.com/codedance/silken

基本思想是创建一个特殊的servlet并将请求转发给它:

RequestDispatcher rd = getServletContext().getRequestDispatcher("/soy/products.boat.sailingBoatView");
rd.forward(req, resp);