spring boot使用拦截器修改请求URL

假如我要将请求路径中/foobar都去掉?

 

1.定义拦截器

package com.laoxu.test.helloweb;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

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

/**
 * @Description:
 * @Author laoxu
 * @Date 2019/11/3 13:45
 **/
@Component
public class GlobalInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpServletResponseWrapper httpResponse = new HttpServletResponseWrapper((HttpServletResponse) response);
        System.out.println(request.getRequestURI());
        String path=request.getRequestURI();
        if(path.indexOf("/foobar")>-1){
            path = path.replaceAll("/foobar","");
            request.getRequestDispatcher(path).forward(request,response);
        }

        return true;
    }
}

 

2.定义WebMvcConfig

 

package com.laoxu.test.helloweb.config;

import com.laoxu.test.helloweb.GlobalInterceptor;
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.WebMvcConfigurer;

/**
 * @author xusucheng
 * @create 2018-10-23
 **/

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
    @Autowired
    GlobalInterceptor globalInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(globalInterceptor).addPathPatterns("/foobar/**");
    }
}
 

 

 

posted @ 2019-11-04 22:19  一锤子技术员  阅读(20)  评论(0编辑  收藏  举报  来源