Java集成thymeleaf视图层模板引擎构建web项目实例讲解(附项目源码)_thymeleaf+servlet项目源码-程序员宅基地

技术标签: java  spring mvc  servlet  模板引擎  thymeleaf  

我们提供一个Java使用Thymeleaf的简单示例。Thymeleaf是一个模板引擎可以处理XML,XHTML、HTML5。Thymeleaf利用最少的IO操作来获得更快的速度,使用thymeleaf模板引擎加快了前后端开发工作的并行运作。Thymeleaf还提供了国际化。Thymeleaf提供了最基础的两个编程API:ServletContextTemplateResolver 和TemplateEngine。Servletcontexttemplateresolver负责解析模板、Templateengine使用templateengine process()方法处理模板数据。模板引擎表达式可以从properties文件和WebContext获取属性值从而展示到页面。需要注意的是:属性文件、模板文件必须同名且位于同一目录(编译后)。

使用servlet3.0注解报会在访问时报404错误,解决方案如下web.xml文件头如下配置:

<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> 

Java+Thymeleaf示例程序的准备工作

(本文章分享在CSDN平台,更多精彩请阅读 东陆之滇的csdn博客:http://blog.csdn.net/zixiao217 ,如在其他平台看到此文可能会出现内容不完整的现象,请移至东陆之滇http://blog.csdn.net/zixiao217查看原文)

  • Java 8
  • Thymeleaf
  • Servlet 3
  • Tomcat 8
  • Maven
  • Eclipse

示例程序的目录结构

这里写图片描述

pom.xml

<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.byron4j</groupId>
    <artifactId>java2Thymeleaf</artifactId>
    <version>1.0.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>java2Thymeleaf</name>
    <url>http://blog.csdn.net/zixiao217/article/details/52723437</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.0.1</version>
            <scope>provided</scope>
        </dependency>



        <dependency>
            <groupId>org.thymeleaf</groupId>
            <artifactId>thymeleaf-spring4</artifactId>
            <version>2.1.5.RELEASE</version>
        </dependency>
    </dependencies>



    <build>
        <finalName>thymeDemo</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.5.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <!-- <compilerArguments> <extdirs>lib</extdirs> </compilerArguments> -->
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

使用th:text外化文本

打开我们的模板文件WEB-INF\templates\welcome.html,如果我们直接访问该html文件,则会显示”Welcome Offline”,当我们通过服务启动之后访问url则显示从后台获得的属性值。

注意:在模板文件中需要声明thymeleaf的文档类型、xml命名空间,WEB-INF\templates\welcome.html

<!DOCTYPE html SYSTEM "http://www.thymeleaf.org/dtd/xhtml1-strict-thymeleaf-4.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
  <head>
    <title>Thymeleaf-Java Demo</title>
    <meta http-equiv="Content-Type" content="text/html;charset=UTF8" />
  </head>
  <body>
    <p th:text="#{welcome.msg}">喂,掉线了丿_|</p>
    <p>Date : <span th:text="${currentDate}">1990-01-01 00:00:00</span></p>
  </body>
</html> 

th:text: 该属性用来计算表达式的值,并将结果展示为标签的内容
#{…}: 从属性文件获得该属性的值。 表达式#{welcome.msg} 会尝试获得属性文件中key为welcome.msg的value。
${…}: OGNL表达式 会获取在org.thymeleaf.context.WebContext中设置的值。在这个Demo中表达式${currentDate} 将会获取在WebContext中设置的currentDate 属性值。

ServletContextTemplateResolver 解析模板和TemplateEngine.process()处理模板

ThymeleafAppUtil.java

package org.byron4j.java2Thymeleaf;

import org.thymeleaf.TemplateEngine;
import org.thymeleaf.templateresolver.ServletContextTemplateResolver;


/**
 *  @author     Byron.Y.Y
 *  @optDate    2016年11月15日
 *  Thymeleaf模板引擎和解析器
 */
public class ThymeleafAppUtil {
    

    private static TemplateEngine templateEngine;

    /**
     * static代码块,加载初始模板设置:/WEB-INF/templates/**.html文件
     */
    static {
        ServletContextTemplateResolver templateResolver = 
                new ServletContextTemplateResolver();
        templateResolver.setTemplateMode("XHTML");
        templateResolver.setPrefix("/WEB-INF/templates/");
        templateResolver.setSuffix(".html");
        templateResolver.setCacheTTLMs(3600000L);
        templateEngine = new TemplateEngine();
        templateEngine.setTemplateResolver(templateResolver);
    }

    public static TemplateEngine getTemplateEngine() {
     return templateEngine;
    }

}

ServletContextTemplateResolver: 负责解析Thymeleaf模板。我们需要设置模板模式、模板文件的前缀、后缀等。
TemplateEngine: 处理thymeleaf模板。

属性文件

属性文件、模板文件必须同名且放在一个目录中(项目编译后)
WEB-INF\templates\welcome_en.properties

welcome.msg=Welcome to Thymeleaf World!

WEB-INF\templates\welcome_zh.properties

welcome.msg=欢迎使用 Thymeleaf!

Servlet类

WelcomeServlet.java

package org.byron4j.java2Thymeleaf;

import java.io.IOException;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *  @author     Byron.Y.Y
 *  @optDate    2016年11月15日
 *  使用servlet3注解,注册一个servlet,并在容器启动时加载
 */
@WebServlet(urlPatterns = "/welcome", loadOnStartup = 1)
public class WelcomeServlet extends HttpServlet {
    

    private static final long serialVersionUID = 1L;

    //POST请求
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException{
            doGet(request,response);
    }

    //GET请求
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException{
        response.setContentType("text/html;charset=UTF-8");
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        WelcomeApplication application = new WelcomeApplication();
        application.process(request, response);
    }
} 

WelcomeApplication.java

package org.byron4j.java2Thymeleaf;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.thymeleaf.context.WebContext;

public class WelcomeApplication {
    
    public void process(HttpServletRequest request, HttpServletResponse response) 
         throws IOException {
        WebContext ctx = new WebContext(request, response, request.getServletContext(),
                request.getLocale());
        ctx.setVariable("currentDate", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));

        /**
         * 使用Thymeleaf引擎加载模板文件welcome.html
         */
        ThymeleafAppUtil.getTemplateEngine().process("welcome", ctx, response.getWriter());
    }
}

web.xml

声明使用了servlet3,eclipse默认生成的web.xml使用的是servlet2.3、2.5,我们需要手动指定为servlet3,运用servlet3.0注解报会在访问时报404错误。

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> 

  <display-name>Archetype Created Web Application</display-name>
</web-app>

运行结果:
这里写图片描述

完整的Demo Maven工程代码

演示项目源码下载 http://download.csdn.net/detail/zixiao217/9684984

Thymeleaf+Java Demo演示项目源码

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/zixiao217/article/details/53191659

智能推荐

C++ :error C3872: '0x3000': this character is not allowed in an identifier 包含中文全角空格错误【已解决】_character <u+ff08> not allowed in an identifier-程序员宅基地

文章浏览阅读870次。error C3872: ‘0x3000’: this character is not allowed in an identifier写的serialdll.cpp文件中报错如下,一大堆错误,但是反复查看了那几行代码,甚至重新写了一遍,还是报错。在网上帖子说可能是代码中有中文的全角空格,导致报错。但使用Ctrl + H查找当前的cpp文件,完全没有找到中文全角空格;继续排查原因,发现..._character not allowed in an identifier

解决Mac下MX4手机无法连接adb问题之解决方案-程序员宅基地

文章浏览阅读46次。一般的android连接mac 很方便不用安装驱动就可以啦,可是不知道为什么特殊情况下有的android手机(小米2,华为等)就是连接不上,下来就说说特殊情况下如何连接。使用USB连接安卓手机后可以做2件事情:1.关于本机-->更多信息->概系统览->系统报告->usb->你所连接的device-->供应商ID(Vendor ID)2..打开终端,输..._macpro adb连接mix4

老花眼:男女的“更年期”-程序员宅基地

文章浏览阅读671次。What do you think, how many operations can be done on one eye? A clinical case of one of my patients confirms that more than 20 operations of various kinds are not the limit. Although, no doubt, thi..._更年期 眼压高

MongoDB索引详解_mongodb索引的数据结构-程序员宅基地

