• SringBoot整合velocity及常用语法


    项目地址:https://github.com/chywx/springboot-velocity

    背景

    由于公司业务面向的是非洲市场
    那边有些国家智能机并未普及,像乌干达地区还是以功能机为主
    为了支持功能机,需要新创一个wap网站用于支持功能机(天哪!)

    技术选型

    由于功能机试不支持js的,前端使用vue不现实,只能通过模板的形式
    可以使用jsp,freemarker,Thymeleaf等引擎,但最终选型velocity模板(老大用过罢了)
    后端使用springboot

    项目简单架构

    springboot整合velocity

    版本选择

    选择spring-boot-starter-velocity,高版本的springboot不支持,只能选用低版本的1.4.7

    pom.xml添加依赖

    <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添加配置

    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
    

    controller器层添加demo测试

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

    templates文件夹下新家index.vm

    <html>
    <body>
        $!{message}
        $!{time}
    </body>
    </html>
    

    访问index页面

    http://localhost:2828/velocity/demo
    ok,最简单的springboot整合velocity完毕

    日期时间处理

    如何将时间戳自定义时间格式呢

    1. 添加toolbox.xml

    内容如下

    <?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>
    

    当然,如果需要处理数字啥的,也可以引入一个tool即可

    2. 指定toolbox.xml的位置

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

    3. 在vm页面中使用

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

    统一异常页面处理

    新建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";
        }
    }
    

    新建500.vm模板页面

    <html>
    <body>
    error
    <br>
        $!msg
    </body>
    </html>
    

    之后如果出现异常,会跳转到500页面。

    最后总结下常用的基础语法标签

        // 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模板页面

    <!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,完毕!重新温馨下熟悉而又陌生的前后端不分离(服务端渲染)的工程,؏؏☝ᖗ乛◡乛ᖘ☝؏؏

  • 相关阅读:
    洛谷 P4861 按钮
    《情人》
    bzoj1019: [SHOI2008]汉诺塔(dp)
    hdu5698瞬间移动(组合数,逆元)
    poj Code(组合数)
    组合数 牛顿二项式定理 杨辉三角
    8.22 NOIP 模拟题
    codevs2495 水叮当的舞步(IDA*)
    codevs 2541 幂运算(迭代加深搜索)
    较复杂搜索,剪枝
  • 原文地址:https://www.cnblogs.com/chywx/p/12657886.html
Copyright © 2020-2023  润新知