1. 程式人生 > 實用技巧 >登入攔截器 HandlerInterceptor 針對web提供的介面

登入攔截器 HandlerInterceptor 針對web提供的介面

為了統一區分所有請求,將所有的請求加上.do

登入,如果使用者登入成功後,則生成一個隨機的字串,將字串作為key儲存在redis中。

登入攔截時,也只攔截.do請求,如果通過字串查詢到資訊,則視為登入。否則未登入

增加配置LoginInterceptorConfig, 這裡設定我們要攔截的是什麼,哪些攔截,哪些不攔截,特殊例外

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import com.ccjr.business.aop.LoginInterceptor;

import lombok.
extern.slf4j.Slf4j; /** * @Description : 登入攔截器 * @author : Chenweixian * @Date : 2020年11月3日 下午6:49:09 */ @Slf4j @Configuration public class LoginInterceptorConfig implements WebMvcConfigurer{ @Value("${login.uriIgnore:/login/*}") private String LOGIN_URIIGNORE; @Autowired private LoginInterceptor interceptor;
public static final String PATH_PATTERNS = "/*/*.do,*.do"; @Override public void addInterceptors(InterceptorRegistry registry) { //addPathPatterns 用於新增攔截規則 //excludePathPatterns 用於排除攔截 registry.addInterceptor(interceptor) .addPathPatterns(PATH_PATTERNS.split(
",")) .excludePathPatterns(LOGIN_URIIGNORE.split(",")); log.info("登入攔截器註冊成功!"); } }

增加攔截器LoginInterceptor ,攔截所有的請求

import java.io.IOException;
import java.io.PrintWriter;

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

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.ccjr.base.BaseApiService;
import com.ccjr.base.BaseResponse;
import com.ccjr.business.web.controller.BaseController;
import com.ccjr.business.web.services.LoginServices;
import com.ccjr.commons.constants.ApiErrorEnum;

import lombok.extern.slf4j.Slf4j;

/**
 * @Description : d登入攔截器
 * @Company : 晨創科技
 * @author : Chenweixian
 * @Date : 2020年11月5日 下午1:24:54
 */
@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private LoginServices loginServices;
    @Autowired
    protected StringRedisTemplate stringRedisTemplate;
    @Autowired
    protected BaseApiService baseApiService;
    
    /**
     * 在業務處理器處理請求之前被呼叫。預處理,可以進行編碼、安全控制、許可權校驗等處理;
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        String token = request.getHeader(BaseController.LOGIN_USER_TOKEN);
        if (StringUtils.isEmpty(token)) {
            returnJson(response);
            return false;
        }
        String userInfoString = stringRedisTemplate.boundValueOps(token).get();
        if (StringUtils.isEmpty(userInfoString)) {
            returnJson(response);
            return false;
        }
        if (!StringUtils.isEmpty(token)) {
            loginServices.refreshLoginToken(token);
        }
        return true;
    }

    /**
     * 在業務處理器處理請求執行完成後,生成檢視之前執行。後處理(呼叫了Service並返回ModelAndView,但未進行頁面渲染),有機會修改ModelAndView;
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
            ModelAndView modelAndView) throws Exception {
//        log.info("postHandle...");
    }

    /**
     * 在DispatcherServlet完全處理完請求後被呼叫,可用於清理資源等。返回處理(已經渲染了頁面);
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
//        log.info("afterCompletion...");
    }
    
    private void returnJson(HttpServletResponse response){
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        try {
            BaseResponse baseResponse = baseApiService.setResultError(ApiErrorEnum.USER_LOGIN_20103);
            writer = response.getWriter();
            writer.print(baseResponse);
        } catch (IOException e){
            log.error("攔截器輸出流異常",e);
        } finally {
            if(writer != null){
                writer.close();
            }
        }
    }
}

完。