從零搭建本身的SpringBoot後臺框架(十九)

Hello你們好,本章咱們添加攔截器功能 。有問題能夠聯繫我mr_beany@163.com。另求各路大神指點,感謝

在web開發的過程當中,爲了實現登陸權限驗證,安全驗證等,咱們每每須要添加一個攔截器在用戶的的請求到達controller層的時候實現登陸驗證,那麼SpringBoot如何添加攔截器呢?
java

一:添加攔截器

打開core→configurer→WebConfigurergit

添加以下github

/**
 * TODO  修改成本身的需求
 */
private static final String IZATION = "CHUCHEN";

/**
 * 添加攔截器  請求頭攔截
 */
@Override
public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(
            //注意,HandlerInterceptorAdapter  這裏能夠修改成本身建立的攔截器
            new HandlerInterceptorAdapter() {
                @Override
                public boolean preHandle(HttpServletRequest request,
                                         HttpServletResponse response, Object handler) throws Exception {
                    String ization = request.getHeader("ization");
                    if(IZATION.equals(ization)){
                        return true;
                    }else{
                        RetResult<Object> result = new RetResult<>();
                        result.setCode(RetCode.UNAUTHORIZED).setMsg("簽名認證失敗");
                        responseResult(response, result);
                        return false;
                    }
                }
            }
            //這裏添加的是攔截的路徑  /**爲所有攔截
        ).addPathPatterns("/userInfo/selectAlla");
}private void responseResult(HttpServletResponse response, RetResult<Object> result) {
    response.setCharacterEncoding("UTF-8");
    response.setHeader("Content-type", "application/json;charset=UTF-8");
    response.setStatus(200);
    try {
        response.getWriter().write(JSON.toJSONString(result, SerializerFeature.WriteMapNullValue));
    } catch (IOException ex) {
        LOGGER.error(ex.getMessage());
    }
}複製代碼

二:測試

輸入localhost:8080/userInfo/selectAllweb


輸入localhost:8080/userInfo/selectAllaspring


在header中添加簽名json


三:本身建立攔截器

建立core→interceptor→Interceptor1安全

package com.example.demo.core.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

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

public class Interceptor1 implements HandlerInterceptor {

    /**
     * 在請求處理以前進行調用(Controller方法調用以前)
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        System.out.println(">>>MyInterceptor1>>>>>>> preHandle");
        // 只有返回true纔會繼續向下執行,返回false取消當前請求
        return true;
    }

    /**
     * 請求處理以後進行調用,可是在視圖被渲染以前(Controller方法調用以後)
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
        System.out.println(">>>MyInterceptor1>>>>>>> postHandle");
    }

    /**
     * 在整個請求結束以後被調用,也就是在DispatcherServlet 渲染了對應的視圖以後執行(主要是用於進行資源清理工做)
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        System.out.println(">>>MyInterceptor1>>>>>>> afterCompletion");
    }
}複製代碼

四:修改WebConfigurer配置

修改addInterceptors  方法以下bash

@Override
public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(
            //注意,HandlerInterceptorAdapter  這裏能夠修改成本身建立的攔截器
            new Interceptor1() {
                @Override
                public boolean preHandle(HttpServletRequest request,
                                         HttpServletResponse response, Object handler) throws Exception {
                    String ization = request.getHeader("ization");
                    if(IZATION.equals(ization)){
                        return true;
                    }else{
                        RetResult<Object> result = new RetResult<>();
                        result.setCode(RetCode.UNAUTHORIZED).setMsg("簽名認證失敗");
                        responseResult(response, result);
                        return false;
                    }
                }
            }
            //這裏添加的是攔截的路徑  /**爲所有攔截
        ).addPathPatterns("/userInfo/selectAlla");
}複製代碼

五:測試

輸入localhost:8080/userInfo/selectAllaapp


在header中添加簽名ide


成功

項目地址

碼雲地址: gitee.com/beany/mySpr…

GitHub地址: github.com/MyBeany/myS…

寫文章不易,如對您有幫助,請幫忙點下star

結尾

添加攔截器功能已完成,後續功能接下來陸續更新,有問題能夠聯繫我mr_beany@163.com。另求各路大神指點,感謝你們。

相關文章
相關標籤/搜索