SpringMVC使用WebMvcConfigurerAdapter+HandlerInterceptorAdapter实现拦截
虽然网上说 WebMvcConfigurerAdapter 已经过时了,但是我看我的 SpringBoot 里用的还是好好的。
而且这个确实也比较容易理解,比较简单。可以很轻易的实现拦截、过滤功能。
如下是我写的一个登陆拦截的例子,只有在 session 域中 adminUser 该 key 下有值的话才会跳转到能够登陆的页面
我这拦截的是所有路径,对登录页和登陆的登陆验证ajax请求做了开放。即除登陆也页以外所有页面都需要登录才能进入,不然就跳转到登录页。
我代码注释还是写的很清晰的。应该算便于理解
package top.yibobo.config;
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;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
/**
* 登录拦截配置
* @author pyb
* @time 2018-10-12
*/
@Configuration
public class LoginSecurityConfig extends WebMvcConfigurerAdapter{
/**
* 添加拦截器
* @param registry
*/
public void addInterceptors(InterceptorRegistry registry) {
InterceptorRegistration addInterceptor =
registry.addInterceptor(new SecurityInterceptor())//注册拦截器,这里注册的是下边写的内部类
//excludePathPatterns() 方法接受一个String 字符串,代表不用拦截的路径
.excludePathPatterns("/**/oauth")
.excludePathPatterns("/**/system/adminUser");
//拦截所有路径
addInterceptor.addPathPatterns("/**");
}
/**
* 拦截器
*/
private class SecurityInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
HttpSession session = request.getSession();
//判断是否已有该用户登录的session
if (session.getAttribute("adminUser") != null) {
return true;
}
//没登录就跳转到登录页
response.sendRedirect("oauth");
return false;
}
}
}

ceshi一下