当前位置:网站首页>Thymeleafengine template engine

Thymeleafengine template engine

2022-06-11 05:54:00 Tyrannosaurus Rex skeleton takes the dodo

Catalog

How to render dynamic pages

Server render

Client rendering

String splicing HTML

Using a template engine

Template engine usage process

Thymeleaf Template syntax

Create only one engine instance

What is? ServletContext

What is a monitor Listener

modify Thymeleaf Engine initialization code


How to render dynamic pages

The dynamic page needs to pass through the server according to the parameters passed by the client , Some results are obtained by dynamic calculation , And display these results on the page .

Server render

The combination of data and pages , Through the server .

Client rendering

The server returns the data to the browser , The browser combines the data with the page .

The data between browser and server often interact through ajax Conduct , The format of data is often JSON.

String splicing HTML

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

@WebServlet("/html")
public class HtmlServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        // A request came from query string, One of the parameters is name, In the returned page , That's it name Value , Requested name Different , The returned page is different 
        String name = req.getParameter("name");
        resp.getWriter().write("<h3>"+name+"</h3");
    }
}

If it is to return to a simple page , You can splice strings in the above way .

But if it's a complex page , It's time to write complex code

Using a template engine

Template engine usage process

adopt maven Introduce dependencies

choice 3.0.12 edition

establish HTML Template file

hello.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>thymeleaf</title>
</head>
<body>
    <!--th Namely thymeleaf Abbreviation , Indicates that this attribute is thymeleaf Class provides the ,text The representation type is string -->
    <h3 th:text="${message}"></h3>
</body>
</html>

To write Servlet Code

helloThymeleafServlet.java

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

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

@WebServlet("/helloThymeleaf")
public class HelloThymeleafServlet extends HttpServlet {
    // This is a Thymeleaf The core class in  TemplateEngine template engine 
    private TemplateEngine engine = new TemplateEngine();

    @Override
    public void init() throws ServletException {
        // Create a template parser object , Use with context 
        ServletContextTemplateResolver resolver = new ServletContextTemplateResolver(this.getServletContext());
        // Let the template parser load the template file , The prefix here indicates the directory where the template file is located , Because of that , The template file must be placed in WEB-INF in 
        // Set prefix and suffix , Let the template engine know which files to load into memory , For later use 
        resolver.setPrefix("/WEB-INF/template/");
        resolver.setSuffix(".html");
        resolver.setCharacterEncoding("utf-8");
        // Put the parser object , Set to engine in 
        engine.setTemplateResolver(resolver);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // After initialization , You are about to perform template rendering 
        //1. First, read out the data to be transmitted by the user from the parameters message Value 
        String message = req.getParameter("message");
        //2. Read the current request message The values in the template and ${message} Connect 
        WebContext webContext = new WebContext(req,resp,this.getServletContext());
        webContext.setVariable("message",message);
        //3. For final rendering , take webContext Replace the contents of with hello
        String html = engine.process("hello",webContext);
        System.out.println(html);
        resp.getWriter().write(html);
    }
}

The deployment process

You can see

Thymeleaf Template syntax

Text labels

th:text Its function is to set the text content of the label .

Set tag properties

Some common properties that need to be set :href src class style ......

<a th:href="${url1}"> Baidu </a>
<a th:href="${url2}"> sogou </a>

conditional

th:if The function of is to determine whether the label is displayed according to conditions .

<div th:if="${!newGame}">
    <div> Already guessed : <span th:text="${count}"></span>  Time </div>
    <div> result : <span th:text="${result}"></span> </div>
</div>

loop

th:each Its function is to construct multiple elements circularly .

stay java The code uses classes to store person, use list Storage presons

<ul>
    <li th:each="person : ${persons}">
        <span th:text="${person.name}"></span>
        <span th:text="${person.phone}"></span>
    </li>
</ul>

View the error message of the template syntax

Render the template with the following code , If the template renders incorrectly , You can see that the server returns 500 Status code , But you can't see the exception call stack .

engine.process("thymeleafEach", webContext, resp.getWriter());

The reason is that the exception thrown is process Internally disposed of .

Instead of , You can see the exception call stack .

String html = engine.process("thymeleafEach", webContext);
resp.getWriter().write(html);

Create only one engine instance

What is? ServletContext

It's to make webapp The multiple Servlet Can share data between

First visit writer, to message Writing data

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

// Responsible image ServletContext Write data in it 
// For example, through /writer?message=aaa Access to the WriterServlet, Just put message=aaa This key value pair is saved to ServletContext
@WebServlet("/writer")
public class WriterServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        //1. Get... From the request message Parameters 
        String message = req.getParameter("message");
        //2. Take out ServletContext object ( This object is Tomcat In the load webapp It's created automatically when you're in the office )
        ServletContext context = this.getServletContext();
        //3. Write key value pairs here 
        context.setAttribute("message",message);
        //4. Return response 
        resp.getWriter().write("<h3> Storage message success </h3>");
    }
}

Revisit reader, Can get message The data of

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

// Use Servlet from ServletContext Read data from 
// from WriterServlet From the data stored inside 
@WebServlet("/reader")
public class ReaderServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        //1. Get the same ServletContext object 
        ServletContext context = this.getServletContext();
        //2. from Context Get the value just saved in 
        String message = (String) context.getAttribute("message");
        //3. Display the extracted data 
        resp.getWriter().write("message: " + message);
    }
}

What is a monitor Listener

You can see , In the two classes just now ServletContext Object is the same , So we need to use ServletContext To store a TemplateEngine object , Reach the present webapp All of the Servlet Use the same... Together TemplateEngine.

You can do it again ServletContext Once you've created it , Give... The first time TemplateEngine To initialize , To that end ,Servlet Provides us with a mechanism ,Listener Monitor , So you can use Listener To listen to ServletContext The initialization of is completed

Servlet There are many kinds of listeners in :

monitor HttpSession The creation and destruction of , Property changes

monitor HttpServletRequest The creation and destruction of , Property changes

monitor ServletContext The creation and destruction of , Property changes

Here we just need to use a listener to listen ServletContext The creation of .

Interfaces involved : ServletContextListener

We implement this interface , Rewrite it servletContextInitialized Method . When ServletContext It will be automatically executed to servletContextInitialized Method

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

// Need make Tomcat Identify this class , So add WebListener This annotation 
@WebListener
public class MyListener implements ServletContextListener {
    // This method will be executed after initialization 
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        System.out.println("ServletContext initialization ");
        // Get it ServletContext object , Obtained through methods and parameters 
        ServletContext context = sce.getServletContext();
        context.setAttribute("message"," Initialization message ");
    }
    // Execute this method before destroying 
    @Override
    public void contextDestroyed(ServletContextEvent sce) {

    }
}

effect

modify Thymeleaf Engine initialization code

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

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

public class ThymeleafConfig implements ServletContextListener {
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        // initialization TemplateEngine
        ServletContext context = sce.getServletContext();
        //1. establish engine example 
        TemplateEngine engine = new TemplateEngine();
        //2. establish resolver example 
        ServletContextTemplateResolver resolver = new ServletContextTemplateResolver(context);
        resolver.setPrefix("/WEB-INF/template/");
        resolver.setSuffix(".html");
        resolver.setCharacterEncoding("utf-8");
        engine.setTemplateResolver(resolver);
        //3. Create a good engine Put examples in ServletContext in 
        context.setAttribute("engine",engine);
        System.out.println("TemplateEngine initialization ");
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {

    }
}
原网站

版权声明
本文为[Tyrannosaurus Rex skeleton takes the dodo]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/162/202206110552195932.html