一 概念
主页:访问网站域名跳转的第一个页面
二 原理
三 使用
环境
idea:2019
springboot:2.0.1.RELEASE
jdk:1.8
1)默认的方式
在resources目录下面创建一个static文件夹,
在static文件夹下面创建一个index.html文件,
不需要任何其他的配置即可完成主页的设置
2)指定某一个页面作为主页
编写一个controller类,该类中有一个方法的匹配路径为/
package com.myworld.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* 主页控制器
*/
@Controller
@RequestMapping(value = "/")
public class IndexController {
@RequestMapping(value = "/")
public String index(){
System.out.println("/index");
return "/html/pages/samples/login";
}
}
或者
添加一个继承自WebMvcConfigurerAdapter的配置类即可
package com.myworld.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
//或者实现WebMvcConfigurer 接口
//public class DefaultView implements WebMvcConfigurer {
//WebMvcConfigurerAdapter已经过时
@Configuration
public class DefaultView extends WebMvcConfigurationSupport {
/**
* 添加主页方法
*
* @param registry 主页注册器
*/
@Override
public void addViewControllers(ViewControllerRegistry registry) {
System.out.println("设置了主页");
//设置主页
registry.addViewController("/").setViewName("/html/pages/samples/login");
//设置优先级
registry.setOrder(Ordered.HIGHEST_PRECEDENCE);
//将主页注册器添加到视图控制器中
super.addViewControllers(registry);
}
}
两种设置的视图都是一样的