April 8, 2020 SringBoot integrates velocity and common grammar

Project address: github.com/chywx/sprin ...

background

Because the company's business is oriented to the African market, some countries have not popularized smart phones. For example, Uganda still focuses on functional machines. In order to support functional machines, a new wapwebsite needs to be created to support functional machines (oh my god!)

Technical selection

Because the functional machine test does not support js, the use of vue in the front end is unrealistic. You can only use jsp, freemarker, Thymeleaf and other engines in the form of templates, but the final selection velocitytemplate (the boss has used it) Backend usespringboot

#Project simple architecture

#springbootintegrated velocity

Version selection

Select spring-boot-starter-velocity, the higher version of springboot does not support, only the lower version of 1.4.7

pom.xml add dependency

<dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter</artifactId>
    </dependency>

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-velocity</artifactId>
    </dependency>
复制代码

application.properties add configuration

server.port=2828
spring.velocity.cache=false
spring.velocity.charset=UTF-8
spring.velocity.check-template-location=true
spring.velocity.content-type=text/html
spring.velocity.enabled=true
spring.velocity.prefix=/templates/
spring.velocity.suffix=.vm
复制代码

Add demo test to controller layer

@Controller
@RequestMapping("/velocity")
public class TestController {

    // demo测试
    @RequestMapping("/demo")
    public String demo1(Map map) {
        map.put("message", "这是测试的内容。。。");
        map.put("time", System.currentTimeMillis());
        return "index";
    }
}
复制代码

new home index.vm under the templates folder

<html>
<body>
    $!{message}
    $!{time}
</body>
</html>
复制代码

Visit index page

http://localhost:2828/velocity/demo ok, the simplest springboot integration velocity is complete

Date and time processing

How to customize time format of time stamp

1. Add toolbox.xml

The content is as follows

<?xml version="1.0" encoding="UTF-8"?>
<toolbox>
  <tool>
    <key>DateTool</key>
    <scope>application</scope>
    <class>org.apache.velocity.tools.generic.DateTool</class>
  </tool>
</toolbox>
复制代码

Of course, if you need to deal with numbers or something, you can also introduce a tool

2. Specify the location of toolbox.xml

application.properties添加spring.velocity.toolbox-config-location=/toolbox.xml

3. Use in the vm page

<h1>日期处理</h1>
处理前:$time
<br>
处理后:$!DateTool.format($!time)
复制代码

Unified exception page handling

New VelocityExceptionHander

@ControllerAdvice
public class VelocityExceptionHander {

    @ExceptionHandler(value = Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public String exceptionHandler(Exception e, HttpServletRequest request) {
        System.out.println("未知异常!原因是:" + e);
        request.setAttribute("msg", e);
        return "500";
    }
}
复制代码

New 500.vm template page

<html>
<body>
error
<br>
    $!msg
</body>
</html>
复制代码

If an exception occurs afterwards, it will jump to page 500.

Finally, summarize the commonly used basic grammar tags

    // velocity常用语法汇总
    @RequestMapping("/allDemo")
    public String demo3(Map map) {
        map.put("amount", 100);
        map.put("msg", "dahai");
        map.put("sex", "man");
        putString(map);
        putSportList(map);
        map.put("time", System.currentTimeMillis());
        return "allDemo";
    }

    private void putSportList(Map map) {
        List<Sport> sportList = new ArrayList<Sport>() {{
            add(new Sport(1, "Football"));
            add(new Sport(2, "Basketball"));
            add(new Sport(3, "tennis"));
            add(new Sport(4, "rugby"));
            add(new Sport(5, "cricket"));
        }};
        map.put("sportList", sportList);
        Map<Integer, Sport> sportMap = sportList.stream().collect(Collectors.toMap(Sport::getId, s -> s));
        map.put("sportMap", sportMap);
    }

    private void putString(Map map) {
        List<String> strings = new ArrayList<>();
        strings.add("a");
        strings.add("b");
        strings.add("c");
        map.put("strings", strings);
    }
复制代码

vm template page

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <title>velocity test</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
</head>
<body>

<h1>字符串类型</h1>
    $!msg

<h1>if标签</h1>
    #if($!sex == 'man')#else#end

<h1>set操作(定义变量)</h1>
    #set($hw = 'ok')
    $hw

<h1>普通for循环</h1>
    #foreach($!s in $!strings)
        $s &nbsp;
    #end

<h1>对象for循环</h1>
    #foreach($!sport in $!sportList)
        $!sport.name &nbsp;
    #end

<h1>map for循环</h1>
    #foreach($!sp in $!sportMap.keySet())
        $sp &nbsp; $!sportMap.get($sp).name &nbsp;<br>
    #end

<h1>日期处理</h1>

处理前:$time
<br>
处理后:$!DateTool.format($!time)

<h1>计算加减乘除</h1>

    #set($jia = $amount + 10)
+10= $jia   <br>
    #set($jian = $amount - 10)
-10= $jian  <br>
    #set($cheng = $amount * 10)
×10= $cheng <br>
    #set($chu = $amount / 10)
÷10= $chu   <br>


</body>
</html>
复制代码

ok, finished! Re-warm the familiar and unfamiliar front-end and back-end without separation (server rendering) project, ؏؏☝ᖗ 乛 ◡ 乛 ᖘ☝؏؏

Guess you like

Origin juejin.im/post/5ea0faf4f265da47eb05b489