springboot 页面静态化

article/2025/10/29 18:59:12

springboot 页面静态化

                    

页面静态化:将动态渲染的页面保存为静态页面(一般存储在nginx),提高访问速度

说明:页面静态化适用于数据不常变更的场景,如果数据频繁变更,宜使用其他方案提高访问性能

                             

                           

                                       

相关类与接口

                   

IContext:存储上下文变量

public interface IContext {Locale getLocale();boolean containsVariable(String var1);Set<String> getVariableNames();Object getVariable(String var1);
}

                

AbstractContext

public abstract class AbstractContext implements IContext {private final Map<String, Object> variables;private Locale locale;protected AbstractContext() {protected AbstractContext(Locale locale) {protected AbstractContext(Locale locale, Map<String, Object> variables) {public void setLocale(Locale locale) {public final Locale getLocale() {public final boolean containsVariable(String name) {public final Set<String> getVariableNames() {public final Object getVariable(String name) {public void setVariable(String name, Object value) {public void setVariables(Map<String, Object> variables) {public void removeVariable(String name) {public void clearVariables() {

                 

Context

public final class Context extends AbstractContext {public Context() {}public Context(Locale locale) {super(locale);}public Context(Locale locale, Map<String, Object> variables) {super(locale, variables);}
}

                   

                         

ITemplateEngine

public interface ITemplateEngine {IEngineConfiguration getConfiguration();String process(String var1, IContext var2);String process(String var1, Set<String> var2, IContext var3);String process(TemplateSpec var1, IContext var2);void process(String var1, IContext var2, Writer var3);void process(String var1, Set<String> var2, IContext var3, Writer var4);void process(TemplateSpec var1, IContext var2, Writer var3);IThrottledTemplateProcessor processThrottled(String var1, IContext var2);IThrottledTemplateProcessor processThrottled(String var1, Set<String> var2, IContext var3);IThrottledTemplateProcessor processThrottled(TemplateSpec var1, IContext var2);
}

                   

ISpringTemplateEngine

public interface ISpringTemplateEngine extends ITemplateEngine {void setTemplateEngineMessageSource(MessageSource var1);
}

                       

TemplateEngine

public class TemplateEngine implements ITemplateEngine {public static final String TIMER_LOGGER_NAME = TemplateEngine.class.getName() + ".TIMER";private static final Logger logger = LoggerFactory.getLogger(TemplateEngine.class);private static final Logger timerLogger;private static final int NANOS_IN_SECOND = 1000000;private volatile boolean initialized = false;private final Set<DialectConfiguration> dialectConfigurations = new LinkedHashSet(3);private final Set<ITemplateResolver> templateResolvers = new LinkedHashSet(3);private final Set<IMessageResolver> messageResolvers = new LinkedHashSet(3);private final Set<ILinkBuilder> linkBuilders = new LinkedHashSet(3);private ICacheManager cacheManager = null;private IEngineContextFactory engineContextFactory = null;private IDecoupledTemplateLogicResolver decoupledTemplateLogicResolver = null;private IEngineConfiguration configuration = null;public TemplateEngine() {this.setCacheManager(new StandardCacheManager());this.setEngineContextFactory(new StandardEngineContextFactory());this.setMessageResolver(new StandardMessageResolver());this.setLinkBuilder(new StandardLinkBuilder());this.setDecoupledTemplateLogicResolver(new StandardDecoupledTemplateLogicResolver());this.setDialect(new StandardDialect());}***********
dialect 操作public void setDialect(IDialect dialect) {public void setDialects(Set<IDialect> dialects) {public void setAdditionalDialects(Set<IDialect> additionalDialects) {public final Set<IDialect> getDialects() {public void addDialect(String prefix, IDialect dialect) {public void addDialect(IDialect dialect) {public void setDialectsByPrefix(Map<String, IDialect> dialects) {public final Map<String, Set<IDialect>> getDialectsByPrefix() {public void clearDialects() {***********
templateResolver 操作public void setTemplateResolver(ITemplateResolver templateResolver) {public void setTemplateResolvers(Set<ITemplateResolver> templateResolvers) {public void addTemplateResolver(ITemplateResolver templateResolver) {public final Set<ITemplateResolver> getTemplateResolvers() {***********
process 操作public final String process(String template, IContext context) {public final String process(String template, Set<String> templateSelectors, IContext context) {public final String process(TemplateSpec templateSpec, IContext context) {public final void process(String template, IContext context, Writer writer) {public final void process(String template, Set<String> templateSelectors, IContext context, Writer writer) {public final void process(TemplateSpec templateSpec, IContext context, Writer writer) {public final IThrottledTemplateProcessor processThrottled(String template, IContext context) {public final IThrottledTemplateProcessor processThrottled(String template, Set<String> templateSelectors, IContext context) {public final IThrottledTemplateProcessor processThrottled(TemplateSpec templateSpec, IContext context) {***********
其余操作public final ICacheManager getCacheManager() {public void setCacheManager(ICacheManager cacheManager) {public final IEngineContextFactory getEngineContextFactory() {public void setEngineContextFactory(IEngineContextFactory engineContextFactory) {public final IDecoupledTemplateLogicResolver getDecoupledTemplateLogicResolver() {public void setDecoupledTemplateLogicResolver(IDecoupledTemplateLogicResolver decoupledTemplateLogicResolver) {public final Set<IMessageResolver> getMessageResolvers() {public void setMessageResolvers(Set<IMessageResolver> messageResolvers) {public void addMessageResolver(IMessageResolver messageResolver) {public void setMessageResolver(IMessageResolver messageResolver) {public final Set<ILinkBuilder> getLinkBuilders() {public void setLinkBuilders(Set<ILinkBuilder> linkBuilders) {public void addLinkBuilder(ILinkBuilder linkBuilder) {public void setLinkBuilder(ILinkBuilder linkBuilder) {public void clearTemplateCache() {public void clearTemplateCacheFor(String templateName) {public static String threadIndex() {public final boolean isInitialized() {public IEngineConfiguration getConfiguration() {private void checkNotInitialized() {final void initialize() {protected void initializeSpecific() {static {timerLogger = LoggerFactory.getLogger(TIMER_LOGGER_NAME);}
}

                      

SpringTemplateEngine:springboot启动时自动创建实例bean(mvc)

public class SpringTemplateEngine extends TemplateEngine implements ISpringTemplateEngine, MessageSourceAware {private static final SpringStandardDialect SPRINGSTANDARD_DIALECT = new SpringStandardDialect();private MessageSource messageSource = null;private MessageSource templateEngineMessageSource = null;public SpringTemplateEngine() {super.setDialect(SPRINGSTANDARD_DIALECT);}public void setMessageSource(MessageSource messageSource) {public void setTemplateEngineMessageSource(MessageSource templateEngineMessageSource) {public void setEnableSpringELCompiler(boolean enableSpringELCompiler) {public void setRenderHiddenMarkersBeforeCheckboxes(boolean renderHiddenMarkersBeforeCheckboxes) {public boolean getEnableSpringELCompiler() {public boolean getRenderHiddenMarkersBeforeCheckboxes() {protected final void initializeSpecific() {protected void initializeSpringSpecific() {

                  

                          

                                       

使用示例

                   

*************

config 层

                  

WebConfig

@EnableAsync
@Configuration
public class WebConfig implements AsyncConfigurer {@Overridepublic Executor getAsyncExecutor() {ThreadPoolTaskExecutor executor=new ThreadPoolTaskExecutor();executor.setCorePoolSize(5);executor.setMaxPoolSize(10);executor.setQueueCapacity(10);executor.setKeepAliveSeconds(60);executor.initialize();return executor;}
}

                        

*************

service

                  

StaticPageService

@Service
public class StaticPageService {private final String path="/usr/nginx/html";@Resourceprivate TemplateEngine templateEngine;@Async@SuppressWarnings("all")public void createOrUpdatePage(Map<String,Object> map, String templateName, String dir, Integer id){System.out.println("createOrUpdatePage: "+dir);Context context=new Context();context.setVariables(map);File root=new File(path+File.separator+dir);if (!root.exists()){root.mkdir();}File file=new File(path,dir+File.separator+id+".html");if (file.exists()){file.delete();}try {PrintWriter writer=new PrintWriter(file, StandardCharsets.UTF_8);templateEngine.process(templateName,context,writer);}catch (Exception e){e.printStackTrace();}}@Async@SuppressWarnings("all")public void deletePage(String dir, Integer id){File file = new File(path, dir+File.separator+id+".html");if (file.exists()){file.delete();}}
}

                 

*************

controller

               

HelloController

@Controller
public class HelloController {private Map<String,Object> map=new HashMap<>();@Resourceprivate StaticPageService pageService;@RequestMapping("/person/{id}.html")public ModelAndView get(@PathVariable("id") Integer id, ModelAndView mv){map.put("id",id);map.put("name","瓜田李下");map.put("age",20);pageService.createOrUpdatePage(map,"template","person", id);mv.setViewName("template");mv.addAllObjects(map);return mv;}
}

                     

*************

前端页面

              

template.html

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml"xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
<head><meta charset="UTF-8"><title>static page</title>
</head>
<body>
<div th:align="center" style="color: coral"><span th:text="'id: '+${id}"></span><br><span th:text="'name: '+${name}"></span><br><span th:text="'age: '+${age}"></span>
</div>
</body>
</html>

                      

 

                                       

创建应用

                

nginx 配置:default.conf

server {listen       80;server_name  localhost;#charset koi8-r;#access_log  /var/log/nginx/host.access.log  main;location /person {root   /usr/share/nginx/html;index  index.html index.htm;if ( !-e $request_filename ){proxy_pass http://192.168.57.2:8080;break;}}error_page   500 502 503 504  /50x.html;location = /50x.html {root   /usr/share/nginx/html;}}

           

创建应用:docker 启动springboot应用,nginx代理应用

docker run -it -d --net fixed3 --ip 192.168.57.2 \
-v /usr/nginx/static-page/demo.jar:/usr/local/app.jar \
-v /usr/nginx/html:/usr/nginx/html \
--name static-page commondocker run -it -d --net fixed3 --ip 192.168.57.3  \
-v /usr/nginx/static-page/conf/default.conf:/etc/nginx/conf.d/default.conf \
-v /usr/nginx/html:/usr/share/nginx/html \
--name nginx nginx

                   

                                      

                                       

使用测试

                  

192.168.57.3:8000/person/1.html

                        

                   

控制台输出

2021-08-24 12:25:21.123  INFO 1 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2021-08-24 12:25:21.180  INFO 1 --- [           main] com.example.demo.SpringbootApplication   : Started SpringbootApplication in 10.528 seconds (JVM running for 13.335)
2021-08-24 12:25:29.686  INFO 1 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring DispatcherServlet 'dispatcherServlet'
2021-08-24 12:25:29.687  INFO 1 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
2021-08-24 12:25:29.690  INFO 1 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Completed initialization in 3 ms
createOrUpdatePage: person

                 

查看本地目录:/usr/nginx/html

[root@centos html]# pwd
/usr/nginx/html[root@centos html]# ls
person
[root@centos html]# ls person
1.html[root@centos html]# cat person/1.html
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml"xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
<head><meta charset="UTF-8"><title>static page</title>
</head>
<body>
<div align="center" style="color: coral"><span>id: 1</span><br><span>name: 瓜田李下</span><br><span>age: 20</span>
</div>
</body>

 再次访问192.168.57.3:8000/person/1.html,nginx直接返回本地缓存的静态文件

                         

                        


http://chatgpt.dhexx.cn/article/MVR8JeyZ.shtml

相关文章

PHP 页面静态化

前言 随着网站的内容的增多和用户访问量的增多&#xff0c;网站加载会越来越慢&#xff0c;受限于带宽和服务器同一时间的请求次数的限制&#xff0c;我们往往需要在此时对我们的网站进行代码优化和服务器配置的优化。 一、页面静态化概念 静态化定义 静态化就是指把原本的动态…

页面静态化

前言 我们在使用购物网站的时候&#xff0c;会选择相应的商品点击查看详情&#xff0c;其实会发现每件商品的商品详情页面都是差不多的&#xff0c;除了一些数据外&#xff0c;其余结构布局都是一模一样的&#xff0c;那么是为每件商品都写一个详情页面吗&#xff1f;很显然这…

img标签图片自适应的样式

问题&#xff1a; img标签宽高固定的情况下&#xff0c;上传的图片尺寸不一致&#xff0c;会导致图片被拉伸变形&#xff0c;影响页面美观。 解决方法&#xff1a; 用css3的object-fit 属性、object-position 属性可以解决&#xff0c;代码如下&#xff1a; <!DOCTYPE htm…

图片自适应屏幕大小

有时候美工给过来的图片不规范&#xff0c;用户手机屏幕大小不一样。可能导致在不同的用户手机上显示效果不一样&#xff0c;这时候需要对图片的显示做自适应。 一把来说自适应可以根据需求&#xff0c;做成宽高固定显示屏幕大小。但对于一些长图可能出现图片被压缩在一个屏幕…

响应式图像--图片自适应大小

Foreword 做项目的过程中遇到了一个图片拉伸的问题&#xff0c;做的是手机端的页面&#xff0c;当让其以电脑端页面显示的时候&#xff0c;图片被拉伸的有那么点丑&#xff01;所以改改它&#xff01; Why 为什么会出现这样的情况呢&#xff1f; 1、因为图片是放在盒子…

HTML网页图片背景以及图片自适应设置

关于HTML网页图片背景以及图片自适应设置 Test 1 背景图片需要用到标签中的background属性 图片背景需要显示的位置是网页的身体部分即在body中显示&#xff0c;因此background属性应该放在body标签内 本次使用图片的大小为4808*2704像素&#xff0c;这是图片原来的样子 这是…

html图片自动适应,css如何让图片自适应?

要使图片能够自适应显示&#xff0c;我们一般可以通过设置CSS样式&#xff0c;让图片作为父元素的背景图片&#xff0c;再设置相关属性来实现。下面我们来看一下使用css设置图片自适应的方法。 css设置图片自适应示例&#xff1a; HTML代码&#xff1a;title css代码&#xff1…

【前端】js实现图片自适应

前言&#xff1a; 前几天写第一版代码的时候&#xff0c;测试跟我说&#xff0c;你这用户上传图片显示有问题啊&#xff0c;图像不是被拉宽就是被拉长了&#xff0c;不行啊。因为我给el-image设计的是固定长宽&#xff0c;如果图片不是这个比例&#xff0c;那直接就会变形了&am…

谈一下图片的自适应

在工作中经常遇到要求图片自适应的需求&#xff0c;下面就谈一下我在工作中经常使用的一些方法 单独使用img标签的情况 单独使用img的时候&#xff0c;可以只设置width就可以了&#xff0c;height不用设置&#xff0c;因为img不设置height&#xff0c;它会自动根据图片的比例…

浅谈图片宽度自适应解决方案

在网页设计中&#xff0c;随着响应式设计的到来&#xff0c;各种响应式设计方案层出不穷。对于图片响应式的问题也有很多前端开发人员在进行研究。比较好的图片响应式设想便是在不同的屏幕分辨率下使用不同实际尺寸的图片&#xff0c;而达到在高速网络环境中使用大或超大高清图…

浅谈图片展示、图片自适应解决方案

文章目录 导读CSS 解决方案background-size&#x1f437;background-size: contain&#xff1b;&#x1f437;background-size&#xff1a;100%&#xff1b;&#x1f437;background-size:cover; object-fit&#x1f437;object-fit: contain&#xff1b;&#x1f437;object-f…

实时即未来,大数据项目车联网之项目基石与前瞻【一】

文章目录 写在前面车联网项目全新升级 车联网行业背景介绍车联网技术汽车行业新能源汽车 车联网行业技术车辆网行业产业链与国内知名企业 车联网项目车联网技术架构和技术选型车联网项目的架构搭建 写在前面 车联网项目全新升级 更全 8-》21篇 更细 -》 图文并茂、部分代码首…

开发一个大数据项目的架构与流程

如果我们想做一个数据分析项目&#xff0c;我们就应该清楚数据的处理流程。 我们大致可以分为: 数据采集——数据存储——数据清洗——数据分析——数据可视化和数据挖掘、二次分析 在以上流程处理完成之后&#xff0c;会进入调度阶段&#xff1a;将数据采集、清洗、分析、导出…

大数据项目大致流程

1、提出需求-需要和多个部门负责人进行协商&#xff1a;关于项目的可行性分析 2、需求分析-进行需求调研&#xff08;研究竞品&#xff09;、市场调研&#xff0c;如果是给甲方做产品&#xff0c;需要和甲方协商需求细则 3、技术选型-需要多个开发部门的人员参与协商 考虑的…

大数据项目之电商数仓、数据仓库概念、项目需求及架构设计

文章目录 1.数据仓库概念2. 项目需求及架构设计2.1 项目需求分析2.1.1 采集平台2.1.2 离线需求2.1.3 实时需求2.1.4 思考题 2.2 项目框架2.2.1 技术选型2.2.2 系统数据流程设计2.2.3 框架版本选型2.2.3.1 Apache框架版本 2.2.4 服务器选型2.2.4.1 物理机&#xff1a;2.2.4.2 云…

大数据项目开发进度(实时更新)

文章目录 前言项目概述项目进度第一周0525-0529&#xff1a;第二周0601-0605&#xff1a;第三周0608-0612&#xff1a;第四周0615-0621&#xff1a;&#xff08;周末加班&#xff09;第五周0622-0628&#xff1a;&#xff08;周末加班&#xff09;第六周0629-0705&#xff1a;&…

大数据项目需求分析

以大数据项目为主线&#xff0c;技术理论与项目实践相结合&#xff0c;按照大数据项目的开发流程逐步推进&#xff0c;本文主要讲解项目的需求分析、架构设计以及离线和实时数据流程设计&#xff0c;然后提前规划好大数据项目需要的集群&#xff0c;按照项目的实现逻辑&#xf…

大数据项目篇--项目架构图

文章目录 离线架构离线架构-表信息离线架构-ETL信息 实时架构 离线架构 离线架构-表信息 离线架构-ETL信息 实时架构

客快物流大数据项目学习框架

文章目录 客快物流大数据项目学习框架 前言 一、项目简介 二、功能介绍 三、项目背景 四、服务器资源规划 五、技术亮点及价值 六、智慧物流大数据平台 客快物流大数据项目学习框架 前言 利用框架的力量&#xff0c;看懂游戏规则&#xff0c;才是入行的前提 大多数人…