spring cloud gateway转发静态资源
最近遇到spring cloud gateway转发静态资源spring:gateway:routes:- id: dh-xxljoburi: lb://dh-xxljobpredicates:- Path=/redirect/**filters:# 第一个predicates地址, 第二个是要转发的地址, 如果要做动态上下文请参考【附加动态上下文】
·
最近遇到spring cloud gateway转发静态资源
spring:
gateway:
routes:
#内部代理
- id: xxl-job
uri: lb://xxl-job
predicates:
- Path=/redirect/**
filters:
# 第一个predicates地址, 第二个是要转发的地址, 如果要做动态上下文请参考【附加动态上下文】
- RewritePath=/redirect/(?<segment>.*), /redirect/$\{segment}
#外部代理
- id: proxy-url
uri: https://blog.csdn.net
predicates:
- Path=/proxy/**
filters:
# 第一个predicates地址, 第二个是要转发的地址, 如果要做动态上下文请参考【附加动态上下文】
- RewritePath=/proxy/(?<segment>.*), /$\{segment}
附加动态上下文
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
*
* 动态上下文
* @author HanKeQi
* @Date 2021/8/7 4:51 下午
* @Version 1.0
*/
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class DynamicContextPathFilter extends OncePerRequestFilter {
private final static Pattern pattern = Pattern.compile("^(?<contextPath>/[^/]+)(?<servletPath>.*)$");
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
Matcher matcher = pattern.matcher(request.getServletPath());
if(matcher.matches()) {
final String contextPath = matcher.group("contextPath");
final String servletPath = matcher.group("servletPath");
if(servletPath.trim().isEmpty()) {
response.sendRedirect(atomicReference.get()+"/");
return;
}
filterChain.doFilter(new HttpServletRequestWrapper(request) {
@Override
public String getContextPath() {
return contextPath;
}
@Override
public String getServletPath() {
return servletPath;
}
}, response);
} else {
filterChain.doFilter(request, response);
}
}
@Override
protected String getAlreadyFilteredAttributeName() {
return this.getClass().getName() + OncePerRequestFilter.ALREADY_FILTERED_SUFFIX;
}
更多推荐
已为社区贡献1条内容
所有评论(0)