在舊版中,通常繼承 WebMvcConfigurerAdapter類,但因爲2.0後,前者已通過時,在spring boot2.x中,WebMvcConfigurerAdapter被deprecated,雖然繼承WebMvcConfigurerAdapter這個類雖然有此便利,但在Spring5.0裏面已經deprecated了。 官方文檔也說了,WebMvcConfigurer接口如今已經有了默認的空白方法,因此在Springboot2.0(Spring5.0)下更好的作法仍是implements WebMvcConfigurer。css
自定義攔截器必須實現HandlerInterceptor,定義一個登陸攔截器,攔截須要登陸的操做,若未登陸則重定向至登陸界面java
package com.cxy.springboot.utils.Interceptor;
import com.cxy.springboot.utils.GlobalConst;
import com.cxy.springboot.utils.UserInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @Auther: cxy
* @Date: 2019/1/10
* @Description: 攔截器
*/
public class LoginInterceptor implements HandlerInterceptor {
private Logger logger = LoggerFactory.getLogger(LoginInterceptor.class);
@Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) throws Exception {
UserInfo user = (UserInfo)request.getSession().getAttribute(GlobalConst.USER_SESSION_KEY);
logger.info(request.getRequestURI().toString());
if (user == null || user.equals("")) {
response.sendRedirect("/login");
logger.info("請先登陸");
return false;
}
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
logger.info("postHandle...");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
logger.info("afterCompletion...");
}
}
複製代碼
新建類 WebConfigurer.java
,addPathPatterns 用來設置攔截路徑,excludePathPatterns 用來設置白名單,也就是不須要觸發這個攔截器的路徑。web
package com.cxy.springboot.utils;
import com.cxy.springboot.utils.Interceptor.LoginInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.*;
/**
* @Auther: cxy
* @Date: 2019/1/10
* @Description: 在web的配置文件中,實例化登錄的攔截器,並添加規則
*/
@Configuration
public class WebConfigurer implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LoginInterceptor()).addPathPatterns("/**").excludePathPatterns("/login").excludePathPatterns("/loginSys").excludePathPatterns("/static/**");
}
}
複製代碼
無論哪一個版本,addResourceHandler方法是設置訪問路徑前綴,addResourceLocations方法設置資源路徑,若是你想指定外部的目錄也很簡單,直接addResourceLocations指定便可,代碼以下:spring
registry.addResourceHandler("/static/**").addResourceLocations("file:E:/cxy/");
複製代碼
在application.properties 或 application.yml指定靜態資源攔截,要否則靜態資源會被攔截。bootstrap
#配置靜態資源
spring.mvc.static-path-pattern=/static/**
複製代碼
<link th:href="@{/static/js/hplus/css/bootstrap.min14ed.css}" rel="stylesheet">
複製代碼