Spring boot配置拦截器

虽然Spring还用得不怎么熟,最近就开始折腾Spring boot 了,还是那句话,废话少说,直接上码吧:

package com.jiaobuchong.springboot.interceptor;

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

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

/**
 * file: UserInterceptor.java
 * Created by jiaobuchong on 12/23/15.
 */
public class UserInterceptor implements HandlerInterceptor {
    private static final Logger logger = LoggerFactory.getLogger(UserInterceptor.class);
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        /**
         * 对来自后台的请求统一进行日志处理
         */
        String url = request.getRequestURL().toString();
        String method = request.getMethod();
        String uri = request.getRequestURI();
        String queryString = request.getQueryString();
        System.out.println(request.getParameterMap());
        logger.info(String.format("请求参数, url: %s, method: %s, uri: %s, params: %s", url, method, uri, queryString));
        return true;
    }

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

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}

上面这个类UserInterceptor implements Spring的HandlerInterceptor定义一个拦截器类,下面是成功的关键,怎么让Spring boot 知道你这个拦截器呢?现在定义另外一个类,对我们刚才定义的拦截器配置一下。
看码:

package com.jiaobuchong.springboot.configure;

import com.jiaobuchong.springboot.interceptor.UserInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

/**
 *file: CustomWebMvcConfigurerAdapter.java
 * Created by jiaobuchong on 12/23/15.
 */
@Configuration   //标注此文件为一个配置项,spring boot才会扫描到该配置。该注解类似于之前使用xml进行配置
public class CustomWebMvcConfigurerAdapter extends WebMvcConfigurerAdapter {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new UserInterceptor()).addPathPatterns("/user/**");  //对来自/user/** 这个链接来的请求进行拦截
    }
}

下面万事具备,快去测试吧,所有的请求都在你的控制之下了……
可以参考我github的代码:https://github.com/jiaobuchong/spring-demo/tree/master/spring-boot/spring-boot1

你可能感兴趣的:(spring)