In CMS, BBS, and other systems, there will be post module, and the article will contain attachments and images. When you click an attachment, the SAVE dialog box may appear and the browser will open it directly, for example, the connection is/zlgc/admin/uploadattach/20110409/20110409145547 _708.doc. This saves or opens in different browsers. Of course, we can also unify this behavior and use the filter in J2EE to filter each download connection, add the header of the attachment to the HTTP response to each request. The core statement is as follows:
<% @ Page contenttype = "application/MSWord; charset = utf8" %>
<! -- In the preceding line, set this webpage to a webpage in Word format -->
<%
// Response. setheader ("content-disposition", "inline; filename=test1.doc"); // open the file in IE
Response. setheader ("content-disposition", "attachment; filename=test1.doc"); // download method, which can be opened without a browser
// Set the file name test1.doc to be transferred to the browser
// This line enables the browser to receive a Word document
%>
Procedure:
1. Create a common Java file in the project as the filter processing body.
2. Modify the filter to implement the javax. servlet. Filter interface and implement the init, dofilter, and destroy methods in the interface.
3. Configure XML and add filter.
<Filter>
<Filter-Name> attachfilter </filter-Name>
<Filter-class> servlet. attachfilter </filter-class>
</Filter>
<Filter-mapping>
<Filter-Name> attachfilter </filter-Name>
<URL-pattern>/admin/uploadattach/* </url-pattern>
</Filter-mapping>
4. Restart tomcat.
Note: The filter execution sequence is in XML.
Detailed Java code:
Package servlet;
Import java. Io. ioexception;
Import java. util. date;
Import javax. servlet. filter;
Import javax. servlet. filterchain;
Import javax. servlet. filterconfig;
Import javax. servlet. servletexception;
Import javax. servlet. servletrequest;
Import javax. servlet. servletresponse;
Import javax. servlet. http. httpservletrequest;
Import javax. servlet. http. httpservletresponse;
Public class attachfilter implements filter {
Private filterconfig = NULL;
Public void destroy (){
Filterconfig = NULL;
}
Public void dofilter (servletrequest request, servletresponse response,
Filterchain chain) throws ioexception, servletexception {
Httpservletrequest hreq = (httpservletrequest) request;
Httpservletresponse hresp = (httpservletresponse) response;
System. Out. println (new date () + "filter ");
String url = hreq. getrequesturi ();
String filename = URL. substring (URL. lastindexof ('/') + 1); // get the file name to be downloaded
System. Out. println (hreq. getrequesturi ());
System. Out. println (filename );
Hresp. setheader ("content-disposition", "attachment; filename =" + filename );
// Hresp. addheader ("content-disposition", "attachment; filename =" + filename );
Chain. dofilter (hreq, hresp );
}
Public void Init (filterconfig arg0) throws servletexception {
This. filterconfig = arg0;
}
}