溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

如何使用SpringBoot攔截器實(shí)現(xiàn)登錄攔截

發(fā)布時(shí)間:2022-03-25 10:44:28 來源:億速云 閱讀:307 作者:小新 欄目:開發(fā)技術(shù)

小編給大家分享一下如何使用SpringBoot攔截器實(shí)現(xiàn)登錄攔截,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!

可以對(duì)URL路徑進(jìn)行攔截,可以用于權(quán)限驗(yàn)證、解決亂碼、操作日志記錄、性能監(jiān)控、異常處理等

如何使用SpringBoot攔截器實(shí)現(xiàn)登錄攔截

 實(shí)現(xiàn)代碼

新建 interceptor包

如何使用SpringBoot攔截器實(shí)現(xiàn)登錄攔截

添加攔截器代碼

package com.qcby.interceptor;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
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;
 
public class LoginInterceptor  implements HandlerInterceptor {
 
    @Autowired
    private HttpSession httpSession;
    //Controller邏輯執(zhí)行之前
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("preHandle....");
        String uri = request.getRequestURI();
        System.out.println("當(dāng)前路徑"+uri);
 
        /**
         * HandlerMethod=>Controller中標(biāo)注@RequestMapping的方法
         *  需要配置靜態(tài)資源不攔截時(shí),添加這塊邏輯  => 前后端分離項(xiàng)目
         */
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        if (httpSession.getAttribute("username") == null) {
            // 未登錄跳轉(zhuǎn)到登錄界面
            throw  new RuntimeException("no login!");
        } else {
            return true;
        }
    }
 
    //Controller邏輯執(zhí)行完畢但是視圖解析器還未進(jìn)行解析之前
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle....");
    }
 
    //Controller邏輯和視圖解析器執(zhí)行完畢
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        System.out.println("afterCompletion....");
    }
}

注冊(cè),配置攔截路徑和排除登錄需訪問路徑

如何使用SpringBoot攔截器實(shí)現(xiàn)登錄攔截

package com.qcby.config;
 
import com.qcby.interceptor.LoginInterceptor;
import org.springframework.context.annotation.Bean;
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 {
 
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(loginInterceptor())
                .addPathPatterns("/**")
                // 那些路徑不攔截
                .excludePathPatterns("/user/login","/error");
    }
 
    @Bean
    public LoginInterceptor loginInterceptor(){
        return new LoginInterceptor();
    }
}

實(shí)現(xiàn)類

@RestController
@RequestMapping("user")
public class UserController {
@Autowired
    private UserService userService;
    @Autowired
    private HttpSession session;
    @ApiOperation("用戶登錄接口")
    @RequestMapping(value="login",method = {RequestMethod.GET,RequestMethod.POST})
    public Map<String,Object>login(User user){
        Map<String,Object> map=new HashMap<>();
        map.put("code",0);
        if(StringUtils.isEmpty(user.getUsername())||StringUtils.isEmpty(user.getPassword())){
            map.put("msg","用戶或密碼為空!");
            return map;
        }
        QueryWrapper<User> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("username",user.getUsername())
                .eq("password",user.getPassword());
        User user1=userService.getOne(queryWrapper);
        if(user1!=null){
            map.put("cod",1);
            map.put("data",user1);
            session.setAttribute("username",user1.getUsername());
        }else {
            map.put("msg","用戶名或密碼錯(cuò)誤!");
        }
        return map;
    }
}

當(dāng)我們未登錄時(shí)我們不能進(jìn)入攔截的頁面 

如何使用SpringBoot攔截器實(shí)現(xiàn)登錄攔截

 登錄

如何使用SpringBoot攔截器實(shí)現(xiàn)登錄攔截

登錄之后我們就能進(jìn)入hello方法了 

如何使用SpringBoot攔截器實(shí)現(xiàn)登錄攔截

以上是“如何使用SpringBoot攔截器實(shí)現(xiàn)登錄攔截”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對(duì)大家有所幫助,如果還想學(xué)習(xí)更多知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI