• 在雅加达EE服务中使用Thymeleaf


    在本教程中,我将向您展示如何将百里叶与雅加达 EE Servlet 集成,以替换在雅加达 EE Servlet 应用程序中使用 JSP。

    首先,我将创建一个新的雅加达 EE Servlet Maven 项目作为示例:

    百里叶依赖性如下:

    1
    2
    3
    4
    5
      org.thymeleaf
      thymeleaf
      3.1.0.M1

    我将创建一个新的 Servlet 来处理来自用户的请求:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    package com.huongdanjava.jakartaee.servlet;
     
    import jakarta.servlet.ServletException;
    import jakarta.servlet.annotation.WebServlet;
    import jakarta.servlet.http.HttpServlet;
    import jakarta.servlet.http.HttpServletRequest;
    import jakarta.servlet.http.HttpServletResponse;
    import java.io.IOException;
     
    @WebServlet("/")
    public class IndexServlet extends HttpServlet {
     
      @Override
      protected void doGet(HttpServletRequest req, HttpServletResponse resp)
          throws ServletException, IOException {
        super.doGet(req, resp);
      }
    }

    在上面的索引服务器的 doGet() 方法中,我们将使用百里叶的模板引擎对象来处理请求的响应。

    为此,首先,我们需要有模板引擎对象。但是要具有模板引擎对象,我们需要 ITemplateResolver 接口的对象来配置模板文件的位置。

    ITemplateResolver 接口有许多实现,可以通过不同的方式将位置配置为模板文件:

    我将使用 Web 应用程序模板解决方案作为本教程的示例:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    private WebApplicationTemplateResolver templateResolver(IWebApplication application) {
      WebApplicationTemplateResolver templateResolver = new WebApplicationTemplateResolver(application);
     
      // HTML is the default mode, but we will set it anyway for better understanding of code
      templateResolver.setTemplateMode(TemplateMode.HTML);
      // This will convert "home" to "/WEB-INF/templates/home.html"
      templateResolver.setPrefix("/WEB-INF/templates/");
      templateResolver.setSuffix(".html");
      // Set template cache TTL to 1 hour. If not set, entries would live in cache until expelled by LRU
      templateResolver.setCacheTTLMs(Long.valueOf(3600000L));
     
      // Cache is set to true by default. Set to false if you want templates to be automatically updated when modified.
      templateResolver.setCacheable(true);
     
      return templateResolver;
    }

    现在,您可以实例化模板引擎对象:

    1
    2
    3
    4
    5
    6
    7
    8
    private ITemplateEngine templateEngine(IWebApplication application) {
      TemplateEngine templateEngine = new TemplateEngine();
     
      WebApplicationTemplateResolver templateResolver = templateResolver(application);
      templateEngine.setTemplateResolver(templateResolver);
     
      return templateEngine;
    }

    您需要在应用程序启动并运行后立即将百合饼的模板引擎对象注册到 ServletContext 中。我们将使用 Servlet 上下文侦听器来执行此操作,如下所示:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    package com.huongdanjava.jakartaee.servlet;
     
    import jakarta.servlet.ServletContextEvent;
    import jakarta.servlet.ServletContextListener;
    import jakarta.servlet.annotation.WebListener;
    import org.thymeleaf.ITemplateEngine;
    import org.thymeleaf.TemplateEngine;
    import org.thymeleaf.templatemode.TemplateMode;
    import org.thymeleaf.templateresolver.WebApplicationTemplateResolver;
    import org.thymeleaf.web.IWebApplication;
    import org.thymeleaf.web.servlet.JakartaServletWebApplication;
     
    @WebListener
    public class ThymeleafConfiguration implements ServletContextListener {
     
      public static final String TEMPLATE_ENGINE_ATTR = "com.huongdanjava.thymeleaf.TemplateEngineInstance";
     
      private ITemplateEngine templateEngine;
     
      private JakartaServletWebApplication application;
     
      @Override
      public void contextInitialized(ServletContextEvent sce) {
        this.application = JakartaServletWebApplication.buildApplication(sce.getServletContext());
        this.templateEngine = templateEngine(this.application);
     
        sce.getServletContext().setAttribute(TEMPLATE_ENGINE_ATTR, templateEngine);
      }
     
      private ITemplateEngine templateEngine(IWebApplication application) {
        TemplateEngine templateEngine = new TemplateEngine();
     
        WebApplicationTemplateResolver templateResolver = templateResolver(application);
        templateEngine.setTemplateResolver(templateResolver);
     
        return templateEngine;
      }
     
      private WebApplicationTemplateResolver templateResolver(IWebApplication application) {
        WebApplicationTemplateResolver templateResolver = new WebApplicationTemplateResolver(application);
     
        // HTML is the default mode, but we will set it anyway for better understanding of code
        templateResolver.setTemplateMode(TemplateMode.HTML);
        // This will convert "home" to "/WEB-INF/templates/home.html"
        templateResolver.setPrefix("/WEB-INF/templates/");
        templateResolver.setSuffix(".html");
        // Set template cache TTL to 1 hour. If not set, entries would live in cache until expelled by LRU
        templateResolver.setCacheTTLMs(Long.valueOf(3600000L));
     
        // Cache is set to true by default. Set to false if you want templates to be automatically updated when modified.
        templateResolver.setCacheable(true);
     
        return templateResolver;
      }
     
      @Override
      public void contextDestroyed(ServletContextEvent sce) {
        // NOP
      }
    }

    如您所见,我们将此模板引擎对象保存到 ServletContext 中,以便每次请求进入应用程序时,我们都会检索它并处理该请求的响应。

    现在,我将修改上面的 servlet 以获取和使用模板引擎,如下所示:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    package com.huongdanjava.jakartaee.servlet;
     
    import jakarta.servlet.ServletException;
    import jakarta.servlet.annotation.WebServlet;
    import jakarta.servlet.http.HttpServlet;
    import jakarta.servlet.http.HttpServletRequest;
    import jakarta.servlet.http.HttpServletResponse;
    import java.io.IOException;
    import org.thymeleaf.TemplateEngine;
    import org.thymeleaf.context.WebContext;
    import org.thymeleaf.web.IWebExchange;
    import org.thymeleaf.web.servlet.JakartaServletWebApplication;
     
    @WebServlet("/")
    public class IndexServlet extends HttpServlet {
     
      @Override
      protected void doGet(HttpServletRequest req, HttpServletResponse resp)
          throws ServletException, IOException {
        TemplateEngine templateEngine = (TemplateEngine) getServletContext().getAttribute(
            ThymeleafConfiguration.TEMPLATE_ENGINE_ATTR);
     
        IWebExchange webExchange = JakartaServletWebApplication.buildApplication(getServletContext())
            .buildExchange(req, resp);
     
        WebContext context = new WebContext(webExchange);
     
        context.setVariable("name", "Huong Dan Java");
     
        templateEngine.process("home", context, resp.getWriter());
      }
    }

    模板引擎对象的进程() 方法将处理应用程序的响应。此方法的参数包括模板名称、从当前 servlet 的请求和响应构建的 WebContext 对象、从当前 servlet 的响应中将响应写入用户的 Writer 对象。

    主.html文件在目录/主目录/网络应用目录下,目录下文件的内容如下:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    xmlns:th="http://www.thymeleaf.org">
      </span><span style="color:#000000;">Home</span><span style="color:#800080;">

      Hello world
     

    from !

    删除 src/主/webapp/WEB-INF/ 目录中的 web.xml文件(因为我们使用的是@WebServlet注释)和 src/主/webapp/ 目录中的索引.jsp文件,然后运行应用程序,您将看到以下结果:

    完整pom.xml
    1. "1.0" encoding="UTF-8"?>
    2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    4. <modelVersion>4.0.0modelVersion>
    5. <groupId>LearnJSPServletgroupId>
    6. <artifactId>jakartaee-servlet-thymeleafartifactId>
    7. <version>0.0.1-SNAPSHOTversion>
    8. <packaging>warpackaging>
    9. <name>jjakartaee-servlet-thymeleaf Maven Webappname>
    10. <url>http://www.example.comurl>
    11. <properties>
    12. <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
    13. <maven.compiler.source>1.7maven.compiler.source>
    14. <maven.compiler.target>1.7maven.compiler.target>
    15. properties>
    16. <dependencies>
    17. <dependency>
    18. <groupId>jakarta.servletgroupId>
    19. <artifactId>jakarta.servlet-apiartifactId>
    20. <version>6.0.0version>
    21. <scope>providedscope>
    22. dependency>
    23. <dependency>
    24. <groupId>org.thymeleafgroupId>
    25. <artifactId>thymeleafartifactId>
    26. <version>3.1.0.M1version>
    27. dependency>
    28. <dependency>
    29. <groupId>junitgroupId>
    30. <artifactId>junitartifactId>
    31. <version>4.11version>
    32. <scope>testscope>
    33. dependency>
    34. dependencies>
    35. <build>
    36. <finalName>jakartaee8finalName>
    37. <pluginManagement>
    38. <plugins>
    39. <plugin>
    40. <artifactId>maven-clean-pluginartifactId>
    41. <version>3.1.0version>
    42. plugin>
    43. <plugin>
    44. <artifactId>maven-resources-pluginartifactId>
    45. <version>3.0.2version>
    46. plugin>
    47. <plugin>
    48. <artifactId>maven-compiler-pluginartifactId>
    49. <version>3.8.0version>
    50. plugin>
    51. <plugin>
    52. <artifactId>maven-surefire-pluginartifactId>
    53. <version>2.22.1version>
    54. plugin>
    55. <plugin>
    56. <artifactId>maven-war-pluginartifactId>
    57. <version>3.2.2version>
    58. plugin>
    59. <plugin>
    60. <artifactId>maven-install-pluginartifactId>
    61. <version>2.5.2version>
    62. plugin>
    63. <plugin>
    64. <artifactId>maven-deploy-pluginartifactId>
    65. <version>2.8.2version>
    66. plugin>
    67. plugins>
    68. pluginManagement>
    69. build>
    70. project>

    需要Tomcat 10运行。

  • 相关阅读:
    第十三章 实现组件库按需引入功能
    Linux企业应用——Docker(一)之初步了解Docker以及Docker的安装
    3D模型轻量化:无损精度和细节,轻量化处理3D模型的云原生工具
    EOS密钥被盗后如何恢复?
    关于WebMvcConfigurer
    PLC可以连接哪些工业设备实现远距离无线通讯?工业网关可以吗?
    短视频矩阵系统源代码开发搭建分享--代码开源SaaS
    Go Web——简单blog项目(二)
    IE退役倒计时, Edge接棒
    SpringMVC_拦截器
  • 原文地址:https://blog.csdn.net/allway2/article/details/127444341