spring boot使用拦截器修改请求URL
假如我要将请求路径中/foobar都去掉?1.定义拦截器package com.laoxu.test.helloweb;import org.springframework.stereotype.Component;import org.springframework.web.servlet.HandlerInterceptor;import javax.servlet....
·
假如我要将请求路径中/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/**");
}
}

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐
所有评论(0)