B站-黑马-velocity教程-学习笔记(到生成器部分)

16 篇文章 0 订阅
9 篇文章 0 订阅

image.png

简介

简介

image.png

应用场景

image.png

组成结构

image.png

快速入门

image.png

创建工程(普通maven工程)

pom

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.malred</groupId>
    <artifactId>velocity_01</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.apache.velocity</groupId>
            <artifactId>velocity-engine-core</artifactId>
            <version>2.2</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>utf-8</encoding>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project> 

resources/src/main/resources/vms/01-quickstart.vm

<!DOCTYPE html>
<html lang="zh_cn">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Title</title>
</head>
<body>
hello ${name} !
</body>
</html>
<style>
</style> 

src/test/java/org/malred/VelocityTest.java

package org.malred; 
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.junit.Test; 
import java.io.FileWriter;
import java.io.IOException;
import java.util.Properties; 
public class VelocityTest {
    @Test
    public void test1() throws IOException {
        // 1,设置velocity的资源加载器
        Properties prop = new Properties();
        prop.put("file.resource.loader.class",
                "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
        // 2,初始化velocity引擎
        Velocity.init(prop);
        // 3,创建velocity容器
        VelocityContext context = new VelocityContext();
        // 设置数据
        context.put("name", "zhangsan");
        // 4,加载velocity模板文件
        Template template = Velocity.getTemplate("vms/01-quickstart.vm", "utf-8");
        // 5,合并数据到模板
        FileWriter fw =
                new FileWriter("D:\\idea_java\\velocity_01\\src\\main\\resources\\html\\01-quickstart.html");
        // 合并+写入
        template.merge(context, fw);
        // 6,释放资源
        fw.close();
    }
} 

测试

image.png

VTL基础语法

image.png

注释

image.png

<!DOCTYPE html>
<html lang="zh_cn">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Title</title>
</head>
<body>
    ## 单行注释,注释内容不会被输出
    #*
    * 多行注释
    * *#
    #**
     * 文档注释
     * *#
hello ${name} !
</body>
</html>
<style>
</style> 

非解析内容

image.png

<!DOCTYPE html>
<html lang="zh_cn">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Title</title>
</head>
<body>
    ## 单行注释,注释内容不会被输出
    #*
    * 多行注释
    * *#
    #**
     * 文档注释
     * *#
hello ${name} !
<h1>非解析内容,原样输出</h1>
#[[
    ${name}
    非解析内容1
    非解析内容2
]]#
</body>
</html>  

image.png

引用

image.png

package org.malred; 
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.junit.Test; 
import java.io.FileWriter;
import java.io.IOException;
import java.util.Properties; 
public class VelocityTest { 
    @Test
    public void test2() throws IOException {
        // 1,设置velocity的资源加载器
        Properties prop = new Properties();
        prop.put("file.resource.loader.class",
                 "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
        // 2,初始化velocity引擎
        Velocity.init(prop);
        // 3,创建velocity容器
        VelocityContext context = new VelocityContext();
        // 设置数据
        //        context.put("name", "zhangsan");
        // 4,加载velocity模板文件
        Template template = Velocity.getTemplate("vms/02-cite-variable.vm", "utf-8");
        // 5,合并数据到模板
        FileWriter fw =
            new FileWriter("D:\\idea_java\\velocity_01\\src\\main\\resources\\html\\02-cite-variable.html");
        // 合并+写入
        template.merge(context, fw);
        // 6,释放资源
        fw.close();
    }
}

属性引用

image.png

src/main/resources/vms/03-cite-field.vm
<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport"
      content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
  </head>
  <body>
    常规语法: $user.username ---- $user.password ---- $user.email
    正规语法: ${user.username} ---- ${user.password} ---- ${user.email}

