velociy template engine uses detailed

1.velocity About
Velocity is a Java-based template engine. It allows web page designers JAVA code predefined reference method. Web designers can parallel mode based on MVC and JAVA programmers work, which means that Web designers can focus on individual well-designed site, and programmers can focus on writing the underlying code alone. Velocity Java code from the web pages separated out, the site still has a good maintainability after a long run, and provides a feasible alternatives are in addition to JSP and PHP.

2. Use
(1) velocity is apache open source project Download http://velocity.apache.org/
(2) the new project file vtl, the directory structure is as follows, at the same time under the new web-inf conf, layout, www directory


(3) introducing the relevant jar package

(4) in velocity.properties new web-inf / conf directory

#----------------------------------------------------------------------------
# These are the default properties for the
# Velocity Runtime. These values are used when
# Runtime.init() is called, and when Runtime.init(properties)
# fails to find the specificed properties file.
#----------------------------------------------------------------------------

parser.pool.size=200


#----------------------------------------------------------------------------
# R U N T I M E  L O G
#----------------------------------------------------------------------------
# Velocity uses the Servlet APIs logging facilites.

#----------------------------------------------------------------------------
# This controls if Runtime.error(), info() and warn() messages include the
# whole stack trace. The last property controls whether invalid references
# are logged.
#----------------------------------------------------------------------------
#runtime.log.logsystem = 
#runtime.log.logsystem.class = 
runtime.log.error.stacktrace = true
runtime.log.warn.stacktrace  = true
runtime.log.info.stacktrace  = false
runtime.log.debug.stacktrace = false
runtime.log.invalid.references = false

#----------------------------------------------------------------------------
# T E M P L A T E  E N C O D I N G
#----------------------------------------------------------------------------

default.contentType=text/html

input.encoding=UTF-8
output.encoding=UTF-8

#----------------------------------------------------------------------------
# I N C L U D E  P R O P E R T I E S
#----------------------------------------------------------------------------
# These are the properties that governed the way #include'd content
# is governed.
#----------------------------------------------------------------------------

directive.include.output.errormsg.start = <!-- include error :
directive.include.output.errormsg.end   =  see error log -->


#----------------------------------------------------------------------------
# P A R S E  P R O P E R T I E S
#----------------------------------------------------------------------------
directive.set.null.allowed = true
directive.parse.max.depth = 10

#----------------------------------------------------------------------------
# VELOCIMACRO PROPERTIES
#----------------------------------------------------------------------------
# global : name of default global library.  It is expected to be in the regular
# template path.  You may remove it (either the file or this property) if
# you wish with no harm.
#----------------------------------------------------------------------------
#dev-changes by Marino

velocimacro.library.autoreload = true
velocimacro.library = /WEB-INF/conf/VM_common_library.vm

velocimacro.permissions.allow.inline = true
velocimacro.permissions.allow.inline.to.replace.global = false
velocimacro.permissions.allow.inline.local.scope = false

velocimacro.context.localscope = false

velocimacro.messages.on = false

#----------------------------------------------------------------------------
# INTERPOLATION
#----------------------------------------------------------------------------
# turn off and on interpolation of references and directives in string
# literals.  ON by default :)
#----------------------------------------------------------------------------
runtime.interpolate.string.literals = true

#----------------------------------------------------------------------------
# RESOURCE MANAGEMENT
#----------------------------------------------------------------------------
# Allows alternative ResourceManager and ResourceCache implementations
# to be plugged in.
#----------------------------------------------------------------------------

resource.loader = webapp

# webapp.resource.loader.description = Velocity File Resource Loader
# webapp.resource.loader.class = org.apache.velocity.tools.view.servlet.WebappLoader
# webapp.resource.loader.path = /
# webapp.resource.loader.cache = false
# webapp.resource.loader.modificationCheckInterval = 600

# resource.manager.class = org.apache.velocity.runtime.resource.ResourceManagerImpl
# resource.manager.cache.class = org.apache.velocity.runtime.resource.ResourceCacheImpl
resource.manager.logwhenfound = false

#----------------------------------------------------------------------------
# VelocityLayoutServlet
#----------------------------------------------------------------------------
# Filepath for error template, 
#  relative to web application root directory
#  处理错误信息的模板路径
tools.view.servlet.error.template = /WEB-INF/www/500.vm

# Directory for layout templates, 
#  relative to web application root directory
#  所有布局文件的默认路径
tools.view.servlet.layout.directory = /WEB-INF/layout

# Filepath of the default layout template 
#  relative to the layout directory 
#  NOT relative to the root directory of the webapp!
#  默认的布局文件
tools.view.servlet.layout.default.template =  default.vm

Description:

① / WEB-INF / conf / VM_common_library.vm is the path macro file, here we will create
②tools.view.servlet.layout.directory = / WEB-INF / layout is a layout template path
③tools.view.servlet.layout.default .template = default.vm is the default layout file, let's create
(4) new class file

package com.foxhu.sims.velocity;
public class SIMS_VelocityTool {
	public String data() {
		return "data from Tool";
	}
}
This class provides data to the main page template
(6) New velocity-toolbox.xml in web-inf / conf directory
<?xml version="1.0" encoding="UTF-8"?>
<toolbox>
	<tool>
		<key>sims</key>
		<scope>request</scope>
		<class>com.foxhu.sims.velocity.SIMS_VelocityTool</class>
	</tool>
	<tool>
		<key>escape</key>
		<scope>application</scope>
		<class>org.apache.velocity.tools.generic.EscapeTool</class>
	</tool>
	<tool>
	    <key>date</key>
	    <scope>application</scope>
	    <class>org.apache.velocity.tools.generic.DateTool</class>
  </tool>
</toolbox>

