`

struts2下freemarker访问静态方法和静态变量

    博客分类:
  • HTML
阅读更多

${stack.findValue("@package.ClassName@method")}

${stack.findValue("@package.ClassName@property")}

因为 stack 是webwork结合 freemarker 后在 ftl 中可以用的,其他的还有 ${base}等等

 

struts2 freemarker当中引进java 常量java静态方法

1.首先在struts.sml中配置<constant name="struts.ognl.allowStaticMethodAccess" value="true" />

标识允许使用静态java方法。

2.在freemarker中引进java常量的方法:

假如:

Test.java

package test;

public class Test{

private String userSex=MAN;

public static final String MAN="男";

public static final String WOMAN="女";

public static String m()
{
  
   return "test";
}

public String getUserSex()
{
   return userSex;
}

public void setUserSex(String userSex)
{
   this.userSex = userSex;
}

}

 

接下来我们在freemarker中调用该类中的 静态常量 和静态方法

a.调用常量:

${stack.findValue("@com.wish.maml.freemarkerexample.model.User1@MAN")}
</br>
${stack.findValue("@com.wish.maml.freemarkerexample.model.User1@m()")}

就会出现想要的结果

 

注意:目前只是调用静态的

 

 

 

 

 

 

 

补充(静态方法的调用):

方法1:
##定义配置文件 freemarkerstatic.properties 
_Validator=com.longyou.util.Validator 
_Functions=com.longyou.util.Functions 
_EscapeUtils=com.longyou.util.EscapeUtils 
/调用代码 
${_Functions.toUpperCase("Hello")}<br> 
${_EscapeUtils.escape("狼的原野")}

方法2:
${stack.findValue("@package.ClassName@method")}
来自:http://www.zhuoda.org/lunzi/83461.html

 

 

 

 

自定义方法
${timer("yyyy-MM-dd H:mm:ss", x)}
${timer("yyyy-MM-dd ", x)}

在模板中除了可以通过对象来调用方法外(${object.methed(args)})也可以直接调用java实现的方法,java类必须实现接口TemplateMethodModel的方法exec(List args). 下面以把毫秒的时间转换成按格式输出的时间为例子
public class LongToDate implements TemplateMethodModel {
    
public TemplateModel exec(List args) throws TemplateModelException {
SimpleDateFormat mydate = new SimpleDateFormat((String) args.get(0)));
        return mydate.format(new Date(Long.parseLong((String)args.get(1)));
    }
}  
将LongToDate对象放入到数据模型中
root.put("timer", new IndexOfMethod());
ftl模板里使用
<#assign x = "123112455445">
${timer("yyyy-MM-dd H:mm:ss", x)}
${timer("yyyy-MM-dd ", x)}

输出
2001-10-12 5:21:12
2001-10-12

 

 

来自:http://203.208.37.132/search?q=cache:K-jfE3IUKvAJ:www.cnblogs.com/ynlxc/archive/2006/10/16/529974.html+freemarker+replace&cd=1&hl=zh-CN&ct=clnk&gl=cn&st_usg=ALhdy2-nnWwf9CnI8LdXVtXHOTn_-KR2Ig

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics