Laze

If I rest I rust !

  博客园  :: 首页  :: 新随笔  ::  ::  :: 管理

 

 

实现HandlerInterceptor自定义拦截器
package com.*.*.interceptor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

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

/**
 * @Auther: Tsui
 * @Description:
 */

@Component
public class MyInterceptor implements HandlerInterceptor {

    private final static Logger logger = LoggerFactory.getLogger(MyInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        logger.info("interceptortest pre");

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

        logger.info("interceptortest post");


    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        logger.info("interceptortest after");

    }
}


重写
WebMvcConfigurationSupport中的addInterceptors方法
package com.*.*.interceptor;
import com.nh.oms.common.interceptor.MyInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.*;


/**
* @Auther: Tsui

* @Description:
*/
@Configuration
public class MyWebMvcConfigurationSupport extends WebMvcConfigurationSupport {

/**
* 配置静态资源
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
registry.addResourceHandler("/templates/**").addResourceLocations("classpath:/templates/");
super.addResourceHandlers(registry);
}

@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")//设置允许跨域的路径
.allowedOrigins("*")//设置允许跨域请求的域名
.allowCredentials(true)//是否允许证书 不再默认开启
.allowedMethods("GET", "POST", "PUT", "DELETE")//设置允许的方法
.maxAge(3600);//跨域允许时间
}

@Override
public void addInterceptors(InterceptorRegistry registry) {
//addPathPatterns 用于添加拦截规则
//excludePathPatterns 用于排除拦截
registry.addInterceptor(new MyInterceptor()).addPathPatterns("/**");
// .excludePathPatterns("/hlladmin/login") //登录页
super.addInterceptors(registry);
}
}
 

 

 

 

  没有英汉互译结果
  请尝试网页搜索
  没有英汉互译结果
  请尝试网页搜索
  没有英汉互译结果
  请尝试网页搜索
posted on 2018-11-08 11:24  CollinTsui  阅读(422)  评论(0编辑  收藏  举报