    常规语法: $!user.username ---- $!user.password ---- $!user.email
    正规语法: $!{user.username} ---- $!{user.password} ---- $!{user.email}
  </body>
</html> 
src/main/java/org/malred/pojo/User.java
package org.malred.pojo;  
public class User {
    private String username;
    private String password;
    private String email;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
} 
src/test/java/org/malred/VelocityTest.java
package org.malred; 
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.junit.Test;
import org.malred.pojo.User; 
import java.io.FileWriter;
import java.io.IOException;
import java.util.Date;
import java.util.Properties; 
public class VelocityTest { 
    @Test
    public void test3() throws IOException {
        // 1,设置velocity的资源加载器
        Properties prop = new Properties();
        prop.put("file.resource.loader.class",
                "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
        // 2,初始化velocity引擎
        Velocity.init(prop);
        // 3,创建velocity容器
        VelocityContext context = new VelocityContext();
        // 设置数据
        User user = new User();
        user.setUsername("malred");
        user.setPassword("123456");
        user.setEmail("malred@gmail.com");
        context.put("user", user);
        // 4,加载velocity模板文件
        Template template = Velocity.getTemplate("vms/03-cite-field.vm", "utf-8");
        // 5,合并数据到模板
        FileWriter fw =
                new FileWriter("D:\\idea_java\\velocity_01\\src\\main\\resources\\html\\03-cite-field.html");
        // 合并+写入
        template.merge(context, fw);
        // 6,释放资源
        fw.close();
    } 
} 

方法引用

image.png

src/test/java/org/malred/VelocityTest.java
package org.malred; 
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.junit.Test;
import org.malred.pojo.User; 
import java.io.FileWriter;
import java.io.IOException;
import java.util.Date;
import java.util.Properties; 
public class VelocityTest { 
    @Test
    public void test4() throws IOException {
        // 1,设置velocity的资源加载器
        Properties prop = new Properties();
        prop.put("file.resource.loader.class",
                "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
        // 2,初始化velocity引擎
        Velocity.init(prop);
        // 3,创建velocity容器
        VelocityContext context = new VelocityContext();
        // 设置数据
        context.put("str", "hello world velocity !");
        context.put("now",new Date());
        // 4,加载velocity模板文件
        Template template = Velocity.getTemplate("vms/04-cite-method.vm", "utf-8");
        // 5,合并数据到模板
        FileWriter fw =
                new FileWriter("D:\\idea_java\\velocity_01\\src\\main\\resources\\html\\04-cite-method.vm.html");
        // 合并+写入
        template.merge(context, fw);
        // 6,释放资源
        fw.close();
    }
} 

指令

流程控制

#set

image.png

<!-- src/main/resources/vms/05-instructions-set.vm -->
<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport"
      content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
  </head>
  <body>
    #set($str="hello world")
    #set($int=10)
    #set($arr=[1,2,3,4,5])
    #set($boolean=true)
    #set($map={"key1":"value1","key2":"value2","key3":"value3"})
    ## 声明时可以引用之前定义过的变量
    #set($name="张三")
    #set($str2="hello,how are you,$name")
    ## 获取set定义的变量
    $str ---- ${str}
    $str2 ---- ${str2}
    $int ---- ${int}
    $arr ---- ${arr}
    $boolean ---- ${boolean}
    $map.key1 ---- ${map.key1}
    $map.key2 ---- ${map.key2}
    $map.key3 ---- ${map.key3}
  </body>
</html>  
package org.malred; 
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.junit.Test;
import org.malred.pojo.User; 
import java.io.FileWriter;
import java.io.IOException;
import java.util.Date;
import java.util.Properties; 
public class VelocityTest { 
    @Test
    public void test5() throws IOException {
        // 1,设置velocity的资源加载器
        Properties prop = new Properties();
        prop.put("file.resource.loader.class",
                "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
        // 2,初始化velocity引擎
        Velocity.init(prop);
        // 3,创建velocity容器
        VelocityContext context = new VelocityContext();
        // 设置数据
        context.put("str", "hello world velocity !");
        // 4,加载velocity模板文件
        Template template = Velocity.getTemplate("vms/05-instructions-set.vm", "utf-8");
        // 5,合并数据到模板
        FileWriter fw =
                new FileWriter("D:\\idea_java\\velocity_01\\src\\main\\resources\\html\\05-instructions-set.html");
        // 合并+写入
        template.merge(context, fw);
        // 6,释放资源
        fw.close();
    }
} 
#if

image.png

<!-- 06-instructions-if.vm -->
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    #set($language="java")
    #if($language.equals("java"))
    JAVA开发工程师
    #elseif($language.equals("golang"))
    GO语言开发工程师
    #else
    开发工程师
    #end
</body>
</html> 
package org.malred; 
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.junit.Test;
import org.malred.pojo.User; 
import java.io.FileWriter;
import java.io.IOException;
import java.util.Date;
import java.util.Properties; 
public class VelocityTest {  
    @Test
    public void test6() throws IOException {
        // 1,设置velocity的资源加载器
        Properties prop = new Properties();
        prop.put("file.resource.loader.class",
                "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
        // 2,初始化velocity引擎
        Velocity.init(prop);
        // 3,创建velocity容器
        VelocityContext context = new VelocityContext();
        // 设置数据
        context.put("str", "hello world velocity !");
        // 4,加载velocity模板文件
        Template template = Velocity.getTemplate("vms/06-instructions-if.vm", "utf-8");
        // 5,合并数据到模板
        FileWriter fw =
                new FileWriter("D:\\idea_java\\velocity_01\\src\\main\\resources\\html\\06-instructions-if.html");
        // 合并+写入
        template.merge(context, fw);
        // 6,释放资源
        fw.close();
    }
} 
#foreach

image.png

<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport"
      content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
  </head>
  <body>
    <h1>遍历数组</h1>
    #foreach($hobby in $hobbies)
    ## 索引 --- 编号 --- 值
    $foreach.index --- $foreach.count --- $hobby
    #end
    <h1>遍历对象集合</h1>
    <table border="1px">
      <tr>
        <td>编号</td>
        <td>用户名</td>
        <td>邮箱</td>
        <td>密码</td>
        <td>操作</td>
      </tr>
      #foreach($user in $userList)
      <tr>
        <td>$foreach.count</td>
        <td>$user.username</td>
        <td>$user.email</td>
        <td>$user.password</td>
        <td>
          <a href="#">编辑</a>
          <a href="#">删除</a>
        </td>
      </tr>
      #end
    </table>
    <h1>遍历map集合</h1>
    <h2>遍历值</h2>
    #foreach($value in $map)
    $value
    #end
    <h2>遍历键值对</h2>
    #foreach($entry in $map.entrySet())
    $entry.key --- $entry.value
    #end
  </body>
</html> 
package org.malred; 
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.junit.Test;
import org.malred.pojo.User; 
import java.io.FileWriter;
import java.io.IOException;
import java.util.*; 
public class VelocityTest {  
    @Test
    public void test7() throws IOException {
    // 1,设置velocity的资源加载器
    Properties prop = new Properties();
    prop.put("file.resource.loader.class",
    "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
    // 2,初始化velocity引擎
    Velocity.init(prop);
    // 3,创建velocity容器
    VelocityContext context = new VelocityContext();
    // 设置数据
    // 数组
    String[] hobbies = new String[]{
    "eat", "drink", "play", "happy"
    };
    context.put("hobbies", hobbies);
    // list
    List<User> userList = new ArrayList<>();
    userList.add(new User("yangguo", "123456", "yg@qq.com"));
    userList.add(new User("xiaolongnv", "123456", "xln@qq.com"));
    userList.add(new User("huangrong", "123456", "hr@qq.com"));
    context.put("userList", userList);
    // map
    Map<String, Object> map = new HashMap<String, Object>();
    map.put("k1", "v1");
    map.put("k2", "v2");
    map.put("k3", "v3");
    context.put("map", map);
    // 4,加载velocity模板文件
    Template template = Velocity.getTemplate("vms/07-instructions-foreach.vm", "utf-8");
    // 5,合并数据到模板
    FileWriter fw =
    new FileWriter("D:\\idea_java\\velocity_01\\src\\main\\resources\\html\\07-instructions-foreach.html");
    // 合并+写入
    template.merge(context, fw);
    // 6,释放资源
    fw.close();
    }
}

引入资源

#include

image.png

<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport"
      content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
  </head>
  <body>
    ## 引入资源
    ## 使用相对路径时,以类加载器的路径为参考,则这里是以resources为根
    #include("vms/01-quickstart.vm")
  </body>
</html> 
package org.malred; 
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.malred.pojo.User; 
import java.io.FileWriter;
import java.util.*; 
public class VelocityTest {
    // 1,设置velocity的资源加载器
    Properties prop;
    FileWriter fw; 
    @Before
    public void before() throws Exception {
        prop = new Properties();
        prop.put("file.resource.loader.class",
                "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
    } 
    @After
    public void after() throws Exception {
        // 6,释放资源
        fw.close();
    } 
    public void run(VelocityContext context, String fileName) throws Exception {
        // 4,加载velocity模板文件
        Template template = Velocity.getTemplate("vms/" + fileName + ".vm", "utf-8");
        // 5,合并数据到模板
        fw = new FileWriter(
                "D:\\idea_java\\velocity_01\\src\\main\\resources\\html\\" + fileName + ".html");
        // 合并+写入
        template.merge(context, fw);
    }
    @Test
    public void test8() throws Exception {
        // 2,初始化velocity引擎
        Velocity.init(prop);
        // 3,创建velocity容器
        VelocityContext context = new VelocityContext();
        // 设置数据
        // 运行
        run(context,"08-reference-include");
    }
} 
#parse

image.png

<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport"
      content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
  </head>
  <body>
    ## 引入外部资源,并且会解析文件里的velocity语法
    #parse("vms/01-quickstart.vm")
  </body>
</html>
package org.malred; 
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.malred.pojo.User; 
import java.io.FileWriter;
import java.util.*; 
public class VelocityTest {
    // 1,设置velocity的资源加载器
    Properties prop;
    FileWriter fw;

