0

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

目前我有以下内容: package 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() 方法不是一个好习惯,有没有更好的方法?

4

1 回答 1

2

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

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

RequestDispatcher rd = getServletContext().getRequestDispatcher("/soy/products.boat.sailingBoatView");
rd.forward(req, resp);
于 2013-06-28T18:36:36.007 回答