JSP and syntax summary

xiaoxiao2021-03-06  20

JSP and syntax summary

JSP and syntax summary (mountains say no words) one thing not to get blocked ~! I don't understand now is that JavaScript is different from the Java programming language! JavaServer Pages (JSP) makes we can separate the static HTML and dynamic part of the page. HTML can be written in any commonly used web making tool, and the writing method is also the same as the original; the code of the dynamic part is placed in a special tag, most of the "<%" starts with "%>". For example, the following is a piece of JSP page, if we use http: //host/orderconfirmation.jsp? Title = core web programming this URL opens this page, the result shows "THANKS for Order Web Programming". Thanks for Ordering <% = Request.getParameter ("Title")%> JSP page file usually with .jsp is extension, and can be installed to any place where a normal web page can be installed. Although the JSP page is more like a normal web page, the JSP page is more like a servlet, but in fact, JSP will eventually be converted into a regular servlet, and the static HTML directly outputs the output stream associated with the Servlet Service method. The conversion process of JSP to Servlet generally is performed when the first page request appears. So if you want the first user to wait too long because the JSP page is converted to servlet, I hope that the servlet has been properly compiled and loaded, and you can request this page after installing the JSP page. Also note that many web servers allow define alias, so a URL that looks to the HTML file is actually pointing to the servlet or JSP page. In addition to ordinary HTML code, other components embedded in JSP pages mainly have the following three: scripting element, command (Directive), Action. The script elements are used to embed Java code, which will become part of the SERVLET that is converted; the JSP instruction is used to control the structure of the servlet as a whole; the action is used to introduce an existing component or control the JSP engine. To simplify scripting elements, JSP defines a set of variables (predefined variables) that can be used (predefined variables), such as REQUEST in the front code segment is one of them. Note This article is based on JSP 1.0 specification. Compared with the 0.92 version, the new version of JSP made a lot of major changes. Although these modifications will only make JSP better, it should be noted that the JSP page of 1.0 is almost not compatible with the early JSP engines. 11.2 JSP Syntax Summary Table JSP Element Syntax Description Remarks JSP Expression <% = Expression%> Calculate the expression and output the result. Equivalent XML expression is: Expression Predefined variables can be used include: Request, Response, Out, Session, Application, Config, PageContext. These predefined variables can also be used in the JSP scriptlet.

JSP Scriptlet <% Code%> Insert the code of the service method. Equivalent XML expression is: Code JSP declaration <%! Code%> code is inserted into the servlet class (outside the service method). Equivalent XML expression is: Code Page Instruction <% @ Page Att = "VAL"%> Global Directive for the Servlet Engine. Equivalent XML expression is . The legitimate properties are as follows, with bold representation defaults: import = "package.class" contentty = "mime-type" isthreadsafe = "true | false" session = "true | false" buffer = "size kb | none" autoflush = "True | false" extends = "package.class" info = "message" errorpage = "url" iesrrorpage = "true | false" language = "java" include instruction <% @ include file = "URL"%> When JSP When converting into a servlet, a specified file on the local system should be included. Equivalent XML expression is: . Where the URL must be relative URL. Using JSP: Include Actions You can introduce files when requested (instead of JSP to servlet). JSP Note <% - Comment -%> Note; JSP is neglected when JSP is converted into servlet. If you want to embed the result html document, use a normal HTML annotation tag <- comment ->. JSP: Include action When the servlet is requested, the specified file is introduced. If you want to include a file while the page is converted, use the JSP Include instruction. Note: On some servers, the included file must be an HTML file or JSP file, which is determined by the server (usually determined according to the file extension). JSP: UseBean action or ... find or instantiate a Java Bean.

Possible properties include: id = "name" scope = "Page | Request | session | Application" class = "package.class" type = "package.class" beanname = "package.class" JSP: setProperty action Sets the properties of the bean. You can set a determined value or specify the attribute value from the request parameters. The legal properties include: name = "beanname" proty = "preordyname | *" param = "parametername" value = "val" jsp: getProperty action extract and output Bean's properties. JSP: Forward action turns the request to another page. JSP: Plugin action ... Generate Object or Embed tags based on the browser type to run Java Applet through Java Plugin. 11.3 About Template Text (Static HTML) Many times, a large part of the JSP page is composed of static HTML, which is also called "template text". Template text and normal HTML are almost identical, they all follow the same syntax rules, and template text is also sent directly to the client by servlet. In addition, template text can also be written in any existing page production tool. The only exception is that if "<%" is output, "<\%" should be written in the template text. 10.1 Session Status Overview The "stateless" feature of the HTTP protocol has brought a range of questions. Especially when shopping is online, the server can not successfully remember the previous business has become a serious problem. It makes it difficult for the application of "shopping basket" to achieve: When we add goods to the shopping basket, how can the server know what is the original in the basket? Even if the server saves context information, we still encounter problems in e-commerce applications. For example, when the user goes from the page selected by the product (supplied by ordinary servers), the server can remember what the user has bought? This issue generally has three solutions: cookie. With HTTP cookies to store information about shopping sessions, the subsequent connections can view the current session and extract complete information about the session from some places of the server. This is an excellent, and the most widely used method. However, even if servlet provides a high-level, easy to use the easy cookie interface, there are still some cumbersome details that require processing: Save the session ID from other cookies. Set a suitable invalidation time for cookies (for example, a session that interrupts more than 24 hours should be resended).

Associate the session identifier and the information of the server side. (The actual saved information may be far more than the information saved to cookie, and sensitive information such as credit card should never be saved with cookies.) Rewriting the URL. You can attach the data of some identity sessions to each URL, and the server can associate the session identifier and the session data it saved. This is also a good method, and there is also the advantage when the browser does not support cookies or users have disabled cookies. However, most of the problems faced when using cookies also exist, that is, the server-side procedures should make a lot of simple but monotonous lengthy processing. In addition, you must also carefully ensure that the necessary information (including non-direct, such as a redirect URL given by Location) is guaranteed. If the user ends the session, the session information will be lost. Hidden form fields. The HTML form can contain the following input domain:

