当前位置:网站首页>Servlet template engine usage example
Servlet template engine usage example
2022-04-23 02:40:00 【Mother in law oriented programming】
1. How to render dynamic pages
1.1 Server-side rendering
HTML as follows :
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<title> Guess the number </title>
</head>
<body>
<div>
<form action="guessNum" method="post">
<input type="text" name="toGuess">
<input type="submit" value=" guess ">
</form>
</div>
<div> result :</div>
</body>
</html>
Java The code is as follows :
package Thymeleaf;
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;
import java.util.Random;
@WebServlet("/guessNum")
public class GuessNumServlet extends HttpServlet {
Random random = new Random();
private int toGuess = 0;
// Use this doGet To get the initial page of guessing numbers from the server
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html;charset=UTF-8");
toGuess = random.nextInt(100) + 1;
resp.getWriter().write("<!DOCTYPE html>\n" +
"<html lang=\"zh\">\n" +
"<head>\n" +
" <meta charset=\"UTF-8\">\n" +
" <title> Guess the number </title>\n" +
"</head>\n" +
"<body>\n" +
"<div>\n" +
" <form action=\"guessNum\" method=\"post\">\n" +
" <input type=\"text\" name=\"toGuess\">\n" +
" <input type=\"submit\" value=\" guess \">\n" +
" </form>\n" +
"</div>\n" +
"<div> result :</div>\n" +
"</body>\n" +
"</html>");
}
// Use doPost To get... From the server " With guesses " The page of
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html;charset=UTF-8");
// First, compare the results according to the numbers submitted by users
int user = Integer.parseInt(req.getParameter("toGuess"));
String result = "";
if (user < toGuess) {
result = " It's low ";
} else if (user > toGuess) {
result = " High ";
} else {
result = " bingo ";
}
resp.getWriter().write("<!DOCTYPE html>\n" +
"<html lang=\"zh\">\n" +
"<head>\n" +
" <meta charset=\"UTF-8\">\n" +
" <title> Guess the number </title>\n" +
"</head>\n" +
"<body>\n" +
"<div>\n" +
" <form action=\"guessNum\" method=\"post\">\n" +
" <input type=\"text\" name=\"toGuess\">\n" +
" <input type=\"submit\" value=\" guess \">\n" +
" </form>\n" +
"</div>\n" +
"<div> result :</div>\n" + result +
"</body>\n" +
"</html>");
}
}
You will find that without using the template engine , Current Java Code ( Represents business logic ) and HTML Code ( Represents the user interface ) Mix it up , Very unfriendly . In especial HTML A long , When it's more complicated .
1.2 Client rendering 「Thymeleaf」
HTML file
<!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>MessageWal</title>
</head>
<body>
<style> * {
margin: 0px; padding: 0px; /* Because there is padding The existence of content will cause the box to expand : Add... Here border-box Then don't open the box */ box-sizing: border-box; } .container {
width: 600px; margin: 0 auto; } h1 {
text-align: center; padding: 20px 0px; } p {
font-size: 12px; color: grey; padding: 10px 0px; text-align: center; } .row {
display: flex; height: 40px; justify-content: center; align-items: center; } .row span {
width: 100px; } .row .edit {
width: 200px; height: 38px; } .row .submit {
width: 300px; height: 40px; background-color: orange; /* Clear border lines */ border: none; color: white; } .row .submit:active {
background-color: grey; } </style>
<div class="container">
<h1> Confession wall </h1>
<p> Click Submit after entering , The information will be displayed in the table </p>
<form action="message" method="post">
<div class="row">
<span> who :</span>
<input type="text" class="edit" name="from">
</div>
<div class="row">
<span> To whom :</span>
<input type="text" class="edit" name="to">
</div>
<div class="row">
<span> what did you say? :</span>
<input type="text" class="edit" name="message">
</div>
<div class="row">
<input type="submit" value=" Submit " class="submit">
</div>
</form>
<!-- This div Just get the content in a mysterious way -->
<div class="row" th:each="message:${messages}">
<span th:text="${message.from}"></span>
Yes
<span th:text="${message.to}"></span>
say :
<span th:text="${message.message}"></span>
</div>
</div>
<script> // Now through java Code to dynamically generate the current page content , There is no need for the front end to generate the label here // let submitButton = document.querySelector(".submit"); // submitButton.onclick = function () {
// // 1. Now get the content in the input frame // let edits = document.querySelectorAll(".edit"); // let from = edits[0].value, to = edits[1].value, message = edits[2].value; // if (!(from == "" || to == "" | message == "")) {
// console.log(from + " Yes " + to + ":" + message); // // 2. According to the input , structure HTML Elements , Add to page // let row = document.createElement("div"); // row.className = "row"; // row.innerHTML = from + " Yes " + to + " say :" + message; // let container = document.querySelector(".container"); // container.appendChild(row); // // 3. Clear the last input ; // for (let i = 0; i < edits.length; ++i) {
// edits[i].value = ""; // } // } // } </script>
</body>
</html>
Servlet Code
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;
import java.util.ArrayList;
class Message {
public String from;
public String to;
public String message;
}
@WebServlet("/message")
public class MessageServlet extends HttpServlet {
// 1. First create the engine
private TemplateEngine engine = new TemplateEngine();
// Save all messages
private ArrayList<Message> messages = new ArrayList<>();
@Override
public void init() throws ServletException {
// 2. Create a parser
ServletContextTemplateResolver resolver = new ServletContextTemplateResolver(getServletContext());
resolver.setPrefix("/WEB-INF/template/");
resolver.setSuffix(".html");
resolver.setCharacterEncoding("UTF-8");
engine.setTemplateResolver(resolver);
}
// Get the initial page
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// Load the current template , Put the news messages Replace it , And return to the page
resp.setContentType("text/html;charset=UTF-8");
WebContext webContext = new WebContext(req, resp, getServletContext());
webContext.setVariable("messages", messages);
engine.process("MessageWall", webContext, resp.getWriter());
}
// Execute new page
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// Read the data submitted by the user , Add to messages Go to... In the list , Then return to a full page
// It is necessary to set the access method of the request , otherwise Servlet The Chinese you read may be garbled
req.setCharacterEncoding("UTF-8");
Message message = new Message();
message.from = req.getParameter("from");
message.to = req.getParameter("to");
message.message = req.getParameter("message");
messages.add(message);
// Return to the full page
resp.setContentType("text/html;charset=UTF-8");
WebContext webContext = new WebContext(req, resp, getServletContext());
webContext.setVariable("messages", messages);
engine.process("MessageWall", webContext, resp.getWriter());
}
}
/* Servlet The purpose of the template engine : It can return to a page more easily ; No template engine , Directly in java In the code , Returns... By assembling strings html【 Very troublesome and error prone 】 There's a template engine , Put... Directly html Put it in .html In file , And put some of the data that needs to be generated dynamically , Use placeholders to take a place . stay java Load this in the code html Template , And dynamically replace the placeholder 1.java Processing in code Thymeleaf The function of template engine object is to dynamically replace data , The core approach is process(" Template name ", webContext, resp.getWriter()) ServletContextTemplateResolver Parser object : Load template file WebContext: Simple key value pairs . Through this object , Put the placeholder in the template and java The variables associated with ServletContext: This object is not Thymeleaf Of , yes Servlet Built in context object , Every webapp There's a context . One webapp Some of them Servlet Share the same context object . The purpose of this context object is to make these Servlet Sharing data between , Or communicate with each other initialization : Fixed routine , Copy and paste 2. Processing in template code Thymeleaf In support of " Place holder " th:text Take the value of the variable as html Label content th:[ attribute ] Take the value of the variable as html Property value of label th:if Conditions to determine th:each loop */
File directory

