Posting Via Java Revisited

xiaoxiao2021-03-06  83

Summary

In

JavaWorld's August issue, we ran a Java Tip on "POSTing from applets." Not only was the tip popular with readers, but it spawned a number of questions. This new tip on POSTing via Java attempts to satisfy your curiosity. We show you how TO Send Post Requests to Web Servers and Display The Response In an applet.

(2,000 Words)

BY

John D. Mitchell

hew! Our previous tip on POSTing from applets generated a slew of reader questions. The predominant question was "How do I display the HTML document returned by the POST CGI-bin handler on the Web server?". In this tip, we explore the Answers to That Question and Delve Into Some Cool Server-Side Java Issues.

Note: this Tip Assumes An Undering On The Part of The Reader of The Basic Problems and Issues of Posting Via Java. If You're Not Familiar with these Concepts, Refer to Java Tip 34.

SO, Just How Do We Display THE RESUS OF A Post from an applet? Well, There Are Four Answers To That Question. In Order of Increasing Pain, Thase Are:

We can't. Don n't post...............

As discussed in Java Tip 34, the current browser security managers will not allow an applet to display applet-generated HTML in a browser; the browser only lets us point it toward URLs that it will display on our behalf This situation is just so unsatisfying. !

We can side-step the POST results display restriction by - surprise -! Not using POST Instead, we can encode some information in the URL that we provide to the showDocument () method That information will get passed on to the the.. Web server as parameters to the GET request Unfortunately, this does have some drawbacks:. Only limited amounts of data can be transferred - plus, the URL is munged in the process So it's pretty ugly We'll see an example of how.. to code this a bit later.Just recently, Sun's JavaSoft division released an HTML renderer bean. (There are a couple of other commercial offerings.) So, it's possible to use the bean as part of your applet and have it display the pages. What are the drawbacks? Size, compatibility, and cost. The bean certainly is not small, it requires a browser supporting beans, and it is not free. Of course, we could all spend time writing our own rendering component, but that's Silly.

The fun and productive solution to the problem is to cheat In this particular case, we cheat by requiring the collusion of the server-side code (for example, the CGI-bin script) with our applet The basic idea is simple:.. Combine The use of post with a subsequent get. The process is as follows:

The applet POSTs information to the server just as before. The server uses the POST information to generate HTML. The server saves the HTML to a file on the Web server. The server returns a magical key to the applet. The applet encodes the key into a URL back to the server. The applet instructs the browser to display a Web page by using the generated URL in a showDocument () call. The server accepts the GET request and extracts the magic key parameter. The server retrieves the file associated with the magic key. The server returns the HTML contents from the file to the browser. The browser displays the HTML contents.This back-and-forth process is definitely more complicated than the other solutions, but it works today across a wide combination of clients and servers. The drawbacks to this process stem from needing to perform multiple HTTP requests to fulfill a single, complete transaction. We must retain "state" information across the multiple requests to be able to keep track of what's going on (recall that HTTP is a stateless request / response protocol) Robustly managing the requisite state information can be quite challenging As John Ousterhout, the father of the Tcl scripting language and the Sprite distributed operating system, has said:.. "State is The Second Worst Thing in Distributed Computing. No, State Is The Worst.

The server part is the most complicated piece, so let's look at the applet first. There are only a few differences between this applet and the Happy applet in the previous Java Tip 34. POSTing to the server is identical, but we have to modify the Reading of the response from the server:

input = new DataInputStream (urlConn.getInputStream ()); String str = null; String firstLine = null; (! null = ((str = input.readLine ()))) while {if (null == firstLine) firstLine = str System.out.Println (STR); TextArea.AppendText (Str "/ N");} Input.close (); by Fiat, The Server Returns A Magic Key As The First Line. The Magic Key Is The Piece of state information that is used to uniquely identify which transaction the applet is involved in with this server. If there are any problems in processing the POST request, the server notifies the applet that this is the case by returning the string "nil" followed by a TEXTUAL DESCRIPTION OF THE PROBLEM. The Only Thing The applet Needs to do now is build the url and call showdocument () to display the html:

IF (NULL! = firstline) {url = new url ("http: //" ). gethost ()). TOSTRING () "/ poster?" firstline); (getAppletContext ()) .Showdocument (URL, "_blank");}

Be sure to note that the URL parameter must be URL-encoded. In that snippet, we only have to add the question mark to separate the base URL from the passed parameters, since the magic key from the server is already safely encoded.

Now that we have the applet part taken care of, let's dive into the server. The server-side code in the earlier Java Tip on POSTing was a traditional CGI-bin script written in Perl. Perl is a fine solution, but would not you rather write server-side Java We can write CGI-bin scripts in Java (see the Resources section), but there's a much better solution:?. Java that is run as part of the Web server itself This type of server-side Java is known as a servlet The solution we're presenting here will be a servlet written to the Java Servlet API -. although you can implement the same solution using CGI-bin scripts in Perl, Tcl, Java, or whatever.Note that an Introduction to servlet programing and administration is beyond the scope of this article; we'l be covering Only to the posting solution.

The PosterServlet code contains a fair number of comments to guide your walk-through. There's lots of error handling and extra checking to handle the plethora of possible problems, some denial-of-service attacks, and so on, but mostly you can ignore that Stuff. (We'll Discuss Security Issues in More Depth Later) The servlet is written to the java 1.1.x Apis (Whereas the applet code is java 1.0.2 code).

The doPost () method handles the POST request - that is, it takes care of the first three server responsibilities: It generates an HTML document based on the POSTed information, saves the document to a temporary disk file, and returns a magic key to The applet what identifier the html document and is suitable for directly Embedding Into a subsequent get request.

