spring3+freemark自定义标签

<bean id="viewResolver"
  class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
  <property name="suffix">
   <value>.ftl</value>
  </property>
  <property name="viewClass">
   <value>org.springframework.web.servlet.view.freemarker.FreeMarkerView
   </value>
  </property>
  <property name="contentType">
   <value>text/vnd.wap.wml;charset=UTF-8</value>
  </property>
  <property name="exposeSpringMacroHelpers" value="true"/>
  <property name="requestContextAttribute" value="rc"></property>
 </bean>
 
<!-- 配置Freemarker -->
	<bean id="freemarkerConfigurer"
		class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
		<property name="templateLoaderPath" value="/WEB-INF/pages/templates/" />
		<property name="freemarkerSettings"><!-- 如果模板不经常更新,此属性设置更新延迟时间 -->
			<props>
				<prop key="template_update_delay">0</prop>
				<prop key="defaultEncoding">UTF-8</prop>
				<prop key="datetime_format">yyyy-MM-dd HH:mm</prop>
				<prop key="time_format">HH:mm</prop>
				<prop key="date_format">yyyy-MM-dd</prop>
				<prop key="number_format">0.##</prop>
			</props>
		</property>
		<property name="freemarkerVariables">
			<map> 
				<entry key="tjia" value-ref="tjia"/> 
				<entry key="tsub" value-ref="tsub"/> 
			</map> 
		</property>
	</bean>

	<bean id="tjia" class="com.wap.web.directive.TestJiaDirective"></bean>
	<bean id="tsub" class="com.wap.web.directive.TestSubDirective"></bean>

 

自定义标签类:

import java.io.IOException;
import java.util.Map;

import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;

public class TestJiaDirective implements TemplateDirectiveModel{

	@Override
	public void execute(Environment env, Map params, TemplateModel[] loopVars,
			TemplateDirectiveBody body) throws TemplateException, IOException {
		int v1 = Integer.parseInt(params.get("v1").toString());
		int v2 = Integer.parseInt(params.get("v2").toString());
		System.out.println("v1:"+v1+"----v2:"+v2);
		for(TemplateModel t:loopVars){
			System.out.println("----TemplateModel:"+t.toString());
		}
		env.getOut().write(String.valueOf(v1+v2));
	}
	
}

 

前端:ftl中

<@tjia v1="1" v2="2"/>

 

 

你可能感兴趣的:(freemark)