springboot的拦截器:
编写配置类实现拦截器接口(HandlerInterceptor),重写preHandle方法:
public class MyHandlerInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
boolean flag=false;
String user= (String) request.getSession().getAttribute("user");
if(user==null){
response.sendRedirect("/book/tologin");
}else{
flag=true;
}
return flag;
}
}
编写配置类,继承WebMvcConfigurationSupport类,重写addInterceptor方法,关联我们的拦截器,编写过滤路径:
@Configuration
public class MyWebMvcConfigurationSupport extends WebMvcConfigurationSupport {
@Override
protected void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new MyHandlerInterceptor())
.addPathPatterns("/**").excludePathPatterns("/book/tologin","/book/login","/book/code/getCode","/book/allBook");
super.addInterceptors(registry);
}
}
登录时创建session:
@RequestMapping("/login")
public String login(String username, String password,HttpServletRequest request){
System.out.println(username);
User user=userService.queryUserbyName(username);
System.out.println(user);
if(username.equals(user.getUsername())&&password.equals(user.getPassword())){
HttpSession session=request.getSession();
session.setAttribute("user","user");
return "redirect:/book/allBook";
}else{
return "login";
}
}
SSM拦截器配置:
首先还是编写拦截器类实现拦截器接口:
public class PermissionInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
HttpSession session = request.getSession();
if(session.getAttribute("user") != null){
return true;
}else{
throw new PermissionException("没有权限访问");
}
}
在springmvc.xml配置文件中加上拦截器配置:
<!--权限拦截器-->
<mvc:interceptor>
<mvc:mapping path="/**/*"/>
<mvc:exclude-mapping path="/login"/>
<mvc:exclude-mapping path="/logout"/>
<mvc:exclude-mapping path="/captcha/*"/>
<mvc:exclude-mapping path="/static/**"/>
<bean class="com.zqy.utils.PermissionInterceptor"/>
</mvc:interceptor>
参考博客:https://blog.csdn.net/xinbumi/article/details/82682288