API version 2.2 is recommended getAttribute instead getvalue, not only because getAttribute and setAttribute name more closely matches (and getvalue match is putvalue, rather than setvalue), but also because setAttribute allows the use of a subsidiary of HttpSessionBindingListener to monitor the value, and putvalue Can't. However, because there is only a few commercial servlet engines support 2.2, we still use GetValue in the examples. This is a very typical example, assuming ShoppingCart is a save purchased items of information such as: HttpSession session = request.getSession (true); ShoppingCart previousItems = (ShoppingCart) session.getvalue ( "previousItems"); if (previousItems =! NULL) {DOSMETHINGWITH (PREVIOSMS);} else {previousItems = new shoppingcart (...); DOSMETHINGELSEWITH (PREVIOSELSEWITH (PREVIOSEMS); The name of all attributes. GetValueSNames returns a string array. The API 2.2 is recommended to use GetAttributeNames, which is not only because of its name, but because it returns an enumeration, and other methods (such as HTTPSERVLETREQUEST's GetHeaders and getParameternames) are consistent. Although developers are often the data saved to session objects, there are still other information. GetID: This method returns the unique identifier of the session. Sometimes the identity is used as a key-value pair, such as only one value is saved in the session, or saves the last session information. Isnew: Returns true if the customer (browser) has not bind to a session, often means that the session has just created, not a request from the client. For a session that has already existed, the return value is false. GetCreationTime: This method returns to establish a session time in millisecond meters, from 1970.01.01 (gmt). To get the time value for printout, the value can be passed to the Date constructor, or the settimeinmillis method of GregorianCalendar. GetLastAccesseedTime: This method returns to the customer's last time the request is measured in milliseconds, from 1970.01.01 (gmt). GetMaxInactiveInterval: Returns the maximum time interval in seconds, if the interval between the customer request does not exceed this value, the servlet engine will keep the session is valid. Negative numbers indicate that the session will never time out. 10.2.3 Save Data in the Session Object As described above, read the information stored in the session uses the getValue method (or, for the 2.2 version of the servlet specification, use GetAttribute). Save Data Use the PUTVALUE (or SetAttribute) method and specify the key and the corresponding value. Note PUTVALUE will replace any existing values.

Sometimes this is exactly what we need (REFERRINGPAGE in the following example), but sometimes we need to extract the original value and expand it (as PreviousItems). The following sample code: HttpSession session = request.getSession (true); session.putvalue ( "referringPage", request.getHeader ( "Referer")); ShoppingCart previousItems = (ShoppingCart) session.getvalue ( "previousItems"); if (previousItems == null) {previousItems = new ShoppingCart (...);} String itemID = request.getParameter ( "itemID"); previousItems.addEntry (Catalog.getEntry (itemID)); session.putvalue ( "previousItems", previousItems) ; 10.3 Example: Display Session Information Below this example generates a web page and displays information about the current session in this page.

