您将要创建Java“过滤器”。 检测自定义HTTP请求标头并插入响应标头,以便自动下载文件。 此最重要的响应标头是“内容类型=附件”响应标头。 您创建了一个插入自定义标头的HTTP请求对象。
functionmyhttpobject (文件路径) {
功能标记pobject (
返回new xmlhttprequest (;
}
var request=makeHttpObject (;
request.open('get ',filePath,false );
request.setrequestheader (x-wria-download,) PDFdownload );
request.send (空;
window.open (文件路径;
控制台. log (request.getallresponseheaders ();
}
这将X-Wria-Download标头插入到请求中。
接下来,您必须具有用于搜索请求标头的Java筛选器,并将响应标头设置为" Content-Type=attachment "
导入javax.servlet.*;
import javax.servlet.http.http servlet请求;
import javax.servlet.http.http无servlet保罗;
导入javax.servlet.http.http session;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
publicclasscontenttypefilterimplementsfilter {
保护文件配置文件配置文件;
公共void init (过滤器配置文件配置) throws ServletException {
this.filterConfig=filterConfig;
}
公共语音目录
//noop
}
publicvoiddofilter (servletrequestrequest,ServletResponse response,FilterChain chain ) throws IOException,ServletException {
http servlet请求req=(http servlet请求)请求;
httpservletresponseres=(http服务器响应)响应;
//gettheheadersweplacedintherequest
//based on those request headers,set some response headers
if (req.get header (x-wria-download )!=空) {
res.setheader('content-type ',' application/pdf ' );
RES.setheader (' content-disposition ',' attachment; filename=success.pdf ';
}
chain.dofilter(req,res );
}
}
当然,web.xml包含代码,所有jsp文件都包含Filter。
令我困惑的是,标题被设置在响应文件中,但它不应该下载。 RES.setheader (" content-disposition "、" attachment; filename= success.pdf "; 在“if”语句以外的行中,它可以工作,但下载行为适用于所有不需要的JSP。
if语句中有res.setHeader时,为什么它应用了内容处理但没有工作; 然后在if文件外工作吗? 如何得到必要的行为责任? ckdsc (是否仅将内容处置应用于应用了自定义请求标头的jsp?