1. 程式人生 > >【第四十章】Spring Boot 自定義攔截器

【第四十章】Spring Boot 自定義攔截器

ram obj pre .config factor ati bean configure 邏輯

1.首先編寫攔截器代碼

package com.sarnath.interceptor;

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

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

import com.sarnath.constants.Constants; import com.sarnath.controller.BaseController; import com.sarnath.dto.output.UserOutput; /** * 自定義攔截器 * @Description * @author Sunny * @date 2018年1月15日 */ @Service public class CustomerInterceptor extends BaseController implements HandlerInterceptor { @Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { String url = request.getRequestURI().substring(1,request.getRequestURI().length()-1); /**登錄和退出登錄不做攔截*/ if(noLoginUrl.contains(url)){ return
true; } //判斷用戶是否已登錄 UserOutput user = getLoginUser(request, response); if(user == null || user.getUserId() == null){ response.sendRedirect("/index"); return false; } //判斷當前用戶請求路徑是否擁有對應權限 boolean allowRequesst = false; if(user.getUserType() == Constants.USER_TYPE_ADMIN){ if(adminUrl.contains(url)){ allowRequesst = true; } }else if(user.getUserType() == Constants.USER_TYPE_TEACHER){ if(teacherUrl.contains(url)){ allowRequesst = true; } }else if(user.getUserType() == Constants.USER_TYPE_STUDENT){ if(studentUrl.contains(url)){ allowRequesst = true; } } if(allowRequesst){ return allowRequesst; } //默認跳轉到登錄頁面 response.sendRedirect("/index"); 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.將攔截器增加到Spring Boot配置中

package com.sarnath.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import com.sarnath.interceptor.CustomerInterceptor;

@Configuration
public class InterceptorConfig extends WebMvcConfigurerAdapter {
    @Autowired
    private CustomerInterceptor interceptor;
    /**
     * 添加攔截器到Spring Boot配置中
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(interceptor).addPathPatterns("/**");
    }
}

Ok,只需要這兩部,設置好方法或路徑的攔截業務邏輯即可

【第四十章】Spring Boot 自定義攔截器