我使用velocity1.6.4,velocity-tools1.4和struts2.3.15.2

struts.xml中:

<constant name="struts.velocity.toolboxlocation" value="/WEB-INF/toolbox.xml" />


toolbox.xml中:

<?xml version="1.0"?>
<toolbox>
    <tool>
        <key>date</key>
        <scope>application</scope>
        <class>
            org.apache.velocity.tools.generic.ComparisonDateTool
        </class>
        <parameter name="format" value="yyyy-MM-dd" />
        <parameter name="depth" value="2" />
        <parameter name="skip" value="month" />
    </tool>
    <tool>
        <key>controlUtil</key>
        <scope>application</scope>
        <class>com.quangao.bible.webapp.util.ControlUtil</class>
    </tool>
</toolbox>


ControlUtil.java是

public class ControlUtil {

    public static List<Keyword> getKeywords(ServletContext servletContext) {
        System.out.println("------");
        KeywordManager keywordManager = (KeywordManager) getBean(
                servletContext, "keywordManager");
        try {
            List<Keyword> value = keywordManager.getKeywords();
            System.out.println(value);
            if (value != null && value.size() > 5) {
                return value.subList(0, 5);
            } else {
                return value;
            }

        } catch (Exception e) {
            return null;
        }
    }
}


index.vm中,我尝试在getKeywords()中使用方法ControlUtil

#set($keyWords=$controlUtil.getKeywords($session.servletContext))


这不是单词,应该打印方法System.out.println("------");getKeywords()的正确方法,但不是

为什么我无法从vm文件访问getKeywords()中的ControlUtil方法,请帮帮我!

最佳答案

没有任何理由通过参数传递servlet上下文。您可以简化代码

#set ($keyWords = $controlUtil.keywords)


但是该工具应该初始化servletContext属性

public class ControlUtil {

    private ServletContext servletContext;

    public void setServletContext(ServletContext servletContext) {
       this.servletContext = servletContext;
    }

    public static List<Keyword> getKeywords() {
        System.out.println("------");
        KeywordManager keywordManager = (KeywordManager) getBean(
                servletContext, "keywordManager");
        try {
            List<Keyword> value = keywordManager.getKeywords();
            System.out.println(value);
            if (value != null && value.size() > 5) {
                return value.subList(0, 5);
            } else {
                return value;
            }

        } catch (Exception e) {
            return null;
        }
    }
}

10-06 09:04