springboot使用攔截器判斷是否登錄

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、未登錄會自動跳轉到登錄頁面

以上為個人經驗,希望能給大傢一個參考,也希望大傢多多支持WalkonNet。

推薦閱讀: