servlet +thymeleaf渲染引擎

发布时间:2023年12月23日

servlet +thymeleaf渲染引擎

一、maven坐标

<dependency>
  <groupId>org.thymeleaf</groupId>
  <artifactId>thymeleaf</artifactId>
  <version>3.0.12.RELEASE</version> <!-- 使用适当的Thymeleaf版本 -->
</dependency>
<dependency>
  <groupId>javax.servlet</groupId>
  <artifactId>javax.servlet-api</artifactId>
  <version>4.0.1</version> <!-- 使用适当的Servlet API版本 -->
  <scope>provided</scope>
</dependency>

二、web.xml配置

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>
  <!-- 在servletContext中配置上下文参数 -->
  <context-param>
    <param-name>view-prefix</param-name>
    <param-value>/WEB-INF/templates/</param-value>
  </context-param>
  <context-param>
    <param-name>view-suffix</param-name>
    <param-value>.html</param-value>
  </context-param>

</web-app>

二、BaseServlet

import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.WebContext;
import org.thymeleaf.templatemode.TemplateMode;
import org.thymeleaf.templateresolver.ServletContextTemplateResolver;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class ViewBaseServlet extends HttpServlet {

    private TemplateEngine templateEngine;

    @Override
    public void init() throws ServletException {

        // 1.获取ServletContext对象
        ServletContext servletContext = this.getServletContext();

        // 2.创建Thymeleaf解析器对象
        ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver(servletContext);

        // 3.给解析器对象设置参数
        // ①HTML是默认模式,明确设置是为了代码更容易理解
        templateResolver.setTemplateMode(TemplateMode.HTML);

        // ②设置前缀
        String viewPrefix = servletContext.getInitParameter("view-prefix");

        templateResolver.setPrefix(viewPrefix);

        // ③设置后缀
        String viewSuffix = servletContext.getInitParameter("view-suffix");

        templateResolver.setSuffix(viewSuffix);

        // ④设置缓存过期时间(毫秒)
        templateResolver.setCacheTTLMs(60000L);

        // ⑤设置是否缓存
        templateResolver.setCacheable(true);

        // ⑥设置服务器端编码方式
        templateResolver.setCharacterEncoding("utf-8");

        // 4.创建模板引擎对象
        templateEngine = new TemplateEngine();

        // 5.给模板引擎对象设置模板解析器
        templateEngine.setTemplateResolver(templateResolver);

    }

    protected void processTemplate(String templateName, HttpServletRequest req, HttpServletResponse resp) throws IOException {
        // 1.设置响应体内容类型和字符集
        resp.setContentType("text/html;charset=UTF-8");

        // 2.创建WebContext对象
        WebContext webContext = new WebContext(req, resp, getServletContext());

        // 3.处理模板数据
        templateEngine.process(templateName, webContext, resp.getWriter());
    }
}

四、demoServlet

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/testservelt")
public class testservlet  extends  ViewBaseServlet{

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, IOException {
         HttpSession httpSession= req.getSession();
        List list=new ArrayList();
        list.add("战神");
        list.add("艾尔登法环");
        list.add("卧龙苍天陨落");
        list.add("霍格沃茨:遗产");
        httpSession.setAttribute("list",list);
        super.processTemplate("testservlet",req,resp);
    }
}

五、html页面

<!DOCTYPE html>
<!--在页面上外部导入thymeleaf-->
<html xmlns:th="http://www.thymeleaf.org">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
  <style>
    table {
      border-collapse: collapse;
    }

    table, td, th {
      border: 1px solid black;
    }

    #gameid {
      margin: 12px auto;
      collapse: 1px;
    }

    td {
      text-align: center;
      width: 160px;
    }
  </style>
</head>
<body>
<table id="gameid">
  <tr>
    <th class="w20">游戏名</th>
    <th>操作</th>
  </tr>
  <tr th:if="${#lists.isEmpty(session.list)}">
    <td colspan="4">对不起,库存为空!</td>
  </tr>
  <tr th:unless="${#lists.isEmpty(session.list)}" th:each="gamename : ${session.list}">

    <td><a th:text="${gamename}" href="#">默认没有如果不是通过服务器启动,就显示这个文本</a></td>

    <td><a th:text="购买" href="#">默认没有如果不是通过服务器启动,就显示这个文本</a></td>
  </tr>
</table>
</body>
</html>

引用地址:

https://blog.csdn.net/u011863822/article/details/129747818?ops_request_misc=&request_id=&biz_id=102&utm_term=javaweb%E9%A1%B9%E7%9B%AE%E4%BD%BF%E7%94%A8thymleaf&utm_medium=distribute.pc_search_result.none-task-blog-2allsobaiduweb~default-0-129747818.142v96pc_search_result_base9&spm=1018.2226.3001.4187

文章来源:https://blog.csdn.net/weixin_52236586/article/details/135173033
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。