Spring Boot 引用静态资源
2019-06-17 本文已影响0人
M_ENG
1 : 代码配置静态资源路径
2 : 登录拦截器
3 : 配置错误页面和所有跳转页面
如果设置了 项目contextPath
server.servlet.context-path=/apply
项目访问路径为:http:127.0.0.1:8080/apply
绝对路径引入:
<link rel="stylesheet" href="/apply/css/index/base.css" />
相对路径引入:(最前面不要加’/‘ )
<link rel="stylesheet" href="css/index/base.css" />
所有路径最好使用相对路径(前面不要加‘/’)、不管是引入资源还是跳转后台
这样不用担心 项目的contextPath 修改、不然当contextPath修改 所有的路径都要修改(包括请求后台的路径)
不设置ContextPath
-#server.servlet.context-path=/apply
项目访问路径为:http:127.0.0.1:8080/ 直接就是‘/’
package com.afcs.webconfig;
import com.afcs.Interceptor.LoginInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
/**
* 配置静态访问资源 页面跳转 配置拦截器
*
* @author MENG
* @version 2017/12/22
* @see
*/
@Configuration
public class WebMvcConfigurer extends WebMvcConfigurationSupport
{
/**
*
* 跳转页面
*
* @param registry
*/
@Override
public void addViewControllers(ViewControllerRegistry registry)
{
registry.addViewController("/err/404").setViewName("/common/404");
registry.addViewController("/err/500").setViewName("/common/500");
registry.addViewController("/err/401").setViewName("/common/401");
registry.addViewController("/").setViewName("/index/index");//首页
registry.addViewController("/login").setViewName("/index/login");//登录页面
super.addViewControllers(registry);
}
@Autowired
private LoginInterceptor loginInterceptor;
/**
*
* 配置拦截器
*
* @param registry
*/
@Override
public void addInterceptors(InterceptorRegistry registry)
{
registry.addInterceptor(loginInterceptor).addPathPatterns("/**")
.excludePathPatterns("/index","/err/*","/login","/user/login"//登录页面和错误页面
,"/images/**","/js/**","/common/**","/css/**" //静态资源
);
super.addInterceptors(registry);
}
/**
* 配置静态访问资源
* @param registry
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry)
{
registry.addResourceHandler("/images/**").addResourceLocations("classpath:/static/images/");
registry.addResourceHandler("/js/**").addResourceLocations("classpath:/static/js/");
registry.addResourceHandler("/common/**").addResourceLocations("classpath:/static/common/");
registry.addResourceHandler("/css/**").addResourceLocations("classpath:/static/css/");
super.addResourceHandlers(registry);
}
}