FreemakerS 成jsp

本文介绍如何在Java Web项目中使用Freemarker模板引擎与JSP进行整合。具体步骤包括配置Freemarker依赖、创建JavaBean、设置web.xml及fmtag.tld文件,并展示如何在index.jsp中调用Freemarker模板。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值