    @Before
    public void before() throws Exception {
        prop = new Properties();
        prop.put("file.resource.loader.class",
                "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
    }

    @After
    public void after() throws Exception {
        // 6,释放资源
        fw.close();
    }

    public void run(VelocityContext context, String fileName) throws Exception {
        // 4,加载velocity模板文件
        Template template = Velocity.getTemplate("vms/" + fileName + ".vm", "utf-8");
        // 5,合并数据到模板
        fw = new FileWriter(
                "D:\\idea_java\\velocity_01\\src\\main\\resources\\html\\" + fileName + ".html");
        // 合并+写入
        template.merge(context, fw);
    }
    @Test
    public void test9() throws Exception {
        // 2,初始化velocity引擎
        Velocity.init(prop);
        // 3,创建velocity容器
        VelocityContext context = new VelocityContext();
        context.put("name", "velocity");
        // 设置数据
        // 运行
        run(context,"09-reference-parse");
    }
} 
#define

image.png

<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport"
      content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
  </head>
  <body>
    ## 定义重用模块(不能传入参数,一般用于封装静态html代码)
    #define($table)
    <table border="1px">
      <tr>
        <td>编号</td>
        <td>用户名</td>
        <td>邮箱</td>
        <td>密码</td>
        <td>操作</td>
      </tr>
      #foreach($user in $userList)
      <tr>
        <td>$foreach.count</td>
        <td>$user.username</td>
        <td>$user.email</td>
        <td>$user.password</td>
        <td>
          <a href="#">编辑</a>
          <a href="#">删除</a>
        </td>
      </tr>
      #end
    </table>
    #end
    ## 引用定义好的模块
    $table
    $table
    $table
    $table
  </body>
</html>
package org.malred; 
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.malred.pojo.User; 
import java.io.FileWriter;
import java.util.*; 
public class VelocityTest {
    // 1,设置velocity的资源加载器
    Properties prop;
    FileWriter fw;