Description: This is mainly to provide a data file to the template file, e.g. SIMS_VelocityTool class reference data (which has a data () method) in the template may then $ sims.data () reference
(7) web-inf / conf directory New VM_common_library.vm file for the macro files, mainly used in the definition of some global macro, and display information such as page links generated macro
#macro(show_msg_box $__msg)
<div class="msgbox">
	${__msg}<br/><br/><a href="#" οnclick="history.go(-1);return false;">返回上页</a>
</div>
<div class="spacer_1"></div>
#end

#*
 * 生成翻页链接
 * 作者: Winter Lau
 *#
#macro(pager $__uri $__obj_count $__page_size)
#if($__obj_count > $__page_size)
    #if($__uri.indexOf("?")>=0)#set($param_char='&')#else#set($param_char='?')#end
    #if(!$__uri.endsWith("?") && !$__uri.endsWith("&"))
		#set($__p_uri = "${__uri}${param_char}")
	#else
		#set($__p_uri = $__uri)
	#end
    #set($PAGE_COUNT = $osc_tool.page_count($__obj_count, $__page_size))
    #set($__p = $link.param("p",1))
	#if($__p <= $PAGE_COUNT)
    #set($pre_page = $__p - 1)
    #set($next_page = $__p + 1)
	#if($__p > 3)
    	#set($begin_idx = $__p - 3)
	#else
		#set($begin_idx = 1)
	#end	
    #set($end_idx = $begin_idx + 9)
    #if($end_idx > $PAGE_COUNT)#set($end_idx = $PAGE_COUNT)#end
    <ul class="pager">
        #if($__p > 1)<li class='page prev'><a href="${__p_uri}p=$pre_page"><</a></li>#end#if($begin_idx > 1)<li class='page'><a href="${__p_uri}">1</a></li>#end#foreach($idx in [$begin_idx..$end_idx])#if($idx != $__p)<li class='page'><a href="${__p_uri}p=$idx">$idx</a></li>#else<li class='page current'><a href="${__p_uri}p=$idx">$idx</a></li>#end#end#if($end_idx < $PAGE_COUNT)<li class='page'><a href="${__p_uri}p=$PAGE_COUNT">$PAGE_COUNT</a></li>#end#if($__p < $PAGE_COUNT)<li class='page next'><a href="${__p_uri}p=$next_page">></a></li>#end
    </ul>
	#end
#end
#end
(8) New in web-inf / layout directory default.vm default layout file
<html >
<head >
	<title>$!page_title</title>
</head>
<body>
##$screen_content便是VelocityLayoutServlet保留的关键字,Velocity依此关键字来潜入实际被 引用的页面内容
	$screen_content
</body>
</html>
(9) New page template error in web-inf / www directory 500.vm
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
    <title>ERROR</title>
    <style type="text/css">
    <!--
        body {font-family: arial,sans-serif}
		#error{padding:20px}
		#title_bar{background-color:#dd0000;padding:8px;padding-left:20px;font-size:16pt;font-weight:bold;color:#ffff00}
		#info{padding-top:20px;padding-bottom:20px;color:#0000aa}
        #error_detail{padding:2px;background-color:#eeeeee;}
		#error_time{padding:2px;font-size:8pt}
    //-->
    </style>
</head>

<body>
<div id="error">
  <div id="title_bar">$escape.html("!!! 错 误 !!!")</div>
    <div id="info">
      <h2>$escape.html("您访问的页面发生错误!")</h2>
		$escape.html("请将此错误信息报告给我们的系统管理员,以便我们尽快为您解决该问题。")<br/><br/>        
		$escape.html("您可以通过电子邮件:")<a href="mailto:[email protected]">[email protected]</a> $escape.html("将下面的信息发送给我们。")<br/><br/>
	    $escape.html("感谢您对我们的大力支持!")(<a href="#" οnclick="history.go(-1);return false;">$escape.html("回到上页")</a>)
    </div>
	
	<div id="error_time">$date.get("yyyy-MM-dd HH:mm:ss")</div>
</div>
</body>
</html>
(10) configured to modify xml file
<?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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>vtl</display-name>
  <servlet>
    <servlet-name>velocity</servlet-name>
    <servlet-class>org.apache.velocity.tools.view.servlet.VelocityLayoutServlet</servlet-class>
    <init-param>
			<param-name>org.apache.velocity.toolbox</param-name>
			<param-value>/WEB-INF/conf/velocity-toolbox.xml</param-value>
	</init-param>
	<init-param>
		<param-name>org.apache.velocity.properties</param-name>
		<param-value>/WEB-INF/conf/velocity.properties</param-value>
	</init-param>
	<load-on-startup>1</load-on-startup>
  </servlet>
  
  <servlet-mapping>
    <servlet-name>velocity</servlet-name>
    <url-pattern>*.vm</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
		<welcome-file>index.vm</welcome-file>
	</welcome-file-list>
	<error-page>
		<error-code>404</error-code>
		<location>/404.vm</location>
	</error-page>
	<error-page>
		<error-code>500</error-code>
		<location>/500.vm</location>
	</error-page>
</web-app>
(111) New Test page test.vm
#set($page_title="Layout Test")
Hello Velocity Layout!
$sims.data();
Note: Do not write here html, head and body labels, since we already configured in default.vm template, this is the layout of the velocity of the classic application
(12) to start tomcat, enter in the address bar http: // localhost: 8080 /vtl/test.vm , see the following results of
the Hello Velocity Layout from the data Tool;!
(13) complete project directory structure


references:
http://www.oschina.net/question/12_4580
HTTP: // the WWW .oschina.net / code / snippet_12_5638








Published 41 original articles · won praise 114 · views 680 000 +

Guess you like

Origin blog.csdn.net/hil2000/article/details/8145271