FreemakerS 成jsp

Freemarker官方网址:http://freemarker.sourceforge.net/index.html


1.新建项目FreemakerS ,将freemaker.jar 拷入lib下

2.新建包:com.shiryu.jspexample

包内新建Hello.java:

package com.shiryu.jspexample;

public class Hello {
private static String[] arr = { "a", "b", "c", "d" };
private String theString = "Hello from " + toString();

//get方法是必须的
public String getTheString() {
return theString;
}

public void setTheString(String theString) {
this.theString = theString;
}

public String[] getArr() {
return arr;
}
}

3.将下载包中的fmtag.tld,web.xml拷入WEB-INF目录下:
web.xml:
<?xml version="1.0" encoding="utf-8"?>

<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"
"http://java.sun.com/j2ee/dtds/web-app_2.2.dtd">

<web-app>
<display-name>FreeMarker Example: Embedding FTL into JSP</display-name>
</web-app>

fmtag.tld:

<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE taglib
PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN"
"http://java.sun.com/j2ee/dtds/web-jsptaglib_1_1.dtd">

<taglib>
<tlibversion>2.0</tlibversion>
<jspversion>1.1</jspversion>
<shortname>FreeMarker JSP Support</shortname>

<tag>
<name>template</name>
<tagclass>freemarker.ext.jsp.FreemarkerTag</tagclass>
<bodycontent>tagdependent</bodycontent>
<info>Allows evaluation of FreeMarker templates inside JSP</info>
<attribute>
<name>caching</name>
<required>false</required>
</attribute>
</tag>
</taglib>

4.新建index.jsp:

<%@ taglib uri="/WEB-INF/fmtag.tld" prefix="fm"%>

<!-- hello所对应的类 -->
<jsp:useBean id="hello" class="com.shiryu.jspexample.Hello" scope="page"/>
<jsp:useBean id="helloReq" class="com.shiryu.jspexample.Hello" scope="request" />
<fm:template>
<html>
<head>
<title>FreeMarker JSP Example</title>
</head>
<body>
<h1>FreeMarker JSP example</h1>
<hr>
<!-- 这里设置变量,将page请求范围里的类hello设为hello -->
<#assign hello = page.hello>
<#assign helloreq = request.helloReq>

<!-- 这里将theString的值在页面显示 -->
<p>page: ${hello.theString}

<!-- 这里将数组的值通过遍历在页面显示 -->
<#list hello.arr as item>
<br>${item}
</#list>
<br>request : ${helloreq.theString}

</body>
</html>
</fm:template>

你可能感兴趣的:(freemaker)