关闭

Spring遇见问题(三)-----FreeMarker自定义标签

标签: FreeMarkersprspan styledisplay
878人阅读 评论(0) 收藏 举报
分类:

web.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
		 xmlns="http://java.sun.com/xml/ns/javaee" 
		 xsi:schemaLocation=
		 "http://java.sun.com/xml/ns/javaee 
		 http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" 
		 id="WebApp_ID" version="3.0">
  	<display-name>Springmvc3.2.5</display-name>

	<servlet>
	  <servlet-name>springmvc</servlet-name>
	  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
	  <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:springmvc-config.xml</param-value>
      </init-param>
	  <load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
	  <servlet-name>springmvc</servlet-name>
	  <url-pattern>/</url-pattern>
	</servlet-mapping>
</web-app>

springmvc-config.xml

<?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:p="http://www.springframework.org/schema/p"
		xmlns:context="http://www.springframework.org/schema/context"
		xmlns:mvc="http://www.springframework.org/schema/mvc"
		xsi:schemaLocation="
		http://www.springframework.org/schema/beans
		http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context
		http://www.springframework.org/schema/context/spring-context.xsd
		http://www.springframework.org/schema/mvc
		http://www.springframework.org/schema/mvc/spring-mvc.xsd"
		default-lazy-init="true">
	
	<!-- 注解方式 -->
	<!-- 自动扫描controller包下的所有类,使其认为spring mvc的控制器 -->
	<context:component-scan base-package="com.springmvc.controller"/>
	<context:component-scan base-package="com.springmvc.directive" />
	
	<!-- HandlerMapping -->
	<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/>
	<!-- HandlerAdapter -->
	<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/>
	<!-- ViewResolver -->
	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
		<property name="prefix" value="/WEB-INF/jsp/"/>
		<property name="suffix" value=".jsp"/>
	</bean>
		
	<bean class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
		<property name="prefix" value="" />
		<property name="suffix" value=".ftl"/>
		<property name="contentType" value="text/html;charset=UTF-8"></property>  
        <property name="order" value="0"></property>
	</bean>
	
	<bean id="freemarkerConfig"  
      class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">  
	<!-- 其中一下代码是用来扫描.ftl的模板文件,在/WEB-INF/ftl目录中 -->
    	<property name="templateLoaderPath" value="/WEB-INF/ftl/" />
		<property name="freemarkerSettings">  
    	    <props>
				<prop key="template_update_delay">0</prop>  
				<prop key="default_encoding">UTF-8</prop>  
				<prop key="number_format">0.##########</prop>  
				<prop key="datetime_format">yyyy-MM-dd HH:mm:ss</prop>  
				<prop key="classic_compatible">true</prop>  
				<prop key="template_exception_handler">ignore</prop>  
			</props>  
		</property>
		<!-- 自定义标签的关联配置 -->
		<property name="freemarkerVariables"> 
			<map> 
				<entry key="K2" value-ref="F4" />
				<entry key="ShowLsit" value-ref="show_list" />
			</map>
		</property> 
	</bean> 

</beans>

在com.springmvc.directive包下定义一个标签类继承TemplateDirectiveModel

package com.springmvc.directive;

import java.io.IOException;
import java.util.Map;
import static freemarker.template.ObjectWrapper.DEFAULT_WRAPPER;
import org.springframework.stereotype.Service;

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

@Service("F4")
public class TestDirective implements TemplateDirectiveModel {

	/**
	 * 
	 * Environment env 当前HTML/FTL的环境引用
	 * Map params 自定义标签的属性参数
	 * TemplateModel[] loopVars	待处理(暂定为无用)
	 * TemplateDirectiveBody body 标签体内部内容引用
	 */
	@Override
	public void execute(Environment env, Map params, TemplateModel[] loopVars,    
            TemplateDirectiveBody body) throws TemplateException, IOException {

		String text = "";
		int length = 0;
		//获取F4标签上的text属性上的值
		if (params.get("text") != null) {
			text = ((SimpleScalar) params.get("text")).getAsString();
		}
		if (params.get("length") != null) {
			length = Integer.valueOf(((SimpleScalar) params.get("length")).getAsString());
		}
		if (length < text.length()) {
			text = "..." + text.substring(text.length() - length);
		}
		
		env.setVariable("key", DEFAULT_WRAPPER.wrap(text));
        if (body != null) {
            body.render(env.getOut());
        }else {
        	env.getOut().write(text);
        }
	}

}

