码上敲享录 > SpringBoot常见问题详解 > springboot实现拦截器

springboot实现拦截器

上一章章节目录下一章 2019-05-17已有96人阅读 评论(0)

springboot实现拦截器


解决方法:

1.拦截器

import org.springframework.boot.web.servlet.FilterRegistrationBean;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

import org.springframework.http.HttpHeaders;

import org.springframework.http.HttpMethod;

import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import org.springframework.web.filter.CorsFilter;

import org.springframework.web.servlet.config.annotation.InterceptorRegistry;

import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import com.jc.admin.common.interceptor.UserInterceptorConfig;


@Configuration

public class WebAppConfig implements WebMvcConfigurer {


@Override

public void addInterceptors(InterceptorRegistry registry) {

// 注册自定义拦截器,添加拦截路径和排除拦截路径,表示/api/开头的请求都会拦截到UserInterceptorConfig的preHandle方法中

registry.addInterceptor(new UserInterceptorConfig()).addPathPatterns("/api/**");

}


}




2.拦截器业务类

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import org.springframework.beans.factory.BeanFactory;

import org.springframework.web.context.support.WebApplicationContextUtils;

import org.springframework.web.servlet.HandlerInterceptor;

import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;



/**

* 拦截过滤

*/

public class UserInterceptorConfig implements HandlerInterceptor {


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


@Override

public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)

throws Exception {

               //权限控制代码,return true可以请求

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 {


}


}


0

有建议,请留言!

  • *您的姓名:

  • *所在城市:

  • *您的联系电话:

    *您的QQ:

  • 咨询问题:

  • 提 交