This is the 15th day of my participation in the Novembermore Challenge

Velocity is a Java-based templating engine that allows anyone to reference objects defined by Java code using only a simple templating language.

1 Introduction to Velocity

The Velocity templating engine, a full-fledged Java-based templating engine, helps us to static pages, separate Java code from web pages, and integrate templates and fill data to produce the pages we need.

1 Basic Syntax

1 keyword

Keywords in Velocity templates are represented with #

  • #set sets a variable
  • #if conditional branching
  • #else Another conditional branch
  • The #end statement ends
  • #foreach loop statement

2 variables

Variables in Velocity templates are represented starting with $

For example, $user $password Indicates the password of the user

{} variable

For explicit Velocity variables, we can include them with {} and display the following effects on the page:

$someoneName = someoneName; ${user}Name = someoneName;

! variable

As mentioned above, the Velocity template will display $user on the page if the variable does not exist, which affects the presentation. You can use $! The user said.

$! User indicates that if it exists, it is displayed. If it does not exist, it is blank

## define a user variable as Libai, Set {$user = "123456"} #set{$user = "123456"} #set{$student. Name = "123456"} ## set{$user = "123456"} # Set ($student.address = $address.info) $student.address = $address.infoCopy the code

Escape characters and logical operators

The escape character in a Velocity template is \

$user $user $user $user $user $user $user $user $user $user $user $userCopy the code

&& and

| | or

! The not

4 cycle

The list collection loop syntax in Velocity templates

Loop through, you can get each element, the number of each element, and the total set length

${list.size()} #end ${list.size()} #endCopy the code

Map collection loop syntax

$entry. Key => $entry. Value #end $entryCopy the code

5 conditions

Conditional syntax if-ifelse-else structure in Velocity template

# # the if (condition1) / / perform business elseif (condition2) / / perform business # # else / / perform business endCopy the code

A common conditional statement is the if-else structure

# if (condition1) / / perform business # # else / / perform business endCopy the code

#break

Break out of the loop

#if($user == "condition1 ") #break; #end #else // Perform business #endCopy the code

#stop

Terminates instruction, terminates template parsing

If ($user == "condition1 ") #stop #end #elseCopy the code

6 comments

Single-line comment ##

Set {$user = "user "}Copy the code

Multi-line comment #* *#

# #set{$user = "$user "}Copy the code

Note #** *#

# #set{$user = "$user "}Copy the code

7 Importing Resources

#include

The imported resources are not parsed by the engine

#include( "one.gif","two.txt","three.htm" )
Copy the code

#parse

Used to import scripts, the imported resources are parsed by the engine

# # # Dr. M file set ($user = "li bai") # # # parse b.v m file (" Dr. M ") # # variable value $user li baiCopy the code

2 The use of Velocity

Common Cases and utility classes for Velocity

public class VelocityUtils {

    public static void main(String[] args) {

        // Template path
        String templatePath = "D:\\work";
        // The template name
        String templateName = "index.html.vm";
        // Generate file path
        String outFilePath = "D:\\index.html";
        // The required parameters in the template
        Map<String, Object> params = new HashMap<>();
        params.put("name"."world");
        List<String> list =  new ArrayList<>();
        list.add("Li bai");
        list.add("Du fu");
        list.add("Lu you");
        params.put("list", list);

        getFile(templatePath,templateName,outFilePath,params);
    }