版权声明
本文为[Mother in law oriented programming]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204220811021753.html
边栏推荐
- Program design: l1-49 ladder race, allocation of seats (simulation), Buxiang pill hot
- 字符串去掉空格问题
- Leetcode cooking
- Those years can not do math problems, using pyhon only takes 1 minute?
- 电源电路设计原来是这么回事
- 012_ Access denied for user ‘root‘@‘localhost‘ (using password: YES)
- PHP sorting of interview questions on April 20, 2022
- hack the box optimum靶机
- PIP install shutil reports an error
- Go语言web中间件的使用
猜你喜欢

Devil cold rice 𞓜 078 devil answers the market in Shanghai and Nanjing; Communication and guidance; Winning the country and killing and screening; The purpose of making money; Change other people's op
![[XJTU computer network security and management] Lecture 2 password technology](/img/b0/263e8dcbfeb2ce9f504a9c8eb76b07.png)
[XJTU computer network security and management] Lecture 2 password technology

Intelligent agricultural management model

Day 3 of learning rhcsa

JVM class loader

So library dependency

本地远程访问云服务器的jupyter

Deploying sbert model based on torchserve < semantic similarity task >

Talk about current limiting

A domestic image segmentation project is heavy and open source!
随机推荐
001_ Redis set survival time
RT_ Thread ask and answer
Go语言web中间件的使用
WordPress calls the specified page content. 2 get_ children()
They are all intelligent in the whole house. What's the difference between aqara and homekit?
JDBC JDBC
牛客手速月赛 48 C(差分都玩不明白了属于是)
Intelligent agricultural management model
So library dependency
MySQL JDBC programming
Flink stream processing engine system learning (I)
Rhcsa day 3 operation
Machine learning (Zhou Zhihua) Chapter 14 probability graph model
Modify the content of MySQL + PHP drop-down box
每日一题冲刺大厂第十六天 NOIP普及组 三国游戏
解决win7 中powershell挖矿占用CPU100%
电源电路设计原来是这么回事
RT_Thread自问自答
5W of knowledge points
Rhcsa day 1 operation