由于jfinal開啟gzip導(dǎo)致返回頭部content-length為0從而導(dǎo)致小程序獲取進(jìn)度失敗問題
- 問題原因
gzip會(huì)使得content-length不生效,因?yàn)榉?wù)器認(rèn)為如果你開啟了gzip最后的壓縮結(jié)果和你提供的length將會(huì)不一致,所以會(huì)移除content-length
- 處理方法分析
//UndertowServer類中存在此方法
protected HttpHandler configGzip(HttpHandler pathHandler) {
if (config.isGzipEnable()) {
//undertow使用HttpHandler 做為請(qǐng)求處理鏈,而如果開啟了gzip則加入EncodingHandler處理器
//ContentEncodingRepository 中便是最終判斷是否需要處理gzip
ContentEncodingRepository repository = new ContentEncodingRepository();
GzipEncodingProvider provider = new GzipEncodingProvider(config.getGzipLevel());
int minLength = config.getGzipMinLength();
Predicate predicate = minLength > 0 ? Predicates.maxContentSize(minLength) : Predicates.truePredicate();
repository.addEncodingHandler("gzip", provider, 100, predicate);
return new EncodingHandler(pathHandler, repository);
}
return pathHandler;
}
}
由上得出兩種處理方式1.在ContentEncodingRepository處擴(kuò)展做手腳2.HttpHandler 處做手腳.
- 處理辦法1
protected HttpHandler configGzip(HttpHandler pathHandler) {
if (config.isGzipEnable()) {
ContentEncodingRepository repository = new ContentEncodingRepositoryExt();
GzipEncodingProvider provider = new GzipEncodingProvider(config.getGzipLevel());
int minLength = config.getGzipMinLength();
Predicate predicate = minLength > 0 ? Predicates.maxContentSize(minLength) : Predicates.truePredicate();
repository.addEncodingHandler("gzip", provider, 100, predicate);
return new EncodingHandler(pathHandler, repository);
}
return pathHandler;
}
復(fù)寫UndertowServer重寫configGzip,并且新建io.undertow.server.handlers.encoding.ContentEncodingRepository#getContentEncodings子類復(fù)寫getContentEncodings方法,在處理前判斷當(dāng)前請(qǐng)求的url是否需要過濾,如果過濾則返回null,否則繼續(xù)執(zhí)行g(shù)zip后續(xù)代碼.
- 處理辦法2
//復(fù)寫UndertowServer重寫configGzip,并且新建HttpHandler 的子類FileHttpHandler
protected HttpHandler configGzip(HttpHandler pathHandler) {
return new FileHttpHandler(super.configGzip(pathHandler));
}
//在FileHttpHandler 內(nèi)部處理掉由getContentEncodings方法使用的ACCEPT_ENCODING,便可實(shí)現(xiàn)
public void handleRequest(HttpServerExchange exchange) throws Exception {
if (exchange.getRequestURI().startsWith("/file")){
exchange.getRequestHeaders().remove(Headers.ACCEPT_ENCODING);
}
next.handleRequest(exchange);
}
筆者采用第二種因?yàn)榇a少,更容易理解.