最近做了一个小项目,只有几个页面,不过也要用到登录拦截,看了网上的博客,自己整理了一下
1、拦截请求和设置不拦截的请求地址
package com.windy.atest;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
public class MyWebAppConfigurer extends WebMvcConfigurerAdapter {
@Bean
public HandlerInterceptor getMyInterceptor(){
return new MyInterceptor();
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
// addPathPatterns 用于添加拦截规则, 这里假设拦截 /url 后面的全部链接
// excludePathPatterns 用户排除拦截
//registry.addInterceptor(getMyInterceptor()).addPathPatterns("/**");
String[] urlArry={"/login","/loginHandle"};//不拦截的访问路径
registry.addInterceptor(getMyInterceptor()).addPathPatterns("/**").excludePathPatterns(urlArry);
super.addInterceptors(registry);
}
}
2、如果请求没有session,则返回到登录页面
package com.windy.atest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
public class MyInterceptor implements HandlerInterceptor {
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {
Object sessionid=request.getSession().getAttribute("password");
if(sessionid!=null){
System.out.println("有session");
return true;
}else{
response.sendRedirect("/tomcat/login");//如果没有session
return false;
}
}
@Override
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
System.out.println("postHandle被调用");
}
@Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
System.out.println("afterCompletion被调用");
}
}
3、测试
登录页:
提交之后登录成功:
访问一个被拦截的地址看看:成功
换一个浏览器访问该地址看看:
跳转到了登录页,说明拦截成功
示例项目代码:
链接:https://pan.baidu.com/s/1XZb16bezrAVHZ4HHcT_0OA
提取码:rzqd