<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>用freemarker做模板创建一个struts2自定义标签</title>
<meta name="Generator" content="EditPlus">
<meta name="Author" content="">
<meta name="Keywords" content="">
<meta name="Description" content="">
</head>
<body>
首先,在web项目的页面根目录下建立目录template
然后创建目录simple和xhtml,以上的目录名是struts2缺省使用的,不同的主题使用相应的目录。然后再创建一个components目录,在这个目录下,创建一个property.ftl。 最后的目录结构如下:
template/simple/components/property.ftl
template/xhtml/components/property.ftl
然后在property.ftl中可以使用FreeMarker来定义新的模板(FreeMarker的具体语法可以查看FreeMarker的官方网站,相当的详细易懂):
<#include "/${parameters.templateDir}/${parameters.theme}/controlheader.ftl" />
<@s.if test="${parameters.value} == null || ${parameters.value} == '' "> </@s.if>
<@s.else><@s.property value="${parameters.value}" /></@s.else>
<#include "/${parameters.templateDir}/xhtml/controlfooter.ftl" />
以上是一个我自定义的模板,检测结果是否为空字符串,如果是空的话,就输出一个 这样在输出结果时表格的边框线就是完整的了。
定义好之后,在jsp页面中就可以这样使用了:
<s:component template="/components/property.ftl" theme="simple">
<s:param name="value" value="%{'bookName'}"/>
</s:component>
第一行中的目录名从自components开始,struts2会自动在template目录下去寻找,如是主题是simple, 就在simple目录下找。
另外,param的语法要注意一下,%{}里面需要加一对引号
FreeMarker的一些使用心得和技巧
1. TagLib的运用(Spring Security)
在web.xml中添加:
<servlet>
<servlet-name>JSPSupportServlet</servlet-name>
<servlet-class>org.apache.struts2.views.JspSupportServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
在页面的最上面添加<#assign security=JspTaglibs["http://www.springframework.org/security/tags"] />
使用的时候:
<@security.authorize ifAnyGranted="ROLE_USER,ROLE_ADMIN">
Hello
</@security.authorize>
注意中间用的是句号,而不再是冒号,我一开始在这里没注意,花了不少时间解决这个问题
2. Context Path的取得
在Google中搜了一下,有人提问题,但是没有得到解决,后来查资料才知道应该是这样写的:
${request.contextPath}
3. 字符串的比较
字符串不能直接比较大小,我原来两个日期字符串的比较就需要先转换成日期型
<#if dateString1?date("yyyy-MM-dd HH:mm:ss") < dateString2?date("yyyy-MM-dd HH:mm:ss")>
日期小
</#if>
4. <#if><#else>
在if比较时小于号可以直接使用,但是大于号不行,要写成
<#if a > b>
</#if>
</body>
</html>