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")%> i> 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:
JSP Scriptlet <% Code%> Insert the code of the service method. Equivalent XML expression is:
Possible properties include: id = "name" scope = "Page | Request | session | Application" class = "package.class" type = "package.class" beanname = "package.class" JSP: setProperty action
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 " "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 " " | " " Table> \ N " " Table> \ 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) } 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) NumcurrentPrimes ". h3>"); if (islastResult) OUT.Println (" Done search. b>"); else out.println (" STILL LOOKING FOR" NUMPRIMESREMAINININING " More private PrimeList findPrimeList (Vector primeListVector, int numPrimes, int numDigits) {synchronized (primeListVector) {for (int i = 0; i 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. 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. 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. 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. 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 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. 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) \n " "" title " h1 > \N " "
|