首页 > 编程知识 正文

jsp和thymeleaf优缺点,thymeleaf可以完全替代jsp

时间:2023-05-06 13:30:29 阅读:204593 作者:1379

先上例子再来介绍吧,理论看多了容易晕

resources目录下的templates新建一个html文件

代码:注意html标签与jsp或者html的不同 自己加进去

<!DOCTYPE html><html xmlns:th="http://www.thymeleaf.org"><head><meta charset="UTF-8"><title>Insert title here</title><meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/></head><body><h1>这是你的thymeleaf页面</h1><span th:text="'你是:'+${key}">SB</span> <table> <tr> <th>NAME</th> <th>PRICE</th> <th>IN STOCK</th> </tr> <tr th:each="prod : ${comments}"> <td th:text="${prod.name}">Onions</td> <td th:text="${prod.price}">2.41</td> <td th:text="${prod.age}">yes</td> </tr> </table></body></html>

build.gradle加入thymeleaf依赖

implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'

新建一个实体类

package com.comment.bean;/*** * * <p>TODO评论实体类</p> * * <p>Copyright: 版权所有 (c) 2002 - 2008<br> * * @author ainy * @version 2019年2月15日 */public class Comment {private String name;private int age;private double price;public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}public double getPrice() {return price;}public void setPrice(double price) {this.price = price;}}

新建一个controller

package com.comment.consumer;import java.util.ArrayList;import java.util.List;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import com.comment.bean.Comment;@Controllerpublic class PageController { @RequestMapping(value = "show", method = RequestMethod.GET) public String show(Model model){ model.addAttribute("key","gdddt"); List<Comment> comments=new ArrayList<>(); Comment c1=new Comment(); c1.setAge(8); c1.setName("李晓明"); c1.setPrice(99); comments.add(c1); Comment c2=new Comment(); c2.setAge(37); c2.setName("畅快的香烟"); c2.setPrice(66); comments.add(c2); model.addAttribute("comments", comments); return "hello.html"; }}

启动入口类
直接访问网址 如图

再在文件夹中直接打开网页,也就是静态网页

效果:

比较打开静态页面和打开动态页面的区别
会发现静态页面展示标签中间的内容:

而动态打开展示的是后台传过来的数据,不再展示标签内的数据,这就很好的做到了前后端分离,和jsp大同小异,用SpringBoot的话就不要用jsp了,虽然可以用,但是官方不推荐

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。