Servlet 2.3 Filter Programming (2)

zhaozj2021-02-11  161

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:

MultipartFilter

com.oreilly.servlet.multipartfilter

UPLOADDIR

/ TMP

->

MultipartFilter

/ *

Uploadtest

Uploadtest

Uploadtest

/ UPLOADTEST

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 (" UploadTest </ Title> </ head>"); out.println ("<body>");</p> <p>Out.println ("<H1> UploadTest </ H1>);</p> <p>// Parameters Can Now Be Read The Same Way for Both</p> <p>// Application / X-WWW-FORM-URLENCODED AND MULTIPART / FORM-DATA Requests!</p> <p>Out.println ("<H3> Request Parameters: </ h3> <pre>");</p> <p>Enumeration enum = Req.getParameterNames ();</p> <p>While (enum.hasmoreElements ()) {</p> <p>String name = (string) enum.nexTelement ();</p> <p>String Values ​​[] = Req.getParameterValues ​​(Name);</p> <p>IF (VALUES! = null) {</p> <p>For (int i = 0; i <value content.length; i ) {</p> <p>Out.println (Name "(" i "):" VALUES [I]);</p> <p>}</p> <p>}</p> <p>}</p> <p>OUT.PRINTLN ("</ pre>");</p> <p>// Files Can Be Read if The Request Class Is MultipartWrapper</p> <p>// init params to multipartWrapper Control The Upload Handling</p> <p>IF (Req InstanceOf MultipartWrapper) {</p> <p>Try {</p> <p>// Cast The Request to a MultipartWrapper</p> <p>MultipartWrapper MULTI = (MultipartWrapper) Req;</p> <p>// show which files we received</p> <p>Out.println ("<H3> Files: </ h3>");</p> <p>OUT.PRINTLN ("<pre>");</p> <p>ENUMERATION FILES = MULTI.GETFILENAMES ();</p> <p>While (files.hasmorelements ()) {</p> <p>String name = (string) FILES.NEXTELEMENT ();</p> <p>String filename = multi.getFileSystemName (name);</p> <p>String type = multi.getContentType (Name);</p> <p>File f = multi.getfile (Name);</p> <p>Out.println ("Name:" Name);</p> <p>Out.println ("FileName:" filename);</p> <p>Out.println ("TYPE:" TYPE);</p> <p>IF (f! = null) {</p> <p>Out.println ("Length:" f.length ());</p> <p>}</p> <p>Out.println ();</p> <p>}</p> <p>OUT.PRINTLN ("</ pre>");</p> <p>}</p> <p>Catch (Exception E) {</p> <p>Out.println ("<pre>"); E.PrintStackTrace (OUT);</p> <p>OUT.PRINTLN ("</ pre>");</p> <p>}</p> <p>}</p> <p>Out.println ("</ Body> </ HTML>");</p> <p>}</p> <p>}</p> <p>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.</p> <p>An HTML example of driving this servlet is as follows:</p> <p><Form action = "UPLOADTEST" ENCTYPE = "Multipart / Form-Data" Method = Post></p> <p>What is your name? <Input type = text name = subster> <br></p> <p>What is your agent? <Input type = text name = ag> <br></p> <p>Which file do you want to upgrad? <Input type = file name = file1> <br></p> <p>Any Other File to Upload? <Input type = file name = file2> <br></p> <p><Input Type = SUBMIT></p> <p></ Form></p> <p>This is a possible output:</p> <p>Uploadtest</p> <p>Request Parameters:</p> <p>Submitter (0): Jason</p> <p>Age (0): 28</p> <p>FILES:</p> <p>Name: file1</p> <p>FILENAME: 4008B21.TIF</p> <p>TYPE: Application / OcTet-Stream</p> <p>Length: 39396</p> <p>Name: file2</p> <p>FileName: Null</p> <p>TYPE: NULL</p> <p>You may be confused how we are confident that MultipartWrapper, which is set by the filter, can be transmitted correctly to the next servlet. It is uncertain in the No. 2 issued draft specification and Tomcat 4.0 Beta 5. In fact, if you try to access this servlet with / servlet / uploadtest, you will notice that filtering does not work correctly, because / servlet calls MultipartWrapper to Tomcat's special Wrapper. This allows parameters to be correctly parsed, but the file access method cannot work correctly. In the discussion of the Servlet API expert group, we decided that the servlet container does not make more packages for the filter's Wrapper. This servlet specification will be modified more clearly. These rules will be clarified in later releases in Tomcat 4.0. Short-term approach is to use the getRequest () method in requesting Wrapper to find this hidden multipart Wrapper.</p> <p>Download the WAR file from the following address:</p> <p>http://www.javaworld.com/jw-06-2001/filters/mulitpart.war</p> <p>Filter capability</p> <p>The servlet filter provides a powerful ability to control the occurrence of the request and the occurrence of the response, providing new servlet features without having much code. I hope to show you the possible situation of using the filter, and taught you some skills on how to use new filter functions more effectively.</p> <p>Thanks to these filters, the author and other people who provide useful recommendations for filters: Amy Roh, Criag McClanahan, Serge KNystautas, and Opensymphony members.</p> <p>About author</p> <p>See the original text</p> <p>Resource</p> <p>See the original text</p></div><div class="text-center mt-3 text-grey"> 转载请注明原文地址:https://www.9cbs.com/read-5571.html</div><div class="plugin d-flex justify-content-center mt-3"></div><hr><div class="row"><div class="col-lg-12 text-muted mt-2"><i class="icon-tags mr-2"></i><span class="badge border border-secondary mr-2"><h2 class="h6 mb-0 small"><a class="text-secondary" href="tag-2.html">9cbs</a></h2></span></div></div></div></div><div class="card card-postlist border-white shadow"><div class="card-body"><div class="card-title"><div class="d-flex justify-content-between"><div><b>New Post</b>(<span class="posts">0</span>) </div><div></div></div></div><ul class="postlist list-unstyled"> </ul></div></div><div class="d-none threadlist"><input type="checkbox" name="modtid" value="5571" checked /></div></div></div></div></div><footer class="text-muted small bg-dark py-4 mt-3" id="footer"><div class="container"><div class="row"><div class="col">CopyRight © 2020 All Rights Reserved </div><div class="col text-right">Processed: <b>0.042</b>, SQL: <b>9</b></div></div></div></footer><script src="./lang/en-us/lang.js?2.2.0"></script><script src="view/js/jquery.min.js?2.2.0"></script><script src="view/js/popper.min.js?2.2.0"></script><script src="view/js/bootstrap.min.js?2.2.0"></script><script src="view/js/xiuno.js?2.2.0"></script><script src="view/js/bootstrap-plugin.js?2.2.0"></script><script src="view/js/async.min.js?2.2.0"></script><script src="view/js/form.js?2.2.0"></script><script> var debug = DEBUG = 0; var url_rewrite_on = 1; var url_path = './'; var forumarr = {"1":"Tech"}; var fid = 1; var uid = 0; var gid = 0; xn.options.water_image_url = 'view/img/water-small.png'; </script><script src="view/js/wellcms.js?2.2.0"></script><a class="scroll-to-top rounded" href="javascript:void(0);"><i class="icon-angle-up"></i></a><a class="scroll-to-bottom rounded" href="javascript:void(0);" style="display: inline;"><i class="icon-angle-down"></i></a></body></html><script> var forum_url = 'list-1.html'; var safe_token = 'v0nzzsqVaRuMD5Xa4agEMyIgw4fdtQEpZ6Fo6Zn_2B4g0XcY9p8lwPRXJfVDuWdefJ5tl73BccOv2XulL9YGpMkg_3D_3D'; var body = $('body'); body.on('submit', '#form', function() { var jthis = $(this); var jsubmit = jthis.find('#submit'); jthis.reset(); jsubmit.button('loading'); var postdata = jthis.serializeObject(); $.xpost(jthis.attr('action'), postdata, function(code, message) { if(code == 0) { location.reload(); } else { $.alert(message); jsubmit.button('reset'); } }); return false; }); function resize_image() { var jmessagelist = $('div.message'); var first_width = jmessagelist.width(); jmessagelist.each(function() { var jdiv = $(this); var maxwidth = jdiv.attr('isfirst') ? first_width : jdiv.width(); var jmessage_width = Math.min(jdiv.width(), maxwidth); jdiv.find('img, embed, iframe, video').each(function() { var jimg = $(this); var img_width = this.org_width; var img_height = this.org_height; if(!img_width) { var img_width = jimg.attr('width'); var img_height = jimg.attr('height'); this.org_width = img_width; this.org_height = img_height; } if(img_width > jmessage_width) { if(this.tagName == 'IMG') { jimg.width(jmessage_width); jimg.css('height', 'auto'); jimg.css('cursor', 'pointer'); jimg.on('click', function() { }); } else { jimg.width(jmessage_width); var height = (img_height / img_width) * jimg.width(); jimg.height(height); } } }); }); } function resize_table() { $('div.message').each(function() { var jdiv = $(this); jdiv.find('table').addClass('table').wrap('<div class="table-responsive"></div>'); }); } $(function() { resize_image(); resize_table(); $(window).on('resize', resize_image); }); var jmessage = $('#message'); jmessage.on('focus', function() {if(jmessage.t) { clearTimeout(jmessage.t); jmessage.t = null; } jmessage.css('height', '6rem'); }); jmessage.on('blur', function() {jmessage.t = setTimeout(function() { jmessage.css('height', '2.5rem');}, 1000); }); $('#nav li[data-active="fid-1"]').addClass('active'); </script>