SpringBoot登录拦截器

SpringBoot 登录拦截器,这里的版本是2.0.4版本

1.编写拦截器实现类,实现接口 HandlerInterceptor,

重写里面需要的三个比较常用的方法,实现自己的业务逻辑代码

(就是自己拦截器拦截时做什么处理)

package com.bigbug.wanrong.travel.api.config;

import com.bigbug.wanrong.travel.api.model.User;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class SysInterceptor extends HandlerInterceptorAdapter {
    /**
     * 进入拦截器后首先进入的方法
     * 返回false则不再继续执行
     * 返回true则继续执行
     */
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler)throws Exception
    {
        System.out.println("我是拦截器:我证明我进来了");
        HttpSession session=request.getSession();
        User userInfo = (User)session.getAttribute("userInfo");
        if(userInfo==null) {
            System.out.println("我证明用户没有登录");
            response.sendRedirect(request.getContextPath()+"/login.html"); // login.html 是你的登陆页地址
           return false;
        }
        System.out.println("我证明用户已经登录");
        return  true;
    }
    /**
     * 生成视图时执行,可以用来处理异常,并记录在日志中
     */
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response,
                                Object arg2, Exception exception){
                //-----------------//
    }

    /** -
     * 生成视图之前执行,可以修改ModelAndView
     */
    public void postHandle(HttpServletRequest request,
                           HttpServletResponse response,
                           Object arg2, ModelAndView arg3)
            throws Exception{
            //----------------------------//
    }
}
编写拦截器配置文件类并继承  WebMvcConfigurer类,并重写其中的方法  addInterceptors并且在主类上加上注解  @Configuration

这里的是网上的常用拦截器,仅做个人学习记录。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值