今天准备自学Freemarker模板,先在网上下载了Freemarker,把freemarker.jar引入到工程中,然后跟着文档开始自学了.........
我先把官方的例子引入到工程中运行了下,知道了大概意思,然后开始在官方例子的基础上进行延伸学习。
Animals类——
package com.freemarker;
public class Animals {
private String name;
private String price;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
}
官方的Servlet进行扩充
package com.freemarker;
import java.util.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import freemarker.template.*;
/**
* This Servlet does not do anything useful, just prints "Hello World!". The
* intent is to help you to get started if you want to build your own Controller
* servlet that uses FreeMarker for the View. For more advanced example, see the
* 2nd Web application example.
*/
public class Hello extends HttpServlet {
private Configuration cfg;
public void init() {
// Initialize the FreeMarker configuration;
// - Create a configuration instance
cfg = new Configuration();
// - Templates are stoted in the WEB-INF/templates directory of the Web app.
cfg.setServletContextForTemplateLoading(
getServletContext(), "WEB-INF/templates");
// In a real-world application various other settings should be explicitly
// set here, but for the sake of brevity we leave it out now. See the
// "webapp2" example for them.
}
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// Build the data-model
Map root=new HashMap();
Animals a=new Animals();
a.setName("mouse");
a.setPrice("50");
Animals a1=new Animals();
a1.setName("elephant");
a1.setPrice("5000");
Animals a2=new Animals();
a2.setName("python");
a2.setPrice("800");
SimpleSequence animals=new SimpleSequence();
animals.add(a);
animals.add(a1);
animals.add(a2);
root.put("animals",animals);
// Get the templat object
Template t = cfg.getTemplate("test.ftl");
// Prepare the HTTP response:
// - Use the charset of template for the output
// - Use text/html MIME-type
resp.setContentType("text/html; charset=" + t.getEncoding());
Writer out = resp.getWriter();
// Merge the data-model and the template
try {
t.process(root, out);
} catch (TemplateException e) {
throw new ServletException(
"Error while processing FreeMarker template", e);
}
}
}
我的FTL文件
<html>
<head> <title>FreeMarker Example WebApplication1</title>
</head>
<body>
姓名:${animals[0].name}
价格:${animals[1].price}
<#list animals as a>
${a.name}->${a.price}
</#list> <br>
hello ${user!"Anonymous"}
<#if user??>
哈哈
<#else>
hi
</#if>
</body>
</html>
遍历Map
<#list roo?keys as m>
key:${m}<br>
vaule:${roo[m]}<br>
</#list>
freemarerk标签
if标签
<#if condition>...
<#elseif condition2>...
<#else>...
</#if>
switch,case,default,break标签
<#switch value>
<#case refvalue>...
<#break>
<#case refvalue2>...
<#break>
<#default>...
</#switch>
include标签
<#include path>or
<#include path options>
import 标签
<#import path as hash>
noparse 标签
<#noparse>...
</#noparse>
compress标签
<#compress>...
</#compress>
escape,noescape标签
<#escape identifier as expression>...
<#noescape>...
</#noescape>...
</#escape>
assign标签
<#assign name=value>or
<#assign name=value1 name2=value2>or
<#assign same as above ... in namespacehash>or
<#assign name>capture this
</#assign>
or
<#assign name in namespace hash>
captrue this
</#assign>
global 标签
<#global name=value>
or
<#global name1=value1 name2= value2>
or
<#global name>
captrue this
</#global>
local标签
<#local name=value>
or
<#local name1=value1 name2=value2>
or
<#local name>
captrue this
</#local>
setting 标签
<#setting name=value>
macro,nested,return 标签
<#macro name param1 param2 ...paramN>...
<#nested loopvar1,loopvar2,...loopvarN>...
<#return>...
</#macro>
function,return 标签
<#function name param1 param2 ...paramN>
...
<#return returnvalue>
</#function>
ftl标签
<#ftl param1=value1 param2=value2...paramN=valueN>
t,lt,rt标签
<#t>
<#lt>
<#rt>
<#nt>
attempt,recover标签
<#attempt>
attempt block
<#recover>
recover block
</#attempt>
visit,recurse,fallback标签
<#visit node using namespace>or
<#visit node>
<#recurcse node using namespace>or
<#recurcse node>or
<#recurse using namespace>or
<#recurse>
<#fallback>
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"
default-lazy-init="true">
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="cacheSeconds" value="-1"/>
<property name="basenames">
<list>
<value>/WEB-INF/languages/jeecore_admin/messages</value>
<value>/WEB-INF/languages/jeecms_admin/messages</value>
<value>/WEB-INF/languages/jeecms_tpl/messages</value>
<value>/WEB-INF/languages/fck/messages</value>
</list>
</property>
</bean>
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>
<!--
<bean id="multipartResolver" class="com.jeecms.common.web.cos.CosMultipartResolver"/>
-->
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="webBindingInitializer">
<bean class=" com.jeecms.common.web.springmvc.BindingInitializer"/>
</property>
</bean>
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
<property name="interceptors">
<list>
<ref bean="adminContextInterceptor"/>
<ref bean="adminLocaleIntercept"/>
</list>
</property>
</bean>
<bean id="adminContextInterceptor" class="com.jeecms.cms.web.AdminContextInterceptor">
<!--<property name="adminId" value="1"/>-->
<property name="auth" value="true"/>
<property name="loginUrl" value="/jeeadmin/jeecms/login.do"/>
<property name="returnUrl" value="/jeeadmin/jeecms/index.do"/>
<property name="excludeUrls">
<list>
<value>/login.do</value>
<value>/logout.do</value>
</list>
</property>
</bean>
<bean id="adminLocaleIntercept" class="com.jeecms.cms.web.AdminLocaleInterceptor"/>
<bean id="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleResolver">
<property name="cookieName" value="clientlanguage"/>
<property name="cookieMaxAge" value="-1"/>
</bean>
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<prop key="org.springframework.web.bind.MissingServletRequestParameterException">/error/requiredParameter</prop>
<prop key="org.springframework.beans.TypeMismatchException">/error/mismatchParameter</prop>
<prop key="org.springframework.web.bind.ServletRequestBindingException">/error/bindException</prop>
<prop key="org.springframework.dao.DataIntegrityViolationException">/error/integrityViolation</prop>
</props>
</property>
</bean>
<bean id="freemarkerViewResolver" class="com.jeecms.common.web.springmvc.RichFreeMarkerViewResolver">
<property name="prefix" value="/jeecms_sys/"/>
<property name="suffix" value=".html"/>
<property name="contentType" value="text/html; charset=UTF-8"/>
<property name="exposeRequestAttributes" value="false"/>
<property name="exposeSessionAttributes" value="false"/>
<property name="exposeSpringMacroHelpers" value="true"/>
</bean>
<bean id="freemarkerConfig" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
<property name="templateLoaderPath" value="/WEB-INF"/>
<property name="freemarkerVariables">
<map>
<!--在FCK编辑器中需要用到appBase,以确定connector路径。-->
<entry key="appBase" value="/jeeadmin/jeecms"/>
<!--后台管理权限控制-->
<entry key="cms_perm" value-ref="cms_perm"/>
<entry key="text_cut" value-ref="text_cut"/>
<entry key="html_cut" value-ref="html_cut"/>
</map>
</property>
<property name="freemarkerSettings">
<props>
<prop key="template_update_delay">0</prop>
<prop key="defaultEncoding">UTF-8</prop>
<prop key="url_escaping_charset">UTF-8</prop>
<prop key="locale">zh_CN</prop>
<prop key="boolean_format">true,false</prop>
<prop key="datetime_format">yyyy-MM-dd HH:mm:ss</prop>
<prop key="date_format">yyyy-MM-dd</prop>
<prop key="time_format">HH:mm:ss</prop>
<prop key="number_format">0.######</prop>
<prop key="whitespace_stripping">true</prop>
<prop key="auto_import">/ftl/pony/index.ftl as p,/ftl/spring.ftl as s</prop>
</props>
</property>
</bean>
<context:annotation-config/>
<!--包含action-->
<import resource="jeecms-servlet-admin-action.xml"/>
</beans>