Spring Boot 自定义首页与浏览器角标(深入源码分析)

🎈博客主页:🌈我的主页🌈
🎈欢迎点赞 👍 收藏 🌟留言 📝 欢迎讨论!👏
🎈本文由 【泠青沼~】 原创,首发于 CSDN🚩🚩🚩
🎈由于博主是在学小白一枚,难免会有错误,有任何问题欢迎评论区留言指出,感激不尽!🌠个人主页



🌟 一、自定义首页

首先,创建两个html文件,一个为静态资源,另一个是动态资源(使用thymeleaf模板),进行映射配置,详细见博文

🌟🌟 1.1、模板

在这里插入图片描述

🌟🌟 1.2、映射配置

@Configuration
public class MyWebMvcConfig implements WebMvcConfigurer {
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/index").setViewName("index");
    }
}

🌟🌟 1.3、结论

请求发送后,默认访问的是放在static静态目录的静态资源,如果将静态资源删除,那么将访问的就是template目录下的动态资源

🌟🌟 1.4、源码分析

进入WebMvcAutoConfiguration类中,找出getWelcomePage方法,这个方法就是用来请求资源的

private Resource getWelcomePage() {
			for (String location : this.resourceProperties.getStaticLocations()) {
				Resource indexHtml = getIndexHtml(location);
				if (indexHtml != null) {
					return indexHtml;
				}
			}
			ServletContext servletContext = getServletContext();
			if (servletContext != null) {
				return getIndexHtml(new ServletContextResource(servletContext, SERVLET_LOCATION));
			}
			return null;
		}
  1. this.resourceProperties.getStaticLocations()
    拿到静态资源的位置"classpath:/META-INF/resources/",
    “classpath:/resources/”, “classpath:/static/”, “classpath:/public/”,’’/’’
  2. Resource indexHtml = getIndexHtml(location)
    拿到上述静态资源的位置,得到html文件

进入WelcomePageHandlerMapping类中,分析下列的方法
WelcomePageHandlerMapping(TemplateAvailabilityProviders templateAvailabilityProviders,
			ApplicationContext applicationContext, Resource welcomePage, String staticPathPattern) {
		if (welcomePage != null && "/**".equals(staticPathPattern)) {
			logger.info("Adding welcome page: " + welcomePage);
			setRootViewName("forward:index.html");
		}
		else if (welcomeTemplateExists(templateAvailabilityProviders, applicationContext)) {
			logger.info("Adding welcome page template: index");
			setRootViewName("index");
		}
	}
  1. if (welcomePage != null && “/”.equals(staticPathPattern)) {
    logger.info("Adding welcome page: " + welcomePage);
    setRootViewName(“forward:index.html”);
    }

    如果静态资源可以找到,那就返回找到的静态页面
  2. else if (welcomeTemplateExists(templateAvailabilityProviders, applicationContext)) {
    logger.info(“Adding welcome page template: index”);
    setRootViewName(“index”);
    }

    如果静态资源找不到,就找动态页面,动态页面存在就返回找到的动态页面

🌟 二、自定义浏览器角标

找到一个favicon制作的在线工具,制作icon,文件命名favicon.ico,加入到static的目录下,之后就会自动的加载到项目中去

在这里插入图片描述


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值