南郭之家
南郭大侠的blog ^_^

struts2与velocity接合的配置

September 9th, 2009 by Titan

搜索到好多文章在web.xml里面加入velocity的解释引擎,然后映射*.vm,这样的话struts2就没有参与到页面render的过程中来,所以是错误的方法
在struts2文档里面明确说明了它支持velocity作为模板,所以不添加任何配置的情况下,在struts.xml的转向里面写/index.vm这样的代码就可以使用velocity模板的。但是这样默认没有加入velocity-tools的支持,velocity像瘸腿了一样,好多功能实现不出来
正确的方法是在struts.xml文件头部加入下面几行

注意:”com.ssh.tzx.commons.VelocityFixedManager”是我自己写的一个VelocityManager的子类,主要是覆盖掉默认的createContext方法,因为在velocity tools 1.3以后,里面调用的getToolboxContext被去掉了,改成getToolbox就可以了。其他的地方依赖问题啥的都解除就ok,我做好的文件见附件

所以,web.xml文件里面只要加入对struts的配置就可以了,velocity会被struts自动调用

参考:进一步提升Struts2对Velocity的支持力度

附代码:

package com.ssh.tzx.commons;
import java.util.Iterator;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.util.VelocityStrutsUtil;
import org.apache.struts2.views.util.ContextUtil;
import org.apache.struts2.views.velocity.StrutsVelocityContext;
import org.apache.struts2.views.velocity.VelocityManager;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.context.Context;
import org.apache.velocity.tools.view.context.ChainedContext;
import com.opensymphony.xwork2.util.ValueStack;

public class VelocityFixedManager extends VelocityManager {

	@SuppressWarnings("unchecked")
	@Override
	public Context createContext(ValueStack stack, HttpServletRequest req,
			HttpServletResponse res) {

		VelocityContext[] chainedContexts = prepareChainedContexts(req, res, stack.getContext());
		StrutsVelocityContext context = new StrutsVelocityContext(chainedContexts, stack);
		Map standardMap = ContextUtil.getStandardContext(stack, req, res);
		for (Iterator iterator = standardMap.entrySet().iterator(); iterator.hasNext();) {
			Map.Entry entry = (Map.Entry) iterator.next();
			context.put((String) entry.getKey(), entry.getValue());
		}

		context.put(STRUTS, new VelocityStrutsUtil(getVelocityEngine(), context, stack, req, res));

		ServletContext ctx = null;
		try {
			ctx = ServletActionContext.getServletContext();
		} catch (NullPointerException npe) {
			// in case this was used outside the lifecycle of struts servlet
			//log.debug("internal toolbox context ignored");
		}

		if (toolboxManager != null && ctx != null) {
			ChainedContext chained = new ChainedContext(context, getVelocityEngine(), req, res, ctx);
			chained.setToolbox(toolboxManager.getToolbox(chained));
			return chained;
		} else {
			return context;
		}
	}
}

Posted in 技术

One Response

  1. loans

    I want to thank the blogger very much not only for this post but also for his all previous efforts. I found titan.buaaer.com to be greatly interesting. I will be coming back to titan.buaaer.com for more information.

Leave a Comment

Please note: Comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.