    @Before
    public void before() throws Exception {
        prop = new Properties();
        prop.put("file.resource.loader.class",
                "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
    }

    @After
    public void after() throws Exception {
        // 6,释放资源
        fw.close();
    }

    public void run(VelocityContext context, String fileName) throws Exception {
        // 4,加载velocity模板文件
        Template template = Velocity.getTemplate("vms/" + fileName + ".vm", "utf-8");
        // 5,合并数据到模板
        fw = new FileWriter(
                "D:\\idea_java\\velocity_01\\src\\main\\resources\\html\\" + fileName + ".html");
        // 合并+写入
        template.merge(context, fw);
    }
    @Test
    public void test10() throws Exception {
        // 2,初始化velocity引擎
        Velocity.init(prop);
        // 3,创建velocity容器
        VelocityContext context = new VelocityContext();
        context.put("name", "velocity");
        // 设置数据
        // 运行
        run(context,"10-reference-define");
    }
} 
#evaluate

image.png

<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport"
      content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
  </head>
  <body>
    #set($language="java")
    ## 解析并使用velocity代码
    #evaluate($code)
  </body>
</html> 
@Test
public void test11() throws Exception {
        // 2,初始化velocity引擎
        Velocity.init(prop);
        // 3,创建velocity容器
        VelocityContext context = new VelocityContext();
        context.put("code", "#if($language.equals(\"java\"))\n" +
                "    JAVA开发工程师\n" +
                "    #elseif($language.equals(\"golang\"))\n" +
                "    GO语言开发工程师\n" +
                "    #else\n" +
                "    开发工程师\n" +
                "    #end");
        // 设置数据
        // 运行
        run(context, "11-reference-evaluate");
    }
宏指令

image.png

<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport"
      content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
  </head>
  <body>
    ## 定义重用模块,可带参
    #macro(table $list)
    <table border="1px">
      <tr>
        <td>编号</td>
        <td>用户名</td>
        <td>邮箱</td>
        <td>密码</td>
        <td>操作</td>
      </tr>
      #foreach($user in $list)
      <tr>
        <td>$foreach.count</td>
        <td>$user.username</td>
        <td>$user.email</td>
        <td>$user.password</td>
        <td>
          <a href="#">编辑</a>
          <a href="#">删除</a>
        </td>
      </tr>
      #end
    </table>
    #end
    ## 引用定义好的模块(引用宏用的是#)
    #table($userList)
  </body>
</html>
@Test
public void test12() throws Exception {
  // 2,初始化velocity引擎
  Velocity.init(prop);
  // 3,创建velocity容器
  VelocityContext context = new VelocityContext();
  List<User> userList = new ArrayList<>();
  userList.add(new User("yangguo", "123456", "yg@qq.com"));
  userList.add(new User("xiaolongnv", "123456", "xln@qq.com"));
  userList.add(new User("huangrong", "123456", "hr@qq.com"));
  context.put("userList", userList);
  // 设置数据
  // 运行
  run(context, "12-reference-macro");
}

综合案例

image.png

vm文件

package ${package}.dao;
import ${package}.pojo.${UpperFeignEntityName};
import org.springframework.data.jpa.repository.JpaRepository;
public interface ${UpperFeignEntityName}Dao extends JpaRepository<${UpperFeignEntityName},Long> { }
package ${package}.controller; ## package是全类名前面那段 如 ${package} 
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import ${package}.pojo.${upperEntityName}; ## 大写的实体类名
import ${package}.service.${entityName}ServiceFeignClient;
import ${package}.service.fallback.SentinelFallbackClass;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; 
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List; 
@RestController
@RequestMapping("/${entityName}") ## 一般使用实体名称(表名),这里是首字母小写
public class ${UpperFeignEntityName}Controller extends BaseController <${upperEntityName}> {

