亲宝软件园·资讯

展开

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

New_HackerHK 人气:0
想了解Java SpringBoot 使用拦截器作为权限控制的实现方法的相关内容吗,New_HackerHK在本文为您仔细讲解Java SpringBoot拦截器的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:Java,SpringBoot拦截器权限控制,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/**");//拦截管理员接口
    }
}

加载全部内容

相关教程
猜你喜欢
用户评论