com.springmvc.controller包下定义Controller类

package com.springmvc.controller;

import java.util.ArrayList;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.springmvc.bean.UserBean;

@Controller //①将一个POJO类声明为处理器
//@RequestMapping(value="/user") //做窄化处理
public class HelloWorldController {
	
	@RequestMapping(value="/hello")
	public ModelAndView helloWorld2() {
		ModelAndView mv = new ModelAndView();
		mv.addObject("message", "AAAAAAA");
		mv.setViewName("hello");
		return mv;
	}

//	@RequestMapping(value={"/hello2","/haha","/xixi"})//②请求URL到处理器功能处理方法的映射
//	public ModelAndView helloWorld(HttpServletRequest request, HttpServletResponse response, HttpSession session) {
//		//1、收集参数//2、绑定参数到命令对象
//		//3、调用业务对象//4、选择下一个页面
//		ModelAndView mv = new ModelAndView();
//		//添加模型数据可以是任意的POJO对象
//		mv.addObject("message", "Hello World!");
//		//设置逻辑视图名,视图解析器会根据该名字解析到具体的视图页面
//		mv.setViewName("hello");
//		return mv; //3 模型数据和逻辑视图名
//	}
	
	@RequestMapping("/dome")
	public ModelAndView freemarkerDome(HttpServletRequest request, HttpServletResponse response, HttpSession session) {
		ModelAndView mv = new ModelAndView();
		ArrayList<UserBean> list = new ArrayList<>();
		UserBean userBean = new UserBean();
		userBean.setUser_id("AAA");
		userBean.setUser_name("学生");
		userBean.setUser_age(21);
		list.add(userBean);
		userBean = new UserBean();
		userBean.setUser_id("BBB");
		userBean.setUser_name("小朋友");
		userBean.setUser_age(12);
		list.add(userBean);
		userBean = new UserBean();
		userBean.setUser_id("CCC");
		userBean.setUser_name("老师");
		userBean.setUser_age(50);
		list.add(userBean);
		mv.addObject("list", list);
		mv.setViewName("tt");
		return mv;
	}
}

指向tt.ftl文件

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>ftl</title>
</head>
<body>
<div style="border:#F33 2px solid;width:20%;float:left;margin-left:50px;padding: 5px;">
<h2>后台传值 list形式取出<br/></h2>
	<#list list as user>
	userID : ${user.user_id}<br/>
	userName : ${user.user_name}<br/>
	userAge : #{user.user_age}<br/>
	</#list>
</div>
<div style="border:#F33 2px solid;width:20%;float:left;margin-left:50px;padding: 5px;">
<#assign x = "自定义标签测试" />
<h2>${x}<br/></h2>
<#assign x = 23.45637 />
#{x}<br>

<@K2 text="1234567" length="6">
	<input type="text" value=${key}>
</@K2>
<br/>
<@K2 text="TTTTTTTTTTTTT" length="6">
	<input type="text" value=${key}>
</@K2>
<br/>
<@K2 text="=============" length="6"></@K2>
</div>
<div style="border:#F33 2px solid;width:20%;float:left;margin-left:50px;padding: 5px;">
<#import "/macrotest.ftl" as BB>
<@BB.page title="宏练习">
	<ul style="color:#F0F;">
		<li>spring</li>
		<li>j2ee</li>
	</ul>
</@BB.page>
</div>
<div style="border:#F33 2px solid;width:20%;float:left;margin-left:50px;padding: 5px;">
<@ShowLsit text="user" value=user stylex="4"></@ShowLsit>
</div>
</body>
</html>

这样一个整体的配置使用流程就形成了。


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:27889次
    • 积分:584
    • 等级:
    • 排名:千里之外
    • 原创:31篇
    • 转载:17篇
    • 译文:0篇
    • 评论:2条
    文章分类
    最新评论