package hall; import java.io. *; import javax.servlet *;. import javax.servlet.http *;. import java.net *;. import java.util *;. public class ShowSession extends HttpServlet {public void doGet ( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {HttpSession session = request.getSession (true); response.setContentType ( "text / html"); PrintWriter out = response.getWriter (); String title = "Searching the Web"; String Heading; Integer AccessCount = new integer (0) ;; if (session.isnew ()) {heading = "welcome, newcomer";} else {heading = "welcome back"; Integer OldAccessCount = // In Servlet API 2.2 getAttribute used instead getvalue (Integer) session.getvalue ( "accessCount"); if (oldAccessCount = null!) {accessCount = new Integer (oldAccessCount.intvalue () 1);}} // 2.2 Servlet API used in putAttribute Session.putValue ("AccessCount", AccessCount; out.println (servletutilities.HeadwithTitle (Title) \n " "

" Heading " \ N " "

Information on your session: \N " " \ " " \N " " \N " " \n " " \n " " \ N" "
Info Type Value \ N " "
iD \ " " " session.getid () \

N " "

" " " new date (session.getcreationTime ()) " \N " "
TIME OF LAST Access\ N" "" New Date (session.getlastaccessedTime ()) "\N" "
Number of Previous Accesses\ N " " " " \ N " " \ N " "} PUBLIC VOID DOPOST (HTTPSERVLETREQUEST REQUEST, HTTPSERVLETRESPONSE) THROWS ServletException IOEXCEPTION {Doget (Request, Response);}} cookie is a small amount of plain text information sent by the server to the browser, and the browser will send them to the server when the user accesss the same web server. By making the server Take it in the information that is originally saved to the client, the website can provide the viewer to provide a series of conveniences, such as the user identity during the online transaction process, and the security requirements are not high to avoid the user repeatedly enter the name and password, the homepage of the portal, there is Targeted advertisements, etc .. The purpose of cookie is to bring convenience to users. Although there are many mistakes, in fact, cookies will not cause serious security threats. Cookie will never use any way Execution, there will be no virus or attack your system. In addition, since the browser is generally only allowed to store 300 cookies, each site stores up to 20 cookies, each cookie size is limited to 4 KB, so cookie is not It will be filled with your hard drive, and it will not be used as a "denial service" attack means. 9.2 Servlet's cookie API To send cookies to the client, servlet first call New cookie (name, value) with the appropriate name and value Create one or more cookies (2.1), set various properties (2.2) via cookie.setxxx, add the cookie to the response head (2.3) via Response.AddCookie (Cookie). Reading from the client, servlet should call Request.getCookies (), and getCookies () methods Returns an array of cookie objects.

In most cases, you only need to use the individual elements of the array to find the cookie of the array, and then call the getValue method to get the value associated with the specified name, this part of this session will be discussed in Section 2.4. 9.2.1 Creating a cookie Call Cookie object constructor can create a cookie. The constructor of the cookie object has two string parameters: cookie name and cookie value. Names and values ​​cannot contain blank characters and the following characters: [] () =, "/? @:; 9.2.2 Read and set the cookie property Before adding the cookie to the response head to be sent, you can view or set the cookie Various properties. In summary These methods: getcomment / setcomment Get / set the cookie annotation. GetDomain / setdomain Get / set the cookie applicable domain. Generally, cookies only returns the identical server that is exactly the same as sending it. The method here can indicate that the browser returns the cookie to other servers in the same domain. Note that the domain must start with a point (for example, .sitename.com), non-national domain (such as .com, .edu, .gov) must contain two For a point, the country's domain (such as .com.cn, .edu.uk) must contain three points. GetMaxage / setMaxage Get / set the time before the cookie expires, in seconds. If this value is not set, Cookie is only It is valid within the current session, which is valid before the user closes the browser, and these cookies will not be saved to the disk. See below about longLivedCookie. GetName / SetName Get / set the name of the cookie. Essentially, the name and value are us Always care two parts. Because HTTPServletRequest's getCookies method returned to an array of cookie objects, it usually uses a loop to access this array to find a specific name, then check it with getValue. GetPath / setPath Get / setup cookies Applicable The path. If the path is not specified, the cookie will return all pages to the current page where the directory and its subdirectories. The method here can be used to set some more general conditions. For example, SomeCookie.setPath ("/"), At this point, all the pages on the server can receive the cookie. GetSecure / SetSecure Get / set a Boolean value, which represents whether cookies can only be sent by encrypted connections (ie, SSL). GetValue / setValue Gets / set the value of cookies As mentioned earlier, the names and values ​​are actually two aspects we have always cared. However, there are some exceptions, such as the name as a logical tag (that is, if the name exists, it means that getversion / setversion / Set the protocol version of the cookie compliance. Default version 0 (Compliance Netscape Specification Version 1 Compliance with RFC 2109, but has not been widely supported. 9.2.3 Setting Cookie cookies in your response head to join the set-cookie response head with the AddCookie method of HttpservletResponse.

Here is an example: cookie usercookie = New cookie ("User", "UID1234"); response.addcookie (userCookie); 9.2.4 Read Save to the client to send cookies to the client, first create a cookie, Then send a SET-Cookie HTTP response head with AddCookie. These contents have been described above in Top 2.1. The getCookies method that calls HTTPSERVLETREQUEST when reading cookies from the client. This method returns an array of cookie objects corresponding to content in the HTTP request header. After getting this array, it is generally used to access the individual elements in the loop, call GetName to check the names of each cookie until the target cookie is found. Then, the GetValue is then called to this target cookie, and other processing is performed according to the result. The above processing process often encounters, and provides a getCookieValue method for the convenience meter. Just give the cookie object array, the cookie name, and defaults, the getCookieValue method returns a cookie value that matches the specified name. If you can't find the specified cookie, return the default value. 9.3 Several Cookie Tools Functions are several tool functions. Although these functions are simple, it is useful when dealing with cookies. 9.3.1 Getting a cookie value of the specified name This function is part of ServletUtilities.java. GetCookieValue sequentially accesses the various elements of the cookie object array via a loop, finds a cookie for specifying the name, if you find it, return the value of the cookie; otherwise, return the default value given in the parameter. GetCookieValue can simplify the extraction of the cookie value to a certain extent. public static String getCookievalue (Cookie [] cookies, String cookieName, String defaultvalue) {for (int i = 0; i

When the customer has access to the same form again, these cookies will be used to pre-fill the form, so that the form automatically displays the most recently used data. Searchenginesfrontend.java This servlet constructs a user interface that is primarily made by a form. When the first display, it is similar to the interface provided by the static HTML page. However, the value selected by the user will be saved to the cookie (this page sends the data to the CustomizeDsearchengines Servlet, which is set by the latter). When the user enters the same page in the future, even if the browser is started, the content is automatically filled in the previous search. Note that servlet uses servletutilities.java, where getCookieValue has been introduced, and HeadwithTitle is used to generate a part of the HTML page. In addition, here also used the LongliveCookie class that has been described above, and we use it to create a Cookie for a long waste term.

package hall; import java.io. *; import javax.servlet *;. import javax.servlet.http *;. import java.net *;. public class SearchEnginesFrontEnd extends HttpServlet {public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {Cookie [] cookies = request.getCookies (); String searchString = ServletUtilities.getCookievalue (cookies, "searchString", "Java Programming"); String numResults = ServletUtilities.getCookievalue (cookies, "numResults", "10" ); String searchEngine = ServletUtilities.getCookievalue (cookies, "searchEngine", "google"); response.setContentType ( "text / html"); PrintWriter out = response.getWriter (); String title = "Searching the Web"; out .println (servletutilities.headwithtitle (title) \N " "

Searching the Web \N " " \ N " "
\N " "
\n " " search string: \ N " " "name" name " = \ "SearchString \" \N " " value = \ "" SearchString "\">
\ N "" Results to show per page: \N " "
\N" " \N " " Google | \N " " \N" "Infosek | \N" " \N" "lycos | \N" " \N " " Hotbot \ " "
\N " " \N" " \n" " \n" "\n" " \n" " \n");

} Private String checked (String name1, String name2) {if (name1.equals (name2)) return ( "CHECKED"); else return ( "");}} foregoing CustomizedSearchEngines.java SearchEnginesFrontEnd Servlet sends data to CustomizedSearchEngines Servlet . In this case, in many ways, the example is similar to the example of the HTTP status code, distinguishably, in addition to constructing a URL for the search engine and sends a redirect response to the user, it is necessary to send a cookies that saves user data.

package hall; import java.io. *; import javax.servlet *;. import javax.servlet.http *;. import java.net *;. public class CustomizedSearchEngines extends HttpServlet {public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {String searchString = request.getParameter ( "searchString"); Cookie searchStringCookie = new LongLivedCookie ( "searchString", searchString); response.addCookie (searchStringCookie); searchString = URLEncoder.encode (searchString); String numResults = request. getParameter ( "numResults"); Cookie numResultsCookie = new LongLivedCookie ( "numResults", numResults); response.addCookie (numResultsCookie); String searchEngine = request.getParameter ( "searchEngine"); Cookie searchEngineCookie = new LongLivedCookie ( "searchEngine", searchEngine ); response.addCookie (searchEngineCookie); searchSpec [] commonSpecs = SearchSpec.getCommonSpecs (); for (int i = 0; i

However, even when there is no special sense of state code, the specified response head is also useful. The response head can be used to complete: set cookies, specify the change date, indicating that the browser refreshes the new page according to the specified intervals, declares the length of the document to take advantage of lasting HTTP connection, ... and more many other tasks. Setting the most commonly used method of respondent is HTTPSERVLETRESPONSE's setHead, which has two parameters, indicating the name and value of the response head, respectively. Similar to setting status code, setting the response heads should be performed before sending any document content. The setDateHeader method and the setInTheadr method are specifically used to set the response to the date and integer value. The former avoids the trouble of converting Java time into a GMT time string, and the latter avoids the inclusion of integers into a string. HttpservletResponse also provides a number of simplicity methods for setting up common responses, as follows: setContentType: Sets the Content-Type header. Most servlets use this method. SetContentLength: Sets Content-Length Head. This function is useful for browsers that support persistent HTTP connections. AddCookie: Set a cookie (there is no setcookie method in the Servlet API, because response often contains multiple set-cookie headers). In addition, as described in the previous section, the SendRedirect method sets the local code 302 will also set the location header. 8.2 Common responses and its meaning about HTTP head detailed and complete descriptions, see http://www.w3.org/protocols/ specification. Respondent Description ALOW server supports which request methods (such as get, post, etc.). The encoding method of the Content-Encoding document. Only the content type specified by the Content-Type header can only be obtained after decoding. The use of GZIP compressed documents can significantly reduce the download time of the HTML document. Java's GzipOutPutStream can easily compress Gzip, but only IE 4 on the Netscape and Windows on UNIX, IE 5 supports it. Therefore, servlet should check if the browser supports Gzip by viewing an accept-encoding header ("Accept-encoding")), returning to the Gzip compressed HTML page for other browsers to return to the Gzip-compressed HTML page to support Gzip's browser. page. Content-length represents the length of the content. This data is only required when the browser uses a persistent HTTP connection. If you want to use the advantage of a lasting connection, you can write the output document to ByteArrayoutputstram. After the completion is complete, then put this value into the Content-Length header, and finally send content by ByteaRrayStream.Writto (response.getputstream (). Content. Content. Content. Content. Content -Type indicates what MIME type belongs later .Servlet defaults to text / plain, but it usually needs to be explicitly designated as Text / HTML. Since the Content-Type is often set, HttpServletResponse provides a dedicated method setContentTyep. Date current GMT time. You can use setDateHeader to set this header to avoid the trouble of conversion time format. How to think that the document has expired, no longer caches the last change time of the last-modified document.

Customers can provide a date via the if-modified-since request header, which will be considered a condition GET, and only the change time is later than the document for the specified time, otherwise returns a 304 (Not Modified) state. Last-Modified can also be set with a SetDateHeader method. Location means where the customer should go to extract the document. Location is usually not directly set, but through HttpservletResponse's SendRedirect method, this method simultaneously sets the status code 302. Refresh means that the browser should refresh the document after the browser will refresh the document in seconds. In addition to refreshing the current document, you can let the browser read the specified page by SetHeader ("Refresh", "5; URL = http: // host / path"). Note that this feature is usually achieved by setting , automatic refresh or redirection Those HTML writers that cannot use CGI or servlet are important. However, for servlet, it is more convenient to set the Refresh header. Note that refresh is "refreshing this page after n seconds or access the specified page" instead of "refreshing this page or accesses the specified page every N-second". Therefore, continuous refresh requirements send a Refresh header each time, while sending 204 status code, preventing browsers from continuing to refresh, whether using the refresh head or . Note that the Refresh head is not part of the HTTP 1.1 formal specification, but an extension, but Netscape and IE support it. Server server name. Servlet generally does not set this value, but is set by the web server yourself. Set-cookie settings and page associated cookies. Servlet should not use Response.setHeader ("SET-Cookie", ...), but should use the dedicated method provided by HTTPSERVLETRESPONSE. See the discussion on cookie settings below. WWW-AUTHENTICATE CEO should provide what type of authorization information in the Authorization header? This head is required in the response containing the 401 (Unauthorized) status line. For example, Response.setHeader ("WWW-Authenticate", "Basic Realm = \" Executives\ "). Note that servlet does not perform this process, but allows the Mechanism of the web server to control the access (for example, .htaccess) of the password protection page (for example,. 8.3 Example: Automatic refresh page below when the content change is used to calculate a large number. Because the calculation is very large (for example, 500) may take a lot of time, the servlet will immediately return the result that has been found and continues to calculate in the background. The background is calculated using a lower priority thread to avoid excessive performance of the Web server. If the calculation has not been completed, the servlet will continue to request new content after a few seconds by sending a refresh header. Note that in addition to the use of the HTTP response head, this example also shows the other two very valuable functions of the servlet.

First, it indicates that the servlet can handle multiple concurrent connections, each has its own thread. Servlet maintains a VECTOR table for existing prime calculations, and matchs all of these requests by looking at the number of number of numbers (lengths of the pop-up list) and the number of numbers (lengths of each prime) Synchronize to this list. Second, this example is proved that the status information between the request in the servlet is very easy. Maintaining status information is a very troublesome thing in traditional CGI programming. Since the status information is maintained, the browser can access the ongoing calculation process when refreshing the page, and also allows the servlet to save a list of recent request results, when a new request specifies the same parameters as the recently requested parameters Return the result immediately. Primenumbers.java Note that the servlet is used to servletUtilities.java given earlier. Also use: Primelist.java, used to create a VECTOR of a prime number in the background thread; Primes.java, used to randomly generate large numbers of the Biginteger type, check whether they are prone. (This is slightly removed from Primelist.java and Primes. Java.

) Package hall; import java.io. *; import javax.servlet *;. Import javax.servlet.http *;. Import java.util *;. Public class PrimeNumbers extends HttpServlet {private static Vector primeListVector = new Vector (); private static int maxPrimeLists = 30; public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {int numPrimes = ServletUtilities.getIntParameter (request, "numPrimes", 50); int numDigits = ServletUtilities.getIntParameter (request, "numDigits" , 120); PrimeList primeList = findPrimeList (primeListVector, numPrimes, numDigits); if (primeList == null) {primeList = new PrimeList (numPrimes, numDigits, true); synchronized (primeListVector) {if (primeListVector.size ()> = maxPrimeLists) primeListVector.removeElementAt (0); primeListVector.addElement (primeList);}} Vector currentPrimes = primeList.getPrimes (); int numCurrentPrimes = currentPrimes.size (); int numPrimesRemaining = (numPrimes - numCurrentPrimes); boolean isLastResult = ( NumprimeSremaining == 0); if (! islastresult) {response.setHeader ("refresh", "5");} response.setContentType ("text / html"); PrintWriter out = response.getwriter (); string title = " Some " Numdigits " -digit prime number "; Out.println (servletutilities.headwithtitle (title) \N" "

" Title " \N" "

primes all" number "or more digits:"

NumcurrentPrimes ". "); if (islastResult) OUT.Println (" Done search. "); else out.println (" STILL LOOKING FOR" NUMPRIMESREMAINININING " More ... ); out.println (""); for (int i = 0; i " CurrentPrimes.Elementat (i));} out.println (" "); out.println (" ");} public void dopost (httpservletRequest Request, HttpservletResponse Response Throws servletexception, ioException {doget (Request, Response);} // checks if there is a kind of request (already completed, or being calculated). // If there is, return an existing result instead of the new background thread.

private PrimeList findPrimeList (Vector primeListVector, int numPrimes, int numDigits) {synchronized (primeListVector) {for (int i = 0; i Best count Calculation </ title> </ head> <center> <body bgcolor =" # fdf5e6> <form action = "/ Servlet / Hall.PrimenumBers> <b> To calculate a few prime numbers: </ b> <input type = "text" name = "numprimes" value = 25 size = 4> <br> <b> Bit Number: </ b> <input type = "text" name = "numdigits" value = 150 size = 3> <br> <input type = "submit" value = "Start Calculation"> </ form> </ center> </ Body> </ html> Status Code Overview When a web server responds to a browser or other client request, its response is generally consisting of the following parts: a status line, several responses, one blank, content document. Here is the simplest answer: http / 1.1 200 ok content-type: text / plain Hello World status row contains a short description of the HTTP version, status code, and status code. In most cases, all responses other than Content-Type are optional. However, Content-Type is required, which describes the MIME type of the back document. Although most responses include a document, there are also some do not include, such as responding to the HEAD request never comes with a document. There are many status code actually used to identify a request for failure, which does not contain documents (or only a short error message description). Servlets can utilize status code to implement many functions.</p> <p>For example, you can redirect the user to another; you can indicate that the following document is a picture, a PDF file, or an HTML file; you can tell the user to provide a password to access documents; and so on. In this part we will specifically discuss the meaning of various status code and how to use these code. 7.2 Set status code As previously mentioned, the HTTP response status row contains HTTP versions, status code, and corresponding status information. Due to the status information is directly related to the status code, the HTTP version is determined by the server, so there is only one status code for servlet settings. Servlet Setting Status Codes Generally uses HTTPSERVLETRESPONSE's SetStatus method. The parameter of the setStatus method is an integer (ie, status code), but in order to make the code have better readability, it can be used to avoid direct use of integers in HTTPSERVLETRESPONSE. These constants are named in accordance with the standard status information in HTTP 1.1, and all the names add the SC prefix (STATUS CODE abbreviation) and uppercase, while converting spaces into underscores. That is, the status information corresponding to the status code 404 is "not found", and the corresponding constant name in HTTPSERVLETRESPONSE is SC_NOT_FOUND. However, there are two exceptions: The constant corresponding to the status code 302 is named by HTTP 1.0, and 307 has no corresponding constant. Setting status code does not always mean not return documents. For example, although most servers returns 404 responses, simply "File Not Found" information is output, but servlets can also customize this response. However, the custom response should call Response.SetStatus before sending anything via PrintWriter. Although setting status code is typically used is a response.setstauts (int) method, HTTPSERVLETRESPONSE provides a dedicated method for both common situations: SendError method generates a 404 response while generating a short HTML error message document; The SendRedirect method generates a 302 response while indicating the URL of the new document in the local header. 7.3 HTTP 1.1 Status Code and Its Meaning The following table shows the common HTTP 1.1 status code and their corresponding status information and meaning. State code supported by HTTP 1.1 should be carefully used, because many browsers can only support HTTP 1.0. If you use the HTTP 1.1 unique state code, it is best to check the requesting HTTP version number (through the GetProtocol method of HttpservletRequest). Status Code Status Information Meaning 100 Continue The initial request has been accepted, and the customer should continue to send the rest of the request. (HTTP 1.1 new) 101 Switching Protocols server will follow the customer's request to another protocol (HTTP 1.1 new) 200 ok everything is normal, the answer document requesting the GET and POST requests back. If you don't have to set status code, the servlet uses the 202 status code by default. The 201 CREATED server has created a document, and the Location header gives its URL. 202 ACCEPTED has been accepted, but the processing has not been completed. 203 Non-Authoritative Information The document has returned normally, but some responses may not be correct because the document is used (HTTP 1.1 new). 204 no content does not have a new document, the browser should continue to display the original document.</p> <p>If the user regularly refreshes the page, the servlet can determine that the user document is new enough, and this status code is useful. 205 Reset Content has no new content, but the browser should reset the content it displayed. Used to force the browser to clear the form input content (HTTP 1.1 new). 206 Partial Content The customer sent a GET request with the Range header, which completed it (HTTP 1.1 new). 300 MULTIPLE Choices Customer Requests Documents can be found at multiple locations, which have been listed within the returned document. If the server wants to make a priority, you should indicate at the Location response. 301 MOVED Permanently Customer Request Document In other places, the new URL is given in the location header, and the browser should automatically access the new URL. 302 FOUND is similar to 301, but the new URL should be considered a temporary alternative, not permanent. Note that the corresponding status information in HTTP1.0 is "Moved Temporatily", and the corresponding constant in httpservletResponse is SC_MOVED_TEMPORARILY instead of sc_found. When this status code appears, the browser automatically accesses the new URL, so it is a very useful status code. To do this, servlet provides a dedicated method, namely SendRedirect. It is better to use Response.sendredirect (URL) than using response.setstatus (response.sc_moved_temporarily) and response.setheader ("Location", URL). This is because: First, the code is more concise. Second, use SendRedirect, servlet automatically construct a page containing new links (for old browsers that cannot be redirected). Finally, SendRedirect can handle relative URLs, automatically convert them into absolute URLs. Note that this status code is sometimes used for replacement with 301. For example, if the browser is incorrectly requests http: // Host / ~ User (missing behind the late slash), some servers return 301, and some returns 302. Strictly speaking, we can only assume that the browser will automatically redirect when the original request is Get. See 307. 303 SEE Other is similar to 301/302, and the difference is that if the original request is POST, the redirect target document specified by the local header should be extracted (HTTP 1.1 new). 304 NOT MODIFIED The client has buffered documents and issues a conditional request (generally providing the IF-Modified-Since header indicating that the customer only updates the document updated than the specified date). The server tells customers that the original buffer document can also be used. 305 USE Proxy Customer Request documents should be extracted by the proxy server indicated by the Location header (HTTP 1.1 new). 307 Temporary Redirect and 302 (Found) are the same. Many browsers are incorrectly responding to the 302 response to redirect, even if the original request is POST, even if it actually only responds to the POST request is 303, it can be redirected.</p> <p>For this reason, HTTP 1.1 has increased by 307 to more clear the regional division of state code: When the 303 response occurs, the browser can follow the redirected GET and POST requests; if it is 307 response, the browser can only follow Redirection to the GET request. Note that there is no corresponding constant for the status code in HTTPSERVLETRESPONSE. (HTTP 1.1 new) 400 Bad Request requests a syntax error. 401 Unauthorized Customers attempt to access the password-protected page without authorization. A WWW-Authenticate header will contain a www-authenticate header, the browser displays the user's name / password dialog, and then issues a request after filling the appropriate Authorization header. 403 Forbidden resource is not available. The server understands the customer's request, but refuses to handle it. It is usually caused due to the permissions settings of the file or directory on the server. 404 NOT FOUND Unable to find resources for the specified location. This is also a common response, HTTPSERVLETRESPONSE provides the corresponding method: Senderror (Message). 405 Method Not ALLOWED Request Method (GET, POST, HEAD, DELETE, PUT, TRAC, etc.) do not apply to the specified resource. (HTTP 1.1 new) 406 Not Acceptable Specifies the resource specified, but its MIME type and customer are not compatible (new HTTP 1.1) specified in the ACCPET header. 407 Proxy Authentication Required Similar to 401, the customer must first authorize the proxy server. (HTTP 1.1 new) 408 Request Timeout In the waiting time of the server license, customers have not issued any requests. Customers can repeat the same request later. (HTTP 1.1 new) 409 Conflict is usually related to the PUT request. Since the request and the current state of the resource conflict, the request cannot be successful. (HTTP 1.1 new) 410 Gone requested documentation is no longer available, and the server does not know which address should be redirected. The difference between it and 404 is that the return 407 indicates that the document is permanently left the specified location, and 404 indicates that the document is not available for unknown reason. (HTTP 1.1 new) 411 Length Required server cannot handle the request unless the customer sends a Content-Length header. (HTTP 1.1 new) 412 Precondition Failed requests some prerequisites fails (HTTP 1.1 new). 413 Request Entity Too Large The size of the target document exceeds the size of the server is currently willing to handle. If the server considers yourself to process the request later, you should provide a Retry -After header (HTTP 1.1 new). 414 Request Uri Too Long Uri is too long (HTTP 1.1 new). 416 Requested Range Not Satisfiable server does not satisfy the Range header specified in the request. (HTTP 1.1 new) 500 INTERNAL Server Error server encountered unexpected situations and cannot complete customer requests. The 501 Not Implemented server does not support the functions required to implement the request. For example, the customer issued a PUT request that the server is not supported.</p> <p>502 BAD GATEWAY Server As a gateway or agent, in order to complete the request to access the next server, the server returns an illegal response. 503 Service UNAVAILALALABLE server has failed to respond due to maintenance or load. For example, servlet may return 503 in the case where the database connection pool is full. A Retry -After header can be provided when the server returns 503. 504 GATEWAY TIMEOUT is used by a server as a proxy or gateway, indicating that you cannot get a response from the remote server in time. (HTTP 1.1 new) 505 HTTP Version Not Supported Server does not support the HTTP version indicated in the request. (HTTP 1.1 new) 7.4 Instance: Accessing the plurality of search engines This example uses two other common status code except 200: 302 and 404.302 Set by SendRedirect method, 404 is set by Senderror method. In this example, the first HTML form appears to select the search engine, search the string, and the number of search results per page. After the form is submitted, the servlet extracts these three variables, and the URL containing these variables is constructed according to the requirements of the selected search engine, and then redirect the user to this URL. If the user does not correctly select the search engine, or use other forms to send an unknown search engine name, returns a 404 page that the search engine is not found. Searchengines.java Note: This servlet is to use the SearchSpec class given later, and the SearchSpec's function is to construct the URL that is suitable for different search engines. package hall; import java.io. *; import javax.servlet *;. import javax.servlet.http *;. import java.net *;. public class SearchEngines extends HttpServlet {public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// getParameter automatically decodes the URL encoded query string.</p> <p>Since we // want to send the query string to another server, use // Urlencoder to use // Urlencoder to perform URL encoded SearchString = urlencoder.Encode ("searchstring")); string NumResults = request.getParameter ("NumResults "); String searchEngine = request.getParameter (" searchEngine "); SearchSpec [] commonSpecs = SearchSpec.getCommonSpecs (); for (int i = 0; i <commonSpecs.length; i ) {SearchSpec searchSpec = commonSpecs [i]; if (searchSpec.getName () equals (searchEngine).) {String url = response.encodeURL (searchSpec.makeURL (searchString, numResults)); response.sendRedirect (url); return;}} response.sendError (response.SC_NOT_FOUND, "No recognized search engine specified.");} public void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doGet (request, response);}} SearchSpec.java package hall; class SearchSpec {private String name, baseURL, NumResultssuffix; private static searchspec [] commitpecs = {new searchspec ("google", "http://www.google.com/search?q="; "& num =") New SearchSpec ("Infoseek", "http://infosek.go.com/titles?qt="; "& nh ="), New SearchSpec ("Lycos", "http://lycospro.lycos.com/ CGI-BIN / PURSUIT? Query = ";" & MaxHits = "), New SearchSpec (" Hotbot "," http://www.hotbot.com/?mt= ";" & DC = ")}; public searchspec (String name, String baseURL, String numResultsSuffix) {this.name = name; this.baseURL = baseURL; this.numResultsSuffix = numResultsSuffix;} public String makeURL (String searchString, String numResults) {return (baseURL searchString </p> <p>numResultsSuffix numResults);} public String getName () {return (name);} public static SearchSpec [] getCommonSpecs () {return (commonSpecs);}} SearchEngines.html following is invoked Servlet above HTML form. <! DOCTYPE HTML PUBLIC "- // W3C // DTD HTML 4.0 Transitional // En"> <html> <head> <title> Access Multiple Search Engine </ Title> </ head> <body bgcolor = # fdf5e6 "> <Form action =" / servlet / hall.searchengines "> <center> Search Keywords: <input type =" text "name =" searchstring "> <br>) Several query results per page: <input type = "Text" name = "NumResults" value = 10 size = 3> <br> <input type = "radio" name = "searchine" value = "google"> Google | <input type = "radio" name = "searchengine" Value = "infoseek"> Infoseek | <input type = "radio" name = "searchengine" value = "lycos"> lycos | <input type = "radio" name = "searchengine" value = "hotbot"> Hotbot <br> <Input Type = "Submit" value = "search"> </ center> </ form> </ body> </ html> CGI variable overview If you are learning Java servlet from traditional CGI programming, perhaps it is used to it "CGI variable" concept. The CGI variable brings together various information about the request: part from the HTTP request command and request head, such as a Content-length header; part from the socket itself, such as the host's name, and IP address; also partially related to the server installation, such as URLs Mapping of the actual path. 6.2 Servlet equivalence of standard CGI variables indicates that the following table assumes that the Request object is a HTTPServletRequest type object that is provided to the Doget and dopost methods.</p> <p>CGI Variable Meaning Access from Doget or Dopost Auth_Type If the Authorization Head is provided, the specific mode is specified here (Basic or Digest). Request.GetAuthType () Content_length is only used for POST requests, indicating the number of bytes sent. Strictly speaking, equivalent expression should be string.valueof (Request.getContentLength ()) (return a string). But more common is to return the same integer with Request.getContentLength (). Content_Type If specified, it means the type of the following data. Request.getContentType () Document_Root with http: // Host / corresponding path. GetServletContext (). getRealPath ("/") Note The equivalent expression in the low version servlet specification is request.getRealPath ("/"). HTTP_XXX_YYY visits any HTTP header. Request.getHeader ("XXX-YYY") Path_info URL The additional path information in the URL, that is, after the servlet path in the URL, the part before the string is queried. Request.getPathInfo () path_translated path information after mapping the actual path of the server. Request.getPathTranslated () query_string This is a query string that is attached to the URL in the string. The data is still URL encoding. In servlets, there is a lot of unresolved data, which generally use GetParameter to access each parameter. Request.getQueryString () Remote_Addr issues the IP address of the requesting client. Request.getRemoteAddr () Remote_host issues a complete domain name for the request, such as java.sun.com. If the domain name cannot be determined, the IP address is returned. Request.getRemotehost () Remote_User If an Authorization header is provided, it represents its part of the user. It represents the name of the user who issues a request. Request.getRemoteuser () Request_Method request type. Usually GET or POST. But occasionally also appear, and the part of the SBRIPT_NAME URL will also appear in the part. Request.getMethod () Script_name URL, which does not contain additional path information and query strings. Request.getServletPath () Server_name web server name. Request.getServerName () Server_Port server listening to the port. Strictly speaking, the equivalent expression should be the string.valueof (Request.getServerPort ()) that returns a string. But often use Request.getServerPort () that returns an integer value. Server_Protocol Requests the protocol name and version of the command (ie HTTP / 1.0 or HTTP / 1.1). The name and version of the Request.GetProtocol () Server_Software Servlet engine. GetServletContext (). GetServerInfo () 6.3 Instance: Read the CGI Variable The servlet is created a table that displays all CGI variables other than HTTP_XXX_YYY. HTTP_XXX_YYY is an HTTP request header information, please refer to the previous section.</p> <p>ShowCGIVariables.java package hall; import java.io. *; import javax.servlet *;. Import javax.servlet.http *;. Import java.util *;. Public class ShowCGIVariables extends HttpServlet {public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {response.setContentType ( "text / html"); PrintWriter out = response.getWriter (); String [] [] variables = {{ "AUTH_TYPE", request.getAuthType ()}, { "CONTENT_LENGTH ", String.Valueof (Request.getContentLength ())}, {" content_type ", request.getContentType ()}, {" document_root ", getServletContext (). GetRealPath (" / ")}, {" Path_info ", request. getPathInfo ()}, { "PATH_TRANSLATED", request.getPathTranslated ()}, { "QUERY_STRING", request.getQueryString ()}, { "REMOTE_ADDR", request.getRemoteAddr ()}, { "REMOTE_HOST", request.getRemoteHost ( )}, {"Transote_user", request.getRemoteuser ()}, {"request_method", request.getMethod ()}, {"script_name", request.getServletPath ()}, {"server_name", request.getServer, Request.getServer Name ()}, {"server_port", string.valueof (Request.getServerPort ()}}, {"server_protocol", request.getProtocol ()}, {"server_software", getServletContext (). GetServerInfo ()}}; string Title = "Show CGI Variable"; Out.println (servletUtilities.HeadwithTitle (Title) <body bgcolor = \ "# fdf5e6\"> \n " " <h1 align = center> " title " </ h1 > \N " " <table border = 1 align = center> \N " " <tr bgcolor = \ "</p> <p># Ffad00 \ "> \N" "<th> cgi variable name <TH> Value"); for (int i = 0; i <variables.length; i ) {string varName = variables [i] [0]; String varValue = variables [i] [1]; if (varvalue == null) Varvalue = "<i> NOT Specified </ i>"; out.println ("<TR> <TD>" VarName <TD > " varvalue);} out.println (" </ TABLE> </ BODY> </ HTML> ");} public void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doGet (request, response); }} The HTTP request header outlines the HTTP client (such as a browser), which must specify the request type when sending a request to the server (typically Get or POST). If necessary, the client can also choose to send other request heads. Most requested heads are not required, except for Content-Length. Content-length must appear for POST requests. Here are some of the most common request heads: Accept: The browser acceptable MIME type. Accept-charset: The browser acceptable character set. Accept-encoding: Browser can decode data encoding, such as Gzip. Servlets are able to return to Gzip's browsers to returns the Gzip encoded HTML page. This can reduce download time by 5 to 10 times in many cases. Accept-language: The language type of the browser wants to use when the server provides more than one language version. Authorization: Authorized information, usually appears in a response to the WWW-Authenticate header sent to the server. Connection: Indicates if a persistent connection is required. If the servlet sees the value here "Keep-alive" or see the request is HTTP 1.1 (HTTP 1.1 default persistent connection), it can take advantage of the persistent connection, when the page contains multiple elements (for example, Applet, image), significantly reduce the time you need. To achieve this, servlet needs to send a Content-Length header in your response. The simplest implementation method is: first writing the content into ByteArrayoutputStream, and then calculate its size before formal writing. Content-length: Indicates the length of the text of the request message. Cookie: This is one of the most important request headers, see the discussion in the chapter of "Cookie Processing" later. From: Request the sender's Email address, use some special web clients, the browser will not use it.</p> <p>Host: The host and port in the initial URL. If-modified-since: Only returns it only when the requested content is modified after the specified date, otherwise returns the 304 "Not Modified" response. Pragma: Specifies the "no-cache" value indicates that the server must return a refresh document, even if it is a proxy server and already has a local copy of the page. Referr: Contains a URL that uses the user from the page represented by the URL to access the currently requested page. User-agent: Browser type, if the content returned by servlet is very useful to the browser type. UA-PIXELS, UA-Color, UA-OS, UA-CPU: Non-standard request headers sent by some versions of IE, represent screen size, color depth, operating system, and CPU type. For complete, detailed descriptions of HTTP headers, see http specifications http://www.w3.org/protocols/. 5.2 Read the request head in the servlet is very convenient to read the HTTP header in the servlet, just call the GetHeader method of HTTPSERVLETREQUEST. If the specified header information is provided in the customer request, GetHeader returns the corresponding string; otherwise, returns NULL. Some headers are often used, and they have a dedicated access method: getCookies method Returns the content of the cookie header. In the array of parsed, see the array of cookie objects, see the discussion of the cookie chapter; GetAuthType and getRemoteuser methods Part of the authorization header; getDateHeader and getInTheader methods read the specified header, then return the date value or integer value. In addition to reading the specified header, you can also get an Enumeration object in the request in the request in the request in GetHeadernAmes. Finally, in addition to viewing the request header information, we can also get some information from the request main command line. GetMethod method Returns a request method, requiring method usually get or post, but it is also possible to be Head, PUT or DELETE. GetRequesturi method Returns the URI (URI is part of the URL from the host and port to the form data). GetRequestProtocol returns the third part of the request command, usually "http / 1.0" or "http / 1.1". 5.3 Example: Output All request heads The following servlet instance outputs all received request heads and its values ​​in the form of a table. In addition, the servlet also outputs three parts of the main request command: request method, URI, protocol / version.</p> <p>ShowRequestHeaders.java package hall; import java.io. *; import javax.servlet *;. Import javax.servlet.http *;. Import java.util *;. Public class ShowRequestHeaders extends HttpServlet {public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {response.setContentType ( "text / html"); PrintWriter out = response.getWriter (); String title = "Show all request headers"; out.println (ServletUtilities.headWithTitle (title) "< Body BGColor = \ "# fdf5e6\"> \N " " <h1 align = center> " title " </ h1> \N " " <b> Request method: </ b> " Request.getMethod () "<br> \ N" "<b> Request Uri: </ b>" Request.getRequesturi () "<br> \N" "<b> Request Protocol: </ b>" request.getProtocol () "<BR> <BR> \n" "<TABLE BORDER = 1 ALIGN = CENTER> \n" "<TR BGCOLOR = \" # FFAD00\ "> \n" "< TH> Header Name <TH> Header value "); Enumeration headerNames = request.getHeaderNames (); while (headerNames.hasMoreElements ()) {String headerName = (String) headerNames.nextElement (); out.println (" <TR> <TD> Heade RNAME); OUT.Println ("<TD>" Request.getHeader (HeaderName));} Out.println ("</ Table> \ N </ Body></p> <p></ HTML> ");} public void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doGet (request, response);}} form data Overview If you have used Web search engine, or browse through online bookstores, Stock price, 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 the most common method of forming web page data to the server program. For the GET request, the form data is attached to the URL question mark (as shown in the example); for the POST request, Form data is sent to the server with a separate row. Previously, the required form variable from this form is one of the troublesome things in CGI programming. First, the data extraction method of the GET request and POST request is different: for GET requests, usually to extract data through query_string environment variables; for POST requests, generally extract data through standard input. Second, programmers must be responsible for truncating variable name-variable values ​​in the "&" symbol, then separating the variable name (Alpha left) and variable value (equal sign right). Third, the variable value must be URL anti-encoding operation. When sending data, the letters and numbers are sent in the original form, but spaces are converted into plus, Other characters are converted into "% xx" form, where XX is a restructive (or ISO Latin-1) encoded value indicated by hexadecimal. For example, if the HTML form is named "User" "~ Hall , ~ gates, and ~ mcnealy ", the data sent by the server is" UserS =% 7EHALL% 2C % 7EGATES% 2C AND % 7emcnealy ". On the end, the fourth causes the fourth caused the resolution form data is very difficult because Variable values ​​may be omitted (such as "param1 = val1 & param2 = & param3 = val3"), and it is possible that a variable has more than one value, that is, the same variable may have more time (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 automatic completion. 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.</p> <p>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. . 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.</p> <p>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) "<Body> \N" "<h1 align = center>" " " <ul> \N " " <li> param1: " Request.GetParameter (" PARAM1 ") " \N " " <li> param2: " Request.getParameter (" param2 ") " \N " " <li> param3: " Request.GetParameter (" param3 ") " \n " " </ UL> \n " " </ BODY> </ HTML> ");} public void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doGet (request, response);}} 4.3 example : Output All Form Data Looking for all variable names sent by the form and put them in the table, there is no value or a variable that has multiple values ​​highlights. 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.</p> <p>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.</p> <p>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) "<BODY BGCOLOR = \ "# Fdf5e6\"> \N " " <h1 align = center> " " <TABLE BORDER = 1 align = center> \ N " " <tr bgcolor = \ "# Ffad00 \"> \n " " <TH> Parameter Name <TH> Parameter Value "); Enumeration paramnames = request.getParameterNames (); while (paramnames.hasmorelements ()) {string paramname = (string) Paramnames.nextelement (); out.println ("<tr> <td>" paramname "\n <td>"); string [] paramvalues ​​= request.getParameterValues ​​(paramname); if (paramvalues.length == 1 ) {String paramvalue = paramvalues ​​[0]; if (paramvalue.Length () == 0) Out.print ("<i> no value </ i>); else out.print (paramvalue);} Else {OUT.PRINTLN ("<UL>"); for (int i = 0; i <paramvalues.length; i ) {Out.Println ("<li>" paramvalues ​​[i]);} out.println "</ Ul>");}} Out.println ("</ Table> \ N </ body> </ html></p> <p>");} Public void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doGet (request, response);.}} The following is the test sheet form to said Servlet PostForm.html Like all transmission data comprising a password input field Like the form, the form sends data with the POST method. We can see that the two methods of doget and dopost are convenient for form production in the servlet.</p> <p><! Doctype html public "- // w3c // DTD HTML 4.0 Transitional // en"> <html> <head> <title> 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> <input type = "radio" name = "cardtype" value = "discover"></p> <p>Discover <br> <input type = "radio" name = "cardtype" value = "java smartcard"> java smartcard <br> Credit Card Number: <input type = "password" name = "cardnum"> <br> REPEAT CREDIT Card Number: <INPUT TYPE = "PASSWORD" NAME = "cardNum"> <BR> <BR> <CENTER> <INPUT TYPE = "SUBMIT" value = "Submit Order"> </ CENTER> </ FORM> </ BODY > </ Html> Servlet Basic Structure The following code shows a basic structure of a simple servlet. The servlet is a get request, so-called GET request, if you are not familiar with http, you can see it as a user in the browser address bar, click on the link in the web page, browse when you do not specify a form of Method The request sent by the unit. The servlet can also easily handle the POST request. The POST request is to submit the requests issued when specifying a form of Method = "POST". For details, see the discussion of later sessions. import java.io. *; import javax.servlet *;. import javax.servlet.http *;. public class SomeServlet extends HttpServlet {public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// Use "request" Reading and requesting information (such as cookies) // and form data // use "response" to specify HTTP response status code and response head // (such as specifying the content type, setting cookie) printwriter out = response.getwriter (); // Use "OUT" to send the answer content to the browser}} If a class is to be a servlet, it should inherit from httpservlet, and send one or all of the DOGET, DOPOST method according to the data. DOGET and DOPOST methods have two parameters, which are HTTPSERVLETREQUEST types and httpservletResponse types, respectively. HTTPServletRequest provides methods for accessing information about the request, such as form data, HTTP request head, and more. In addition to providing methods for specifying HTTP response status (200, 404, etc.), response head (Content-type, set-cookie, etc.), is the most important thing that it provides a PrintWriter for sending data to the client .</p> <p>For simple servlets, most of its work is to generate a page sent to the client via the PrintLn statement. Note that doget and dopost throw two exceptions, so you must include them in the statement. Alternatively, you must also import java.io packages (to use PrintWriter and other classes), Javax.Servlet package (to use httpservlets) and javax.servlet.http packages (to use the HttpservletRequest class and HttpservletResponse class). Finally, the two methods of doget and dopost are called by the Service method, sometimes you may need to directly override the service method, such as the servlet to process both GET and POST requests. 3.2 Simple Servlets Output Pure Text Next is a simple servlet that outputs plain text. 3.2.1 HelloWorld.java package hall; import java.io. *; import javax.servlet *;. Import javax.servlet.http *;. Public class HelloWorld extends HttpServlet {public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException IOEXCEPTION {PrintWriter out = response.getwriter (); out.println ("Hello World");}}}} 3.2.2 Servlet compiling and installing specific details of installing servlets on different web servers, please refer to the web server documentation Understand more authoritative instructions. Assume that Java Web Server (JWS) 2.0 is used, the servlet should be installed under the servlets subdirectory of the JWS installation directory. In this article, in order to avoid servlet naming conflicts on different users on the same server, we put all servlets in a separate package Hall; if you and others share a server, and the server does not have a "virtual server" mechanism to avoid This name conflict, then it is best to use a package. After putting the servlet into the bag Hall, helloworld.java is actually placed in the Hall subdirectory of the servlets directory. Most other servers are similar, except for JWS, the servlets and JSP examples of this article have been tested in BEA WebLogic and IBM WebSphere 3.0. WebSphere has excellent virtual server mechanism, so if it is just to avoid naming conflicts, it is not necessary to use a package. For beginners who have not used bags, let's introduce two methods of the class inside the compilation package. One way is to set ClassPath to point to the last level directory (servlet home directory) that actually stores the servlet, and then compile in the directory.</p></div><div class="text-center mt-3 text-grey"> 转载请注明原文地址:https://www.9cbs.com/read-39454.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="39454" 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.062</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 = 'V3magAAFZ_2Fk7cOPOWemT_2FrIUDocV8w2J175axEsh19WL7EsyZGjDdQ2l_2FFBygLrNtOx_2FlBRcGScyvqL4N8ESRg_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>