Fourth, deal with form data

zhaozj2021-02-16  146

4.1 Form Data Overview If you have used the web search engine, or browse online bookstores, stock prices, ticket information, may pay attention to some weird URLs, such as "http: // host / path? User = marty Hall & Origin = BWI & DEST = LAX. This URL is located behind the question mark, ie "User = Marty Hall & Origin = BWI & DEST = LAX" is form data, which is the most common method of sending web page data to the server program. For the GET request, the form data is attached to the question mark of the URL (as shown in the above example); for the POST request, form data is sent to the server with a separate row. Previously, from this form of data extraction, the required form variables were one of the troublesome things in CGI programming. First, the data extraction method of the GET request and the POST request is different: for the GET request, it is usually extracted by the Query_String environment variable; for the POST request, the data is generally extracted by standard input. Second, the programmer must be responsible for truncating the variable name-variable pair at the "&" symbol, then separating the variable name (left side) and variable value (equal sign right). Third, the variable value must be performed on the URL anti-encoding operation. Because the letters and numbers are sent in the original form, the spaces are converted into a plus sign, and the other characters are converted into "% xx" form, where XX is the character ASCII represented by hexadecimal (or ISO Latin " 1) Code value. For example, if the domain value named "USERS" in the HTML form is "~ Hall, ~ Gates, and ~ McNEAL", the data sent to the server is "UserS =% 7EHALL% 2C % 7EGATES% 2C AND % 7emcnealy) ". Finally, the fourth causes the fourth result of the analysis of the parsing form data is that the variable value may be omitted (such as "param1 = var_ param2 = & param3 = val3"), and it is possible that a variable has more than one value, that is, the same variable Among the above (such as "param1 = val1 & param2 = VAL2 & param1 = val3). One of the benefits of Java Servlet is that all of the above parsed operations can be done automatically. Just simply call the getParameter method of HTTPSERVLETREQUEST, providing the name of the form variable in the call parameter (case sensitive), and the GET request and the POST request are identical. The return value of the getParameter method is a string, which is the corresponding value specified in the parameter, the corresponding value is obtained by the countercodes (can be used directly). If the specified form variable exists, but no value, getParameter returns an empty string; returns NULL if the specified form variable does not exist. If the form variable may correspond to multiple values, you can use GetParameterValues ​​to replace GetParameter. GetParameterValues ​​can return a string array.

Finally, although the servlet is likely to use the form variables of those known words in practical applications, it is often very useful in debugging environments, which can be easily implemented using the GetParameRnames method. . getParameRNames returns an enumeration, each of which can be converted to a string that calls getParameter. 4.2 Instance: Reading three tables Unit is a simple example, which reads three tables monologous param1, param2, and param3, and lists their values ​​in the form of an HTML list. Note that although the response type (including the content type, status, and other HTTP header information) must be specified before sending the answer content, but the servlet does not require any requirements. In addition, we can easily make the servlet to process the GET request, and can handle the POST request, which only needs to call the Doget method in the dopost method, or override the service method (Service method call doget, dopost, dohead, etc. ). This is a standard method in actual programming because it only needs little additional work, but it can increase the flexibility of client encoding. If you are used to using traditional CGI methods, read POST data through standard input, then there are similar methods in the servlet, namely GetReader or GetInputStream upon httpservletRequest, but this method is too troublesome for ordinary form variables. However, if you want to upload files, or POST data is sent through a dedicated client instead of an HTML form, then this method is used. Note When you read the POST data in a second method, you cannot read these data again with GetParameter.

ThreeParams.java package hall; import java.io *;. Import javax.servlet *;. Import javax.servlet.http *;. Import java.util *;. Public class ThreeParams extends HttpServlet {public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {response.setContentType ( "text / html"); PrintWriter out = response.getWriter (); String title = "request read three parameters"; out.println (ServletUtilities.headWithTitle (title) " \N" "

" " "
    \N " "
  • param1: " Request.GetParameter (" PARAM1 ") " \N " "
  • param2: " Request.getParameter (" param2 ") " \N " "
  • param3: " Request.GetParameter (" param3 ") " \n " " \n " " ");} public void dopost (httpservletRequest Request, HttpservletResponse Re Sponse) THROWS servleTexception, IOException {doget (request, response);}} 4.3 instance: Output All Form Data Looking for all variable names sent by the form, put them in the table, no value or multiple Variable variables are highlighted. First, the program gets all the variable names through the GetParameterNames method of HTTPSERVLETREQUEST, and getParameterNames returns an enumeration.

    Next, the program uses a loop to traverse this Enumeration, determine when to end the loop via HasMELEMENTS, use the nextElement to get the enumerations in the enumeration. Since NexTelement returns an Object, the program converts it into a string and uses this string to call GetParameterValues. getParameterValues ​​returns a string array if this array has only one element and is equal to the empty string, indicating that this form variable does not value, and servlet outputs "no value" in a slope body; if the number of elements is greater than 1, how many of this form is more Values, servlets output these values ​​in the form of an HTML list; the servlet puts the variable value into the form in other cases. ShowParameters.java Note that ShowParameters.java uses servletutilities.java described earlier.

    package hall; import java.io *;. import javax.servlet *;. import javax.servlet.http *;. import java.util *;. public class ShowParameters extends HttpServlet {public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {response.setContentType ( "text / html"); PrintWriter out = response.getWriter (); String title = "read all request parameters"; out.println (ServletUtilities.headWithTitle (title) " \N " "

    " " \ N " " \n " "
    Parameter Name Parameter Value "); Enumeration paramnames = request.getParameterNames (); while (paramnames.hasmorelements ()) {string paramname = (string) Paramnames.nextelement (); out.println ("
    " paramname "\N "); string [] paramvalues ​​= request.getParameterValues ​​(paramname); if (Paramvalues.length == 1) {String paramvalue = paramvalues ​​[0]; if (paramvalue.length () == 0) Out.print (" no value ); else out.print (paramvalue);} Else {OUT.PRINTLN ("
      "); for (int i = 0; i

      ) {OUT.PRINTLN ("

    • " paramvalues);} out.println ("");}}}} out.println (" \ N " } PUBLIC VOID DOPOST (HTTPSERVLETREQUEST, HTTPSERVLETRESE RESPONSE) THROWS ServletException, IOException {dogt (request, response);}} The following is a form Postform.html to send data to the servlet described above. Just like all forms containing password input domains, the table sends data with the POST method. We can see that the two methods of doget and dopost have brought convenience to form production in the servlet.

      example form </ title> </ head> <body bgcolor = "# fdf5e6> < H1 align = "center"> Forms </ h1> <form action = "/ servlet / hall.showparameters" method "method =" post "> item name: <input type =" name = "item Num "> <br> Quantity: <input type =" text "name =" quantity "> <br> Price Each: <input type =" text "name =" price "value =" $ "> <br> <HR> First Name: <input type = "text" name = "firstname"> <br> Last Name: <input type = "text" name = "lastname"> <br> middle initial: <input type = "text" name = "Initial"> <br> Shipping address: <textarea name = "address" rows = 3 cols = 40> </ textarea> <br> Credit Card: <br> <input type = "radio" name = "cardtype" VALUE = "VISA"> VISA <br> <input type = "radio" name = "cardtype" value = "master card"> master card <br> <input type = "radio" name = "cardtype" value = "amex" > American Express <BR> <</p></div><div class="text-center mt-3 text-grey"> 转载请注明原文地址:https://www.9cbs.com/read-9014.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="9014" 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.055</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 = 'UT5B0CwSEFA4rq7LqmoNRc_2F_2FzpIUGlJMWoUf_2BiQuZqEGF95bnrvOopR56hDOno83Fs_2BLAxThMvzblSMsOEuFfQ_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>