让nutz支持 jetbrick-template

用简单的方式,新增个View

package com.nutz.view;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jetbrick.template.JetContext;
import jetbrick.template.JetTemplate;
import jetbrick.template.utils.ExceptionUtils;
import jetbrick.template.web.JetWebContext;
import jetbrick.template.web.JetWebEngineLoader;

import org.nutz.lang.Files;
import org.nutz.lang.Strings;
import org.nutz.mvc.Mvcs;
import org.nutz.mvc.view.AbstractPathView;

/**
 * jetbrick-template View
 * 
 * @author zwt([email protected])
 *
 */
public class JetView extends AbstractPathView {

	public JetView(String name){
		super(name);
	}
	
	@Override
	public void render(HttpServletRequest request, HttpServletResponse response,
			Object obj) throws Throwable {
	     String path = evalPath(request, obj);
	        String args = "";
	        if (path != null && path.contains("?")) { //将参数部分分解出来
	            args = path.substring(path.indexOf('?'));
	            path = path.substring(0, path.indexOf('?'));
	        }

	        String ext = getExt();        
	        // 空路径,采用默认规则
	        if (Strings.isBlank(path)) {
	            path = Mvcs.getRequestPath(request);
	            path = "/WEB-INF"
	                    + (path.startsWith("/") ? "" : "/")
	                    + Files.renameSuffix(path, ext);
	        }
	        // 绝对路径 : 以 '/' 开头的路径不增加 '/WEB-INF'
	        else if (path.charAt(0) == '/') {
	            if (!path.toLowerCase().endsWith(ext))
	                path += ext;
	        }
	        // 包名形式的路径
	        else {
	            path = "/WEB-INF/" + path.replace('.', '/') + ext;
	        }
	        request.setAttribute("ctx",request.getContextPath());
	        // 执行 Jet模板
	        path = path + args;
		if (JetWebEngineLoader.unavailable()) {
            JetWebEngineLoader.setServletContext(request.getSession().getServletContext());
        }
        JetContext context = new JetWebContext(request, response);
        JetTemplate template = JetWebEngineLoader.getJetEngine().getTemplate(path);
        try {
            template.render(context, response.getOutputStream());
        } catch (IOException e) {
            throw ExceptionUtils.uncheck(e);
        }
		
	}
	
	/**
     * 子类可以覆盖这个方法,给出自己特殊的后缀,必须小写哦
     * 
     * @return 后缀
     */
    protected String getExt() {
        return ".html";
    }

}



使用方法跟jsp一样,后缀自己可以修改

@At("/index")
public Object index() {
	return new JetView("pages/main/index");
}




你可能感兴趣的:(让nutz支持 jetbrick-template)