spring boot项目一般通过Application启动,且不需要配置web.xml,所以设置默认访问页面可以通过以下方法实现,比如增加默认DefaultView类,代码如下:
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.WebMvcConfigurerAdapter;
/**
*
* <p>类描述:项目默认访问路径 </p>
* <p>创建人:wanghonggang </p>
* <p>创建时间:2018年12月27日 上午11:29:03 </p>
*/
@Configuration
public class DefaultView extends WebMvcConfigurerAdapter {
@Override
public void addViewControllers(ViewControllerRegistry reg) {
reg.addViewController("/").setViewName("login");//默认访问页面
reg.setOrder(Ordered.HIGHEST_PRECEDENCE);//最先执行过滤
super.addViewControllers(reg);
}
}
再次访问项目即可默认到login这个页面。
另一种方法是通过实现HandlerInterceptor配合WebMvcConfigurerAdapter实现。
spring boot 2.0开始弃用了WebMvcConfigurerAdapter ,我们可以用WebMvcConfigurer,完整代码如下:
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.WebMvcConfigurer;
/**
*
* <p>类描述:项目默认访问路径 </p>
* <p>创建人:wanghonggang </p>
* <p>创建时间:2018年12月27日 上午11:29:03 </p>
*/
@Configuration
public class WebConfigurer implements WebMvcConfigurer{
@Override
public void addViewControllers(ViewControllerRegistry registry) {
//默认地址(可以是页面或后台请求接口)
registry.addViewController("/").setViewName("forward:/login.html");
//设置过滤优先级最高
registry.setOrder(Ordered.HIGHEST_PRECEDENCE);
}
}