1

I use velocity1.6.4, velocity-tools1.4, and struts2.3.15.2

in struts.xml:

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

in 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>

the ControlUtil.java is

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;
        }
    }
}

and in index.vm I try to user the method getKeywords() in ControlUtil

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

It is don't word, the right way of System.out.println("------"); in method getKeywords() should print ,but it not

why I can't reach method getKeywords() in ControlUtil from vm file,please help me !

Roman C
  • 49,761
  • 33
  • 66
  • 176
Meng Qian
  • 97
  • 1
  • 1
  • 9

1 Answers1

0

There's no any reason to pass servlet context via parameter. You can simplify code

#set ($keyWords = $controlUtil.keywords)

But the tool should initialize servletContext property

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;
        }
    }
}
Roman C
  • 49,761
  • 33
  • 66
  • 176