直接按我的步骤走都没有问题:
1 配置自定义的拦截器:
package com.configs;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* Created by Yousiqi on 2017/11/16.
*/
@Component
public class UserInterceptor implements HandlerInterceptor {
/**
* 登录session key
*/
public final static String SESSION_KEY = "user";
private static final Logger logger = LoggerFactory.getLogger(UserInterceptor.class);
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
HttpSession session = request.getSession();
if (session.getAttribute(SESSION_KEY) == null){
// 跳转登录(这里是重定向需要包括上下文的名也就是项目名)
String viewUrl = "/DayIndicators/loginview";
response.sendRedirect(viewUrl);
}
/**
* 对来自后台的请求统一进行日志处理
*/
String url = request.getRequestURL().toString();
String method = request.getMethod();
String uri = request.getRequestURI();
String queryString = request.getQueryString();
System.out.println(request.getParameterMap());
logger.info(String.format("request param: url: %s, method: %s, uri: %s, params: %s", url, method, uri, queryString));
// return true;
return true;
}
@Override
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
}
}
2 接下来要让Spring boot知道我们配置了这一个拦截器并拦截:
package com.configs;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
/**
*file: CustomWebMvcConfigurerAdapter.java
* Created by jiaobuchong on 12/23/15.
*/
//利用Configuration注解来代替以往的xml配置方式
@Configuration
public class CustomWebMvcConfigurerAdapter extends WebMvcConfigurerAdapter {
@Override
public void addInterceptors(InterceptorRegistry registry) {
InterceptorRegistration addInterceptor = registry.addInterceptor(new UserInterceptor());
// 排除配置
//这里的路径匹配不包括上下文路径
//不拦截错误的页面
addInterceptor.excludePathPatterns("/error");
//不拦截登入的页面
addInterceptor.excludePathPatterns("/login**");
// 拦截配置
//这里的路径匹配不包括上下文路径
addInterceptor.addPathPatterns("/**");
}
}
只需要这两步即可完成Spring Boot拦截器配置