. Here's the core of the code (. See the actual source file for the complete code) Implementation note: The magic key actually is the name of the file that generated the HTML document for that transaction The name is generated using the java.util. .Random class to generate a long value.

protected void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {response.setContentType ( "text / plain"); // Build the output filename.String fileName = (new Long (randomizer.nextLong ())) toString (. ); File file = null; try {file = new File (posterTempDir File.separator fileName posterTempExt);} catch (Exception e) {sendPostFailure (response, "Unable to build output file path!"); return;} // Open the output file.PrintWriter output = null; try {output = new PrintWriter (new BufferedWriter (new FileWriter (file)));} catch (IOException e) {sendPostFailure (response, "Unable to open output file!") }} Output.println (""); Output.print (" poster servlet generated output"); OUTPUT.PRINTLN ("</ Title> </ head>"); Output .println ("<body>"); // now, loop through the request headers and spew the the file.string headername = null; enumeration headers = request.getHeader Names (); if (Headers.haASMoreElements ()) {Output.println ("<H1> CGI Headers: </ h1> <hr>"); Output.Println ("<UL>"); while (Headers.hasMoreElements ()) {Headername = (String) Headers.NexTelement (); Output.Print ("<li> <b>"); Output.print (Headername); Output.print ("="); Output.print (Request .getHeader (Headername); Output.println ("</ b> </ li> <br>);} Output.println (" </ ul> <hr> <br> ");} // DEAL with The post contents.if (0 <request.getContentLength ()) {string line =</p> <p>null; // Translate all of those incoming bytes to characters BufferedReader in = new BufferedReader (new InputStreamReader (request.getInputStream ())); output.println ( "<h1> POST contents: <h1> <hr>").; Output.println ("<p> <pre>"); // read each line of infut and spew it to the output file. httputils httputils = new httputils (); try {whele (null! = (line = in.readline ()) {Try {HashTable Data = httputils.ParseQueryString (LINE); String Keyname = NULL; Enumeration Keys = DATA.KEYS (); while (keys.hasmoreElements ()) {string [] value = null; keyName = Keys.NexTelement (); output.print (keyName); values ​​= (String []) Data.get (keyName); output.print ("="); if (1 <values.length) Output.println ""); For (int i = 0; i <value.length; i ) {output.print ("/T");output.println (Values ​​[i]);}} output.println ();} catch (ILLEGALARGUMENTEXCEE) {Output.Print (line);}}} catch (ooException e) {OUTPUT.PRINTLN ("/ N </ pre> <br> <P> <B>"); OUTP Ut.println ("Unable to read entire pos"); Output.println ("</ b> </ p> <br> <pre> / n");} Output.println ("</ pre> < / p> <hr> ");} // tidy up the output file.output.println (" </ body> </ html> "); output.flush (); Output.close (); // build the POST response.ServletOutputStream out = response.getOutputStream (); out.println (fileName); out.println ( "That is the magic value to return as a URL" "parameter in a showDocument () call to / n" "</p> <p>get the data generated by this POST call ");...} // End of doPost () The doGet () processes the GET request It takes care of extracting the magic key from the GET query, loading the HTML document from the associated Disk file, and returning the HTML Document:</p> <p>protected void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {response.setContentType ( "text / html"); // Get the identifier the doPost () method gave the caller, if any.String fileName = request.getQueryString ( ); // Build the input filename.File file = null; try {file = new File (posterTempDir File.separator fileName posterTempExt);} catch (Exception e) {sendGetFailure (response, "Unable to get data file. please start over! "); return;} // Open the file.BufferedReader input = null; try {input = new BufferedReader (new FileReader (file));} catch (FileNotFoundException e) {sendGetFailure (response," Unable to find Data file. Please start over! "); return;} // read in the data file and spew it out = response.getoutputstream (); string line = null; try {whell (null! = (line = input) .readline ())) {out.println (line);}} catch (ooException e) {OUT.P RINTLN ("/ N <BR> <P> <B>"); Out.Println ("Unable to read Entire Data File Contents!"); Out.Println ("</ b> </ p> <br> / N ");} // close and delete the input file.input.close (); try.de (! file.delete ()) {// log the error for the sysadmin to deal with.}} catch (SecurityException E ) {}} // end of doget ().</p> <p>The last bit of code worth mentioning is the init () method. It initializes some global data and deletes any temporary files that have not yet been claimed by using the clearTempDir () method. Check out the source files for the definitions of those two methods (there's nothing interesting enough about them to show them here :-). Note that a more robust and secure solution would be to limit the time that a temporary file can live, and put a limit on the total number of files that can be alive at any given time. Adding some logic to deal with other resource saturation issues also would be prudent.Speaking of security and robustness, the predominantly paranoid may want something a bit more, um, paranoid. Using SSL or some other cryptographic solution definitely would increase Overall security.</p> <p>Well, There you have it. We've colluded with the server to make it..................</p> <p>Printer-Friendly Version | Mail this to a friend</p> <p>About the authorAlternately as employee, consultant, and principal of his own company, John has invested the last ten years in developing cutting-edge computer software and advising other developers John co-authored Making Sense of Java:. A Guide for Managers and the Rest of Us and Dummies 101:. Java Programming and has published articles in programming journals in addition to writing the Java Tips & Tricks column for JavaWorld, he moderates the comp.lang.tcl.announce and comp.binaries.geos newsgroups.</p> <p>Resources</p></div><div class="text-center mt-3 text-grey"> 转载请注明原文地址:https://www.9cbs.com/read-107027.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="107027" 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.034</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 = '67zAmd3sjU79jNBMEubeRaou3BH7REro5BTcClmJW_2BPsMTUFVo6g8GBvC1bMu0stYyV3_2F5M0xZ4sNZ1_2BgUcWUw_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>