直接按我的步骤走都没有问题:
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拦截器配置
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/17912.html