Spring Boot學習筆記(7)—— SpringBoot項目自定義歡迎頁

1、前面在 https://blog.csdn.net/weixin_43231076/article/details/90142888 中提到,springboot項目的默認歡迎頁是放在 4個靜態資源目錄 下面,在訪問:localhost:8080 或者 localhost:8080/index.html 請求時,會從4個靜態資源目錄下面依次查找 index.html 文件,找到就返回,沒有找到就返回 404。
2、但是在實際項目中,靜態資源目錄 中只會存放靜態資源,歡迎頁一般也是頁面,會放在模板文件目錄:templates 下面,此時再通過 localhost:8080 或者 localhost:8080/index.html 來訪問,就訪問不到歡迎頁
3、可以通過自定義請求,或者自定義視圖控制的方式,來控制訪問默認歡迎頁:
1)、通過自定義請求的方式,來訪問默認歡迎頁

package com.dss.springboot.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class IndexController {

	/**
	 * 配置一個請求,作爲訪問默認首頁的請求
	 * @return
	 */
	@GetMapping(value = {"/", "/index.html"})
	public String index() {
		return "main/login";
	}
}

通過寫一個Controller,配置默認的請求,讓他指向自己的歡迎頁,這樣就能實現訪問默認歡迎頁

2)、通過自定義視圖控制的方式:

package com.dss.springboot.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * 聲明這個類是一個配置類
 * @author asong
 *
 */
@Configuration
public class MySpringMvcConfigurer {

	/**
	 * 向 spring容器中注入一個組件,組件的類型是 WebMvcConfigurer,組件的id是 webMvcConfigurer
	 * 這裏是添加一個自定義的視圖控制
	 * @return
	 */
	@Bean
	public WebMvcConfigurer webMvcConfigurer() {
		return new WebMvcConfigurer() {
			
			/**
			 * 添加一個自定義的視圖控制,用於訪問 springboot 項目的默認首頁
			 */
			@Override
			public void addViewControllers(ViewControllerRegistry registry) {
				registry.addViewController("/").setViewName("main/login");
				registry.addViewController("/index.html").setViewName("main/login");
			}
			
		};
	}
}

定義一個配置類,裏面聲明一個方法,向spring容器中注入一個 WebMvcConfigurer 組件,在組件中通過自定義的視圖控制,來控制 springboot 默認歡迎頁的訪問url

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章