    /** * read the local template, generate file *@paramTemplatePath templatePath *@paramTemplateName specifies the templateName *@paramOutFilePath Generated file path *@paramFill the params template with the */ parameter
    public static void getFile(String templatePath, String templateName, String outFilePath, Map
       
         params)
       ,> {
        try {
            // Create a property
   			loadTemplateFileByTwo(templatePath);

            // Encapsulate the fill parameter
            VelocityContext context = new VelocityContext(params);
            // Get the template
            Template tpl = Velocity.getTemplate(templateName, "UTF-8");
            // Create an output stream
            Writer writer = new PrintWriter(new FileOutputStream(new File(outFilePath)));
            // Template and data population
            tpl.merge(context, writer);
            // Refresh data
            writer.flush();
			writer.close();  
        } catch(IOException e) { e.printStackTrace(); }}/** * returns the generated template file as a zip package@paramResponse Response object *@paramParams template encapsulation parameter *@throws IOException
     */
    public static void createFile(HttpServletResponse response, Map<String, Object> params)
            throws IOException {
        
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        ZipOutputStream outZip = new ZipOutputStream(output);

        // Set the Velocity resource loader
        loadTemplateFileByOne();

        // Encapsulate template data
        VelocityContext context = new VelocityContext(params);

        // Get the template list
        List<String> templates = getTemplates();
        for (String template : templates) {
            // Render the template
            StringWriter sw = new StringWriter();
            Template tpl = Velocity.getTemplate(template, "UTF-8");
            tpl.merge(context, sw);
            
            // Add data
            outZip.putNextEntry(new ZipEntry(getFileName(template)));
            IOUtils.write(sw.toString(), outZip, "UTF-8");
            IOUtils.closeQuietly(sw);
        }

        IOUtils.closeQuietly(outZip);
        byte[] data = output.toByteArray();

        // Generate a zip response
        response.setHeader("Content-Disposition"."attachment; filename=\"template-file.zip\"");
        response.addHeader("Content-Length", String.valueOf(data.length));
        response.setContentType("application/octet-stream; charset=UTF-8");
        IOUtils.write(data, response.getOutputStream());

    }

    /** * get the file name */
    / * * *@paramTemplate The template name is index.html.vm */
    private static String getFileName(String template) {
        return template.replace(".vm"."");
    }

    /** * get template */
    private static List<String> getTemplates(a) {
        List<String> templates = Lists.newArrayList();
        // Back-end related templates
        templates.add("index.html.vm");
        return templates;
    }
    

    Method 1: Load the VM file in the classpath directory */
    public static void loadTemplateFileByOne(a) {
        Properties p = new Properties();
        p.put("file.resource.loader.class"."org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
        Velocity.init(p);
    }

    /** * Load the configuration file. Method 2 Load the VM file ** in the absolute directory@paramTemplatePath templatePath */
    public static void loadTemplateFileByTwo(String templatePath) {
        Properties p = new Properties();
        // Set the template loading path to the work folder on drive D
        p.setProperty(VelocityEngine.FILE_RESOURCE_LOADER_PATH, templatePath);
        Velocity.init(p);
    }

    /** * Load the configuration file. Method 3 Use the configuration file **@paramPropertiesPath, e.g. /velocity.properties */
    public static void loadTemplateFileByThree(String propertiesPath) throws IOException {
        Properties p = newProperties(); p.load(VelocityUtils.class.getClass().getResourceAsStream(propertiesPath)); Velocity.init(p); }}Copy the code

The index.html.vm template file is stored in the WORK folder on D: disk

<table cellspacing="0" cellpadding="5" width="20%" >
<tr>
<td bgcolor="#eeeeee" align="center">Names: ${name}</td>
</tr>
#foreach($name in $list)
	<tr>
	<td>${list.size()} ${list.size()} ${list.size()</td>
	</tr>
#end
</table>
Copy the code

The generated index.html file

<table cellspacing="0" cellpadding="5" width="20%" >
<tr>
<td bgcolor="#eeeeee" align="center">Names: world</td>
</tr>
	<tr>
	<td>The first one, whose name is Li Bai, is three in all</td>
	</tr>
	<tr>
	<td>The second, named Du Fu, is three in all</td>
	</tr>
	<tr>
	<td>The third one is Lu You. There are three in all</td>
	</tr>
</table>
Copy the code

From the above test case, we can see that the name parameter has, and the list collection parameter has. The Velocity templating engine is very useful for routine loop conditions.

References:

www.51gjie.com/javaweb/896…

Yanglinwei.blog.csdn.net/article/det…