java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Java SpringBoot拦截器

Java SpringBoot 使用拦截器作为权限控制的实现方法

作者:New_HackerHK

这篇文章主要介绍了Java SpringBoot 使用拦截器作为权限控制的实现,文中通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

如何实现

首先拦截器是属于web这块的,那我们需要引入springboot web模块,具体版本在parent中

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

然后我们在config目录下新建interceptor目录,用来放拦截器

登陆拦截器

package com.example.interceptor_demo.config.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
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;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
/**
 * 拦截器,登录检查
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private HttpSession session;

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        Object user = session.getAttribute("sessionUser");
        if (sessionUser!=null){
            return true;
        }else {
            Map<String,Object> notLogin = new HashMap<>();
            notLogin.put("msg","not login");
            notLogin.put("code",403);
            notLogin.put("data",null);
            try(PrintWriter printWriter = response.getWriter()){
                printWriter.print(objectMapper.writeValueAsString(notLogin));
            }catch (Exception e){
                e.printStackTrace();
            }
            return false;
        }
    }


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
    }

}

管理员拦截器

package com.example.interceptor_demo.config.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
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;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
/**
 * 拦截器,管理员验证
 */
@Component
public class AdminInterceptor implements HandlerInterceptor {

    @Autowired
    private HttpSession session;

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        Boolean isAdmin = (Boolean)session.getAttribute("sessionAdmin");
        if (isAdmin!=null && isAdmin){
            return true;
        }else {
            Map<String,Object> notLogin = new HashMap<>();
            notLogin.put("msg","no power");
            notLogin.put("code",403);
            notLogin.put("data",null);
            try(PrintWriter printWriter = response.getWriter()){
                printWriter.print(objectMapper.writeValueAsString(notLogin));
            }catch (Exception e){
                e.printStackTrace();
            }
            return false;
        }
    }


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
    }

}

最后我们在config目录下新建WebMvcConfig类,用来注册拦截器

package com.example.interceptor_demo.config;

import com.example.interceptor_demo.config.interceptor.AdminInterceptor;
import com.example.interceptor_demo.config.interceptor.LoginInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Autowired
    private LoginInterceptor loginInterceptor;

    @Autowired
    private AdminInterceptor adminInterceptor;
    
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        this.loginInterceptor(registry);//登录拦截        
        this.adminInterceptor(registry);//管理员拦截
    }

    private void loginInterceptor(InterceptorRegistry registry){
        registry.addInterceptor(loginInterceptor)
                .addPathPatterns("/**")
                .excludePathPatterns(//释放登陆接口
                        "/login/**"
                );
    }

    private void adminInterceptor(InterceptorRegistry registry){
        registry.addInterceptor(htmlPageInterceptor)
                .addPathPatterns("/admin/**");//拦截管理员接口
    }
}

到此这篇关于Java SpringBoot 使用拦截器作为权限控制的文章就介绍到这了,更多相关Java SpringBoot拦截器权限控制内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文