文章浏览阅读1.2k次,点赞15次,收藏9次。MongoDB索引详解_mongodb索引的数据结构

SWAN之ikev2/acert-inline测试_ikev2测试向量-程序员宅基地

文章浏览阅读369次。本测试中远程用户(roadwarrior)carol和dave与网关moon建立连接。认证方式基于X.509证书,为了对远程用户进行授权,moon网关期望用户在IKEv2报文的CERT载荷中带有属性证书。carol主机具有合法的证书,但是dave提供的是两个无效属性证书:一个证书不是用于sales组;另外一个是由已过期的AA所签发。以下启动ikev2/acert-inline测试用例,注意在启动..._ikev2测试向量

威雅学校:2024威雅校友英国首聚!共同编织校友网络,共创威雅美好未来-程序员宅基地

文章浏览阅读826次,点赞24次,收藏20次。校长先生还表示:“孩子们的热情和激情充分证明了在常州威雅求学之际所获得的人生观和价值观,影响是十分深远的,我很高兴地得知他们充分拥抱了‘终身学习’的教育理念,很高兴地听到他们计划在不久的将来创立自己的企业,学习更多的语言,继续开展研究生阶段的学习,或申请攻读博士。我们可以确信——这群杰出的年轻人一定会拥有无比光明的未来,尤其在看到他们可以在不同的语言之间自如地转换,比如与服务员用粤语交谈,用普通话谈论菜肴的可口和美味,随即迅速转换为英语,描述目前的住宿情况和个人烹饪技能的时候。

随便推点

微信小程序蓝牙功能_微信小程序蓝牙连接成功之后-程序员宅基地

文章浏览阅读1.3k次,点赞4次,收藏10次。wx.openSetting(Object object) | 微信开放文档 (qq.com)微信官方文档小程序相关API。_微信小程序蓝牙连接成功之后

【Unity3D小技巧】Unity3D中Animation和Animator动画的播放、暂停、倒放控制_unity 动画倒放-程序员宅基地

文章浏览阅读1.6w次,点赞23次,收藏116次。在日常开发中,常常会遇到要控制动画的播放、暂停和倒放的情况。这篇文章就总结一下,Animation和Animator动画播放系统的控制播放、暂停、倒放的代码。首先,来了解一下Animation和Animator的区别和联系。_unity 动画倒放

vue + el-calendar 日历考勤对接后台数据_el-calendar跟后台返回数据结合-程序员宅基地

文章浏览阅读999次。HTML部分<template> <div class="container"> <!-- <el-row> <el-col :span="24" style="margin-bottom: 20px;text-align: right;"> <el-date-picker v-model="queryParams.month" type="month" placeholder="请选择月份" valu_el-calendar跟后台返回数据结合

(Java)面向对象编程六大基本原则_java 面向对象 6大原则 详解-程序员宅基地

文章浏览阅读1.9k次。《Android源码设计模式解析与实战》面向对象六大原则_java 面向对象 6大原则 详解

关于Word中使用公式3.0编辑的中括号无法完全显示的解决办法_word中括号公式显示不完全-程序员宅基地

文章浏览阅读5.1k次,点赞6次,收藏5次。在Word中,使用公式编辑器3.0输入中括号的时候,会出现中括号的上半部分没办法完全显示的问题,也就是下图所示的情况。至于为什么会出现这个情况,我也不清楚,以前在打公式的时候基本上没出现过,后来慢慢出现了,网上有说改行距的,我试过了,这是公式本身的尺寸限制,改行距不可以,如果在Word里面显示不了的话,打印出来肯定也是不行的,现在说明一种能解决这个问题的方法。1. 双击公式,进入公..._word中括号公式显示不完全

滤除50HZ工频干的滤波电路及其仿真_50hz工频干扰的消除电路-程序员宅基地

文章浏览阅读6.1k次,点赞4次,收藏28次。工频干扰:工频干扰是由电力系统引起的50HZ的正弦波对测量过程的干扰。实现对50HZ正弦波的滤波可以采用带阻滤波器(陷波器),电路图及其交流分析如下:仿真电路图:仿真效果图:..._50hz工频干扰的消除电路

推荐文章

热门文章

相关标签