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

springboot使用拦截器判断是否登录

程序员文章站 2022-03-21 16:22:32
目录springboot拦截器判断是否登录实现拦截器的两个步骤1、自定义拦截器2、自定义配置类继承webmvcconfigureradapterspringboot 增加拦截器判断是否登录1、创建拦截...

springboot拦截器判断是否登录

实现拦截器的两个步骤

  • 自定义拦截器实现handlerinterceptor接口
  • 创建一个配置类继承webmvcconfigureradapter类并重写addinterceptors方法

代码:

1、自定义拦截器

@component
public class adminlogininterceptor implements handlerinterceptor { 
//    在请求处理之前调用,只有返回true才会执行请求
    @override
    public boolean prehandle(httpservletrequest httpservletrequest, httpservletresponse httpservletresponse, object o) throws exception {
//        得到session
        httpsession session = httpservletrequest.getsession(true);
//        得到对象
        object admin = session.getattribute("admin");
//        判断对象是否存在
        if(admin!=null){
            return true;
        }else{
//            不存在则跳转到登录页
            httpservletresponse.sendredirect(httpservletrequest.getcontextpath()+"/login/adminlogin");
            return false;
        }
    }
 
//    试图渲染之后执行
    @override
    public void posthandle(httpservletrequest httpservletrequest, httpservletresponse httpservletresponse, object o, modelandview modelandview) throws exception { 
    }
 
//    在请求处理之后,视图渲染之前执行
    @override
    public void aftercompletion(httpservletrequest httpservletrequest, httpservletresponse httpservletresponse, object o, exception e) throws exception {
 
    }
}

2、自定义配置类继承webmvcconfigureradapter

@springbootconfiguration
public class adminloginadapter extends webmvcconfigureradapter { 
    @autowired
    adminlogininterceptor adminlogininterceptor;
 
    @override
    public void addinterceptors(interceptorregistry registry) {
        registry.addinterceptor(adminlogininterceptor).addpathpatterns("/admin/**").excludepathpatterns("/login/**");
        super.addinterceptors(registry);
    }
}

springboot 增加拦截器判断是否登录

1、创建拦截器

package com.example.demo.interceptor;
import org.slf4j.logger;
import org.slf4j.loggerfactory;
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;
/**
 * 〈一句话功能简述〉<br>
 * 〈拦截器〉
 *
 * @author 丶zh1guo
 * @create 2018/11/22
 * @since 1.0.0
 */
public class logininterceptor implements handlerinterceptor {
    private logger logger = loggerfactory.getlogger(logininterceptor.class);
    // 在请求处理之前,只有返回true才会执行请求
    @override
    public boolean prehandle(httpservletrequest request, httpservletresponse response, object handler) throws exception {
        logger.info("[拦截器]启动登录状态拦截");
        // 得到session
        httpsession session = request.getsession();
        logger.info("[拦截器]sessionid:" + session.getid());
        // 得到用户信息
        object userinfo = session.getattribute("userinfo");
        //判断用户是否登录
        if (userinfo != null) {
            logger.info("[拦截器]用户已经登录,用户名,密码:" + session.getattribute("userinfo"));
            return true;
        } else {
            //不存在跳转至登录页
            response.sendredirect(request.getcontextpath() + "/");    // 跳转到首页登录
            logger.info("[拦截器]用户没有登录,已跳转到:" + request.getcontextpath() + "/");
            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 {
    }
}

2、继承webmvcconfigureadapter类

覆盖其addinterceptors接口,注册自定义的拦截器

@configuration 注解一定要有

package com.example.demo.interceptor;
import org.springframework.context.annotation.configuration;
import org.springframework.web.servlet.config.annotation.interceptorregistry;
import org.springframework.web.servlet.config.annotation.webmvcconfigurer;
/**
 * 〈一句话功能简述〉<br>
 * 〈自定义配置类〉
 *
 * @author 丶zh1guo
 * @create 2018/11/22
 * @since 1.0.0
 */
@configuration
public class loginconfig implements webmvcconfigurer {
    /**
     * 该方法用于注册拦截器
     * 可注册多个拦截器,多个拦截器组成一个拦截器链
     */
    @override
    public void addinterceptors(interceptorregistry registry) {
        // addpathpatterns 添加路径
        // excludepathpatterns 排除路径
        registry.addinterceptor(new logininterceptor())
                .addpathpatterns("/sys/*"); // 拦截sys路径下的url
//              .excludepathpatterns("");
    }
}

3、logincontroller

/**
 * copyright (c), 2017-2018, xxx有限公司
 * filename: logincontroller
 * author:   丶zh1guo
 * date:     2018/11/22 11:10
 * description: 登录
 * history:
 * <author>          <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号              描述
 */
package com.example.demo.controller;
import com.example.demo.dao.userdao;
import com.example.demo.pojo.user;
import org.slf4j.logger;
import org.slf4j.loggerfactory;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.stereotype.controller;
import org.springframework.web.bind.annotation.requestmapping;
import org.springframework.web.bind.annotation.requestmethod;
import org.springframework.web.bind.annotation.responsebody;
import javax.servlet.http.httpservletrequest;
/**
 * 〈一句话功能简述〉<br>
 * 〈登录〉
 *
 * @author 丶zh1guo
 * @create 2018/11/22
 * @since 1.0.0
 */
@controller
public class logincontroller {
    // 日志
    private logger logger = loggerfactory.getlogger(logincontroller.class);
    @autowired
    private userdao userdao;
    // 启动服务自动跳转登录
//    @requestmapping(value = {"/", "/login"})
    @requestmapping(value = "/")
    public string login() {
        return "login";
    }
    // 登录
    @requestmapping(value = "/logincheck", method = requestmethod.post)
    @responsebody
    public string logincheck(httpservletrequest request) {
        // 获取登录信息
        string username = request.getparameter("username");
        string password = request.getparameter("password");
        // 封装成对象
        user user = new user();
        user.setusername(username);
        user.setpassword(password);
        // 校验用户信息
        user info = userdao.checkuser(user);
        if (info != null) {
            request.getsession().setattribute("userinfo", username + "-" + password);
            logger.info("登录成功,用户名:" + username + "密码:" + password);
            return "success";
        } else {
            logger.info("登录失败,用户名:" + username + "密码:" + password);
            return "fail";
        }
    }
}

4、未登录会自动跳转到登录页面

springboot使用拦截器判断是否登录

springboot使用拦截器判断是否登录

springboot使用拦截器判断是否登录

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。