Spring 拦截器配置

Posted 七脉

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring 拦截器配置相关的知识,希望对你有一定的参考价值。

1.编写拦截器,实现HandlerInterceptor接口

package com.shareworx.interceptor;

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

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

import com.alibaba.fastjson.JSONObject;
import com.shareworx.platform.mvc.SessionContext;
import com.shareworx.platform.mvc.ThreadLocalContextHolder;
import com.shareworx.platform.util.SpringUtils;
import com.shareworx.yjwy.login.commons.APPResultMsgCommons;
import com.shareworx.yjwy.login.commons.LoginCommons;
import com.shareworx.yjwy.login.service.IAPPLoginAuthorizationService;
/**
 * 
 * @author zhenwei.shi
 * 用于处理APP请求拦截操作
 */
public class APPHttpRequestInterceptor implements HandlerInterceptor {
    // 将不走监听的Action的url放进FILTERURIS
    private static final String[] FILTERURIS = new String[] { "/app/login","/app/isalready/login" };
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        String requestUri = request.getRequestURI().substring(request.getContextPath().length());
        for (String uri : FILTERURIS) {
            if (requestUri.startsWith(uri)) {
                return true;
            }
        }
        int validState = validateRequest(request);
        if (LoginCommons.SUCCESSCODE.equals(validState)) {
            return true;
        } else {
            JSONObject json = new JSONObject();
            json.put(APPResultMsgCommons.CODE, validState);
            String msg = "";
            if(LoginCommons.USEROTHORALREADYLOGIN.equals(validState)){
                msg="用户已经在其他地点登录";
            }else if(LoginCommons.USERCOOKIEERROR.equals(validState)){
                msg="请重新登录";
            }
            json.put(APPResultMsgCommons.MSG, msg);
            response.setContentType("application/json; charset=utf-8");
            response.getWriter().write(json.toJSONString());
            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 {
    }

    /**
     * 
     * @param request
     * @return
     */
    private Integer validateRequest(HttpServletRequest request) {
        IAPPLoginAuthorizationService service = SpringUtils.getBean(IAPPLoginAuthorizationService.ID);
        String sessionId="";
        String userName="";
        Cookie[] cookies = request.getCookies();
        if(null==cookies||cookies.length<1){
            return LoginCommons.USERCOOKIEERROR;
        }
        for(Cookie cookie : cookies){
            if(APPResultMsgCommons.LOGINCOOKIENAME.equals(cookie.getName())){
                sessionId = cookie.getValue();
            }
            if(APPResultMsgCommons.LOGINUSERNAME.equals(cookie.getName())){
                userName = cookie.getValue();
            }
        }
        if(service.isAlreadyLoginForSelf(sessionId)){
            SessionContext context = new SessionContext(sessionId);
            ThreadLocalContextHolder.setContext(context);
            return LoginCommons.SUCCESSCODE;
        }
        if(service.isAlreadyLogin(userName)){
            return LoginCommons.USEROTHORALREADYLOGIN;
        }
        return LoginCommons.USERCOOKIEERROR;
    }
}

2.配置拦截适配器 并定义拦截范围

package com.shareworx.interceptor;

import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
/**
 * 
 * @author zhenwei.shi
 * 用于配置全局控制拦截操作
 */
@Configuration
public class YJWYWebConfiguration extends WebMvcConfigurerAdapter {
    
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
//        registry.addViewController("/").setViewName("view/main/index.html");
        registry.setOrder(Ordered.HIGHEST_PRECEDENCE);
        super.addViewControllers(registry);
    }
    
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        /*WebAuthInterceptor interceptor = new WebAuthInterceptor();
        interceptor.addExcludeMapping("/view/login/");
        interceptor.addExcludeMapping("/view/main/");
        interceptor.addExcludeMapping("/pageerror");
        interceptor.addExcludeMapping("/jsonerror");
        interceptor.addExcludeMapping("/error");
        registry.addInterceptor(interceptor);*/
        
        YJWYHttpRequestInterceptor requestInterceptor = new YJWYHttpRequestInterceptor();
        registry.addInterceptor(requestInterceptor).addPathPatterns("/yjwy/**");
        APPHttpRequestInterceptor appRequestInterceptor = new APPHttpRequestInterceptor();
        registry.addInterceptor(appRequestInterceptor).addPathPatterns("/app/**");
    }
}

 

以上是关于Spring 拦截器配置的主要内容,如果未能解决你的问题,请参考以下文章

Spring 拦截器配置

spring AOP 拦截器实现问题

spring boot怎么配置拦截器

如何配置spring拦截器以在每个请求中调用

Spring Boot 优雅的配置拦截器方式

Spring Security自定义拦截器