    @Override
    public List<${upperEntityName}> findAll() {
    return new ArrayList <${upperEntityName}>();
                           }

    @Override
        public ${upperEntityName} findById(Long id) {
        return new ${upperEntityName}();
    }

    @Override
        public ${upperEntityName} insert() {
        return new ${upperEntityName}();
    }

    @Override
        public ${upperEntityName} update() {
        return new ${upperEntityName}();
    }

    @Override
        public void delete(Long id) {
        }
                                                             } 
package ${package}.controller; ## package是全类名前面那段 如 ${package} 
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import ${package}.pojo.${upperEntityName}; ## 大写的实体类名
import ${package}.service.${upperEntityName}ServiceFeignClient;
import ${package}.service.fallback.SentinelFallbackClass;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; 
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List; 
@RestController
@RequestMapping("/${entityName}") ## 一般使用实体名称(表名),这里是首字母小写
public class ${UpperFeignEntityName}Controller extends BaseController <${upperEntityName}> {

    @Override
    public List<${upperEntityName}> findAll() {
        return new ArrayList <${upperEntityName}>();
   }

   @Override
   public ${upperEntityName} findById(Long id) {
       return new ${upperEntityName}();
   }

   @Override
   public ${upperEntityName} insert() {
   return new ${upperEntityName}();
   }

   @Override
   public ${upperEntityName} update() {
   return new ${upperEntityName}();
   }

   @Override
   public void delete(Long id) {
   }

   @Qualifier("${package}.service.${UpperFeignEntityName}ServiceFeignClient}") ## UpperFeignEntityName 远程调用的实体类名
   @Autowired
   private ${UpperFeignEntityName}ServiceFeignClient ${feignEntityName}ServiceFeignClient; ## feignEntityName 远程调用的实体类名,首字母小写

   @GetMapping("/feign/find/{id}")
   @SentinelResource(
   value = "find${UpperFeignEntityName}ById",
   blockHandlerClass = SentinelFallbackClass.class,
   blockHandler = "handleException", fallback = "handleError",
   fallbackClass = SentinelFallbackClass.class
   )
   public String find${UpperFeignEntityName}ById(@PathVariable Long id, HttpServletRequest request) {
   // 从路径获取token
   token = request.getQueryString();
   return ${feignEntityName}ServiceFeignClient.find${UpperFeignEntityName}ById(id);
   }
} 
package ${package}.service; 
import ${package}.pojo.${upperEntityName};
public interface ${upperEntityName}Service {
List<${upperEntityName}> findAll();
${upperEntityName} find${upperEntityName}ById(Long id);
${upperEntityName} save${upperEntityName}(${upperEntityName} ${entityName});
void delete${upperEntityName}(Long id);
} 
package ${package}.service.impl;  
import io.seata.spring.annotation.GlobalTransactional;
import ${package}.dao.${upperEntityName}Dao;
import ${package}.pojo.${upperEntityName};
import ${package}.service.${upperEntityName}Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service; 
@Service
    public class ${upperEntityName}ServiceImpl implements ${upperEntityName}Service {
    @Autowired
    private ${upperEntityName}Dao ${entityName}Dao; 
@Override
    @Cacheable(
        cacheNames = "${entityName}",
        // 如果结果为空就不缓存
        unless = "#result==null"
    )
    public ${upperEntityName} find${upperEntityName}ById(Long ${entityName}Id) {
    System.out.println("service接收路由参数: " + ${entityName}Id);
    ${upperEntityName} ${entityName} = new ${upperEntityName}();
${entityName}.setId(${entityName}Id);
  // 自动类型推断
  Example<? extends ${upperEntityName}> example = Example.of(${entityName});
                      return ${entityName}Dao.findOne(example).get();
                     }
  @Override
      @Cacheable(
          cacheNames = "${entityName}",
          // 如果结果为空就不缓存
          unless = "#result==null"
      )
      public ${upperEntityName} find${upperEntityName}ById(Long ${entityName}Id) {
    System.out.println("service接收路由参数: " + ${entityName}Id);
    ${upperEntityName} ${entityName} = new ${upperEntityName}();
${entityName}.setId(${entityName}Id);
  // 自动类型推断
  Example<? extends ${upperEntityName}> example = Example.of(${entityName});
                      return ${entityName}Dao.findOne(example).get();
                     }

  // 添加和更新方法(通过post和put的http请求来区分)
  @Override
      // 事务发起者使用@GlobalTransactional,其他参与者使用@Transactional
      @GlobalTransactional
      @CachePut(
          cacheNames = "${entityName}",
          // 将修改结果的id作为缓存的key
          key = "#result.id"
      )
      public ${upperEntityName} save${upperEntityName}(${upperEntityName} ${entityName}) {
    ${entityName}Dao.save(${entityName});
return ${entityName}; // 如果返回的是修改之后的(修改后会更新缓存),就是更新成功
}

// 删除方法
@Override
    @GlobalTransactional
    @CacheEvict(
        cacheNames = "${entityName}"
    )
    public void delete${upperEntityName}(Long id) {
    ${entityName}Dao.deleteById(id);
}
} 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

飞鸟malred

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值