Servlet 2.3 Filter Programming (2)
File upload filter
The last filter we will see is the POST request for processing multiplex / multi-type data, which can contain file upload. Each multi-channel / multi-type data POST request includes all parameters and files that use a special format that a servlet cannot recognize. History servlet developers use third-party classes to process upload, such as MultipArtRequest and MultipartParser classes in my com.ore.Servlet package. Here we will see a new way to use MultipartFilter to handle this request easier. This filter is based on the Parsers under the com.Oreilly.Servlet package and has been integrated into the package (see Resources).
MultipartFilter works with the request for the input request, when it discovers a file upload request (Content Type: Multipart / Form-Data), the filter uses a special request package that knows how to analyze this special Content Type format will package the request object. . Servlet gets this special request package and seamlessly accesses this Multipart parameter through standard GetParameter () methods, as this method has redefined these methods in this Wrapper. This ServelT can process file upload by converting REQUSET to a Wrapper type and using a getFile () method that is attached in Wrapper.
Filter code:
Package com.oreilly.servlet;
Import java.io. *;
Import javax.servlet. *;
Import javax.servlet.http. *;
Public Class MultipartFilter Implements Filter {
PRIVATE FILTERCONFIG CONFIG = NULL;
PRIVATE STRING DIR = NULL;
Public void init (filterconfig config) throws servletexception {
THIS.CONFIG = Config;
// DETERMINE THE UPLOAD DIRECTORY. First Look for An UploadDir Filter
// init parameter. The Look for the context tempdir.
Dir = config.getinitParameter ("UploadDir");
IF (dir == null) {
File Tempdir = (file) config.getServletContext ()
.getattribute ("javax.servlet.context.tempdir");
IF (Tempdir! = null) {
Dir = Tempdir.toString ();
}
Else {
Throw new servletexception
"Multipartfilter: No Upload Directory Found: Set An UploadDir"
"init parameter or ensure the javax.servlet.context.tempdir"
"Directory Is Valid";
}
}
}
Public void destroy () {
CONFIG = NULL;
}
Public Void Dofilter (ServletRequest Request, ServletResponse Response,
Filterchain chain) throws oException, servletexception {httpservletRequest Req = (httpservletRequest) Request;
String type = Req.getHeader ("Content-Type");
// if this is not a multipart / form-data request company
IF (type == null ||! type.startswith ("multipart / form-data") {
Chain.dofilter (Request, Response);
}
Else {
MultipartWrapper Multi = New MultipartWrapper (REQ, DIR);
Chain.dofilter (Multi, Response);
}
}
}
The INIT () method determines the path uploaded by the file. This is where Multipart Parser places files, so actually requested do not need to reside in memory. It first looks for the UPLOADDIR filter initialization parameter. If you are not found, use the default tempdir directory - the standard Context property in Servlet API 2.2.
DOFILTER () method Checks the requested Content Type, if it is a Multipart / Form-Data request, use MultipartWrapper packages. The Wrapper code is as follows:
Package com.oreilly.servlet;
Import java.io. *;
Import java.util. *;
Import javax.servlet. *;
Import javax.servlet.http. *;
Public Class MultipartWrapper Extends httpservletRequestWrapper {
MultipartRequest MREQ = NULL;
Public MultipartWrapper (httpservletRequest Req, String Dir)
THROWS IOEXCEPTION {
Super (REQ);
MREQ = New MultipartRequest (Req, Dir);
}
//Methods to replace HSR Methods
Public Enumeration getParameterNames () {
Return Mreq.getParameterNames ();
}
Public String getParameter (String name) {
Return MREQ.GETPARAMETER (NAME);
}
Public String [] getParameterValues (String name) {
Return Mreq.getParameterValues (Name);
}
Public map getparametermap () {
Map map = new hashmap ();
ENUMERATION ENUM = getParameters ();
While (enum.hasmoreElements ()) {
String name = (string) enum.nexTelement ();
Map.put (name, mreq.getparametervalues);
}
Return Map;
}
//Methods Only in MultipartRequest
Public Enumeration getFilenames () {
Return Mreq.getFileNames ();
Public string getFileSystemName (String name) {
Return Mreq.getFileSystemName (Name);
}
Public String getContentType (String name) {
Return Mreq.getContentType (Name);
}
Public file getfile (String name) {
Return MREQ.GETFILE (NAME);
}
}
Wrapper constructs a com.ioLly.Servlet.MultipArtRequest object to process upload analysis and overload the getParameter () method family to read the parameter values using MultipArtRequest to replace the raw request. Wrapper also defines a different getFile () method to allow a servlet to receive packn requests to process uploaded files by calling other methods.
Web.xml Deployment Description Use the following code to add this filter:
init-param>
->
filter>
filter-mapping>
Uploadtest
servlet-name>
Uploadtest
servlet-class>
servlet>
Uploadtest
servlet-name>
/ UPLOADTEST
url-pattern>
servlet-maping>
UploadText servlet is as follows:
Import java.io. *;
Import java.util. *;
Import javax.servlet. *;
Import javax.servlet.http. *;
Import com.oreilly.servlet. *;
Public class uploadtest extends httpservlet {
Public void dopost (httpservletRequest Req, httpservletResponse res)
Throws servletexception, ioException {
Res.SetContentType ("text / html");
PrintWriter out = res. maxwriter ();
Out.println ("");
Out.println ("
Out.println ("
// Parameters Can Now Be Read The Same Way for Both
// Application / X-WWW-FORM-URLENCODED AND MULTIPART / FORM-DATA Requests!
Out.println ("
");Enumeration enum = Req.getParameterNames ();
While (enum.hasmoreElements ()) {
String name = (string) enum.nexTelement ();
String Values [] = Req.getParameterValues (Name);
IF (VALUES! = null) {
For (int i = 0; i
Out.println (Name "(" i "):" VALUES [I]);
}
}
}
OUT.PRINTLN (" pre>");
// Files Can Be Read if The Request Class Is MultipartWrapper
// init params to multipartWrapper Control The Upload Handling
IF (Req InstanceOf MultipartWrapper) {
Try {
// Cast The Request to a MultipartWrapper
MultipartWrapper MULTI = (MultipartWrapper) Req;
// show which files we received
Out.println ("
Files: h3>");
OUT.PRINTLN ("
");ENUMERATION FILES = MULTI.GETFILENAMES ();
While (files.hasmorelements ()) {
String name = (string) FILES.NEXTELEMENT ();
String filename = multi.getFileSystemName (name);
String type = multi.getContentType (Name);
File f = multi.getfile (Name);
Out.println ("Name:" Name);
Out.println ("FileName:" filename);
Out.println ("TYPE:" TYPE);
IF (f! = null) {
Out.println ("Length:" f.length ());
}
Out.println ();
}
OUT.PRINTLN (" pre>");
}
Catch (Exception E) {
Out.println ("
"); E.PrintStackTrace (OUT);OUT.PRINTLN (" pre>");
}
}
Out.println (" Body> HTML>");
}
}
The first half of the servlet shows how the filter is transmitted to the received servlet without a change in the parameter data. The second half shows how a servlet is sent to MultipartWrapper to get the additional file access method.
An HTML example of driving this servlet is as follows: