欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

springboot配置interceptor,并且实现权限登录

程序员文章站 2022-04-19 21:27:05
...

1.开始interceptor的配置

配置interceptor不和filter一样,filter一个@component 和一个@WebFilter注解就配置成功,而interceptor不是

interceptor

package com.van.mall.controller.common.interceptor;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Van
 * @date 2020/3/24 - 12:12
 */
@Slf4j
public class AuthorityInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("preHandle");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        log.info("postHandle" );
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.info("afterCompletion");
    }
}

这里要继承HandlerInterceptor接口,实现三个方法
分别是在controller之前,在controller执行之后,和所有结束后触发

配置interceprot

package com.van.mall.configuration;

import com.van.mall.controller.common.interceptor.AuthorityInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

/**
 * @author Van
 * @date 2020/3/24 - 13:10
 */
@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {
    @Override
    protected void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new AuthorityInterceptor()).addPathPatterns("/manage/**");
        super.addInterceptors(registry);
    }
}

这里别忘记加上@Configuration注解,这里继承WebMvcConfigurationSupport 类, 重写addInterceptors方法,简单理解起来就是把registry 配置好(加入我自定义的interceptor类),然后把registry加入。就成功配置好了interceptor
这里path:
/manage/** /** 是指它下面的所有,比如/manage/user/login.do。如果是/*
那么只能拦截到/manage/login.do方法。

这篇不错

2.实战,用interceptor来验证用户登录权限

package com.van.mall.controller.common.interceptor;

import com.van.mall.common.Const;
import com.van.mall.common.ServerResponse;
import com.van.mall.entity.User;
import com.van.mall.service.serviceImpl.UserServiceImpl;
import com.van.mall.util.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Map;

/**
 * @author Van
 * @date 2020/3/24 - 12:12
 */
@Slf4j
public class AuthorityInterceptor implements HandlerInterceptor {
    @Resource
    private UserServiceImpl userService;//没错,interceptor中是可以注入其它bean的

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
       //用request获取HttpSession,我用的是springSession,信息都保存在session中。
        HttpSession session=request.getSession();//注意。不能在方法里面加入session,要不然和父类的方法不一致了
        log.info("preHandle");
        //把handler强转为Methodhandler
        HandlerMethod handlerMethod=(HandlerMethod)handler;
        //获取拦截到的是哪一个类名和方法名
        String methodName=handlerMethod.getMethod().getName();
        String className=handlerMethod.getBean().getClass().getSimpleName();
        //...................................
        //用iterator遍历出来request中的ParameterMap
        Map requestMap=request.getParameterMap();
        Iterator it=requestMap.entrySet().iterator();
        StringBuffer stringBuffer=new StringBuffer();
        //show requestParamMap
        while (it.hasNext()){
            String value=StringUtils.EMPTY;
            Map.Entry entry=(Map.Entry) it.next();
            String key=(String) entry.getKey();
            if (entry.getValue() instanceof String[]){
                value= Arrays.toString((String[])entry.getValue());
            }else {
                value=(String)entry.getValue();
            }
            stringBuffer.append(key).append("=").append(value);
        }
        //。。。。。。。。。。。。。。。。。。。。
        //要在interceptor里面返回出来json,就得做一下response的配置
        response.reset();//重置response 要不然会报错
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");//说明要返回json
        PrintWriter writer=response.getWriter();
        //end。。。。。。。。。。。。。。。。。。。。。。。。。。。
        User user=(User) session.getAttribute(Const.CURRENT_USER);
        if (user==null||(user.getRole()!=Const.Role.ROLE_ADMIN)) {
            if (user == null) {
                //要把类变为jsonString,print出来才显示正常的值,直接print一个对象。只会显示该对象的类名和它的id
                writer.println(JsonUtil.object2String(ServerResponse.error("亲还没有登录呢")));
            } else {
                writer.println(JsonUtil.object2String(ServerResponse.error("没有管理员权限")));
            }
            writer.flush();//清空print中的值
            writer.close();//关闭它
            return false;//既然验证失败就不让这次请求放到controller中了
        }
        return true;//验证通过那么就放行到controller中继续执行业务逻辑

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        log.info("postHandle" );
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.info("afterCompletion");
    }
}

注解写的很详细了,对了,得到了哪个class和哪个method 就可以对其进行更细粒度的操控。