JSP and syntax summary (mountains say no words)

xiaoxiao2021-03-06  55

JSP and syntax summary (mountains say no words)

Don't get among it ~! 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:

10.2 Session Status Tracking API Using Session Information in Servlet is quite simple, the main operations include: viewing the session objects associated with the current request, create a new session object when necessary, view information related to a session, in the session Save information in the object, and release the session object when the session is completed or aborted. 10.2.1 Viewing the currently requested session object View the currently requested session object is implemented by calling the GetSession method of httpservletRequest. If the getSession method returns null, you can create a new session object. More often, we automatically create a session object when there are no ready-made sessions, namely TRUE when there is no ready-made session. Therefore, the first step of accessing the current request session object is usually as follows: httpsession session = request.getSession (TRUE); 10.2.2 Viewing the information about the HTTPSession object HttpSession objects There is a servers, through the cookie or URL background The mechanism is automatically associated with the requesting sender. The session object provides a built-in data structure where any number of keys-value pairs can be saved in this structure. In the 2.1 or earlier version of the Servlet API, check the previously saved data is the GetValue ("Key") method. getValue Returns Object, so you have to convert it into a more specific data type. If the keys specified in the parameter do not exist, getValue returns NULL. 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"; Out.println (servletUtilities. Headwithtitle (Title) \n " "

heading " \N" "

information On your session: \ N " " \N " " \N" " \n "

"

\ N" " \N" " \n" "
Info Type Value \ N " "
iD\N" "" session.getid () "\N" "
CREATION TIME \ N" "" New date (session.getcreationTime ()) "\N" "
TIME OF Last Access\ N" "" New Date (session.getlastaccessedTime ()) "\N" "
Number of Previous Accesses\ N" "" AccessCount "\N" " \N" "< / BODY> ");} public void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doGet (request, response);}} Cookie server is sent to the browser of a small volume of plain text information When the user visits the same web server, the browser will send them to the server. By letting the server reads the information you originally saved to the client, the website can provide the viewer to provide a series of convenience, such as the user identity in the online transaction process, and the security requirements are not high to avoid user repeated input name and password, portal The home page is customized, targetedly putting advertisements, and so on. The purpose of cookie is to bring convenience to users, bring value to the website. Although there are many mistakes, in fact, cookies will not cause serious security threats. Cookie will never be executed in any way, so 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 the cookie will not be full of your hard drive, and it will not be used as "refusal." Service "attack means.

9.2 SERVET Cookie API To send cookies to the client, servlet first creates one or more cookies (2.1) with the appropriate name and value, set various properties with cookie.setxxx ( Section 2.2), add the cookie to the response head (Section 2.3) via response.addcookie (cookie). To read from the client, servlet should call the request.getCookies (), and the getCookies () method 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 also some exceptions, such as using the name as a logical tag (that is, if the name exists, it means true. GetVersion / SetVersion Gets / Sets the protocol version of the cookies. The default version 0 (complies with the original Netscape specification); version 1 follows 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

package hall; import javax.servlet.http *;. public class LongLivedCookie extends Cookie {public static final int SECONDS_PER_YEAR = 60 * 60 * 24 * 365; public LongLivedCookie (String name, String value) {super (name, value); setMaxAge (Seconds_per_Year);}} 9.4. Instance: The custom search engine interface is also an example of a search engine interface, by modifying an example of the front HTTP status code. In this servlet, the user interface is dynamically generated instead of being provided by a static HTML file. In addition to reading form data and sending them to search engines, servlet is sent to the client. 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 " " < Center> \N " " Search String: \ N " "
\N " " Results to show per page: \n " "

Text \ "name = \" NumResults\ "\N" "value =" NumResults "size = 3>
\N" " \N" "Google | \N" " \N " " Infoseek | \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 ("");}} CustomizedSearchengines.java SearchenginesFrontend Servlet sends data to the Customizedsearchengines Servlet. This example is similar to the example when introducing the HTTP status code in the previous example, in addition to constructing a targeted Search engine's URL and send a redirection response to the user, and 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; searchspec [] commonspecs = searchspec.getCommonspecs (); for (int i = 0; i

For example, several status code indicating "document location has changed" accompanied by a location head, and 401 (Unauthorized) status code must be accompanied by a WWW-Authenticate header. 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 later. Theservlet defaults to Text / Plain, but usually needs to be explicitly designated as Text / HTML.

Since CONTENT-TYPE is often set, HTTPSERVLETRESPONSE provides a dedicated method setContentTyep. Date current GMT time. You can use SetDateHeader to set this head to avoid the trouble of conversion time format. When expires should think that the document has expired, no longer cache it? 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"; outputln (servletutilities.headwithtitle (title) \n " "

" Title " \N" "<

H3> Primes Found with " Numdigits " or more Digits: " NumcurrentPrimes " "" f (islastResult) OUT.PRINTLN (" done search. "); Else Out.println (" STILL LOOKING FOR" NUMPRIMESREMAING "More ... ); Out.Println (" "); for (INT i = 0; i " currentprimes.elementat (i));} out.println (""); Out.println (" < / Html> ");} public void dopost (httpservletRequest request, httpservletResponse response) throws servletexception, ooException {dogt (request, response);} // checks if there is a similar type request (already completed, or being calculated). // The existence is returned to the 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.</p> <p>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. 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.</p> <p>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.</p> <p>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.</p> <p>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.</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: / / Infoseek.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 =</p> <p>baseURL; this.numResultsSuffix = numResultsSuffix;} public String makeURL (String searchString, String numResults) {return (baseURL searchString numResultsSuffix numResults);} public String getName () {return (name);} public static SearchSpec [] getCommonSpecs () {RETURN (CommonsPecs);}} Searchengines.html The following is the HTML form that calls the above servlet.</p> <p><! 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. 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).</p> <p>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 ( )}, {"Remote_user", request.getRemoteuser ()}, {"request_method", request.getMethod ()}, {"SCRI PT_NAME ", request.getServletPath ()}, {" SERVER_NAME ", request.getServerName ()}, {" 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 " " <</p> <p>Table border = 1 align = center> \N " " <tr bgcolor = \ "# 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, ooException {doget (request, response);}} HTTP request header outlines the HTTP client (eg browser), when sending a request to the server, you must specify the request type (generally get or pos ). 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. Below is some of the most common requests Head: Accept: Browser acceptable MIME type. Accept-charset: browser acceptable character set. Accept-encoding: Browser can decode data encoding, such as gzip.servlets to return to Gzip's browser The HTML page encoded by Gzip. This can reduce 5 to 10 times download time. Accept-language: The language type of browser wants to use when the server provides more than one language version. Authorization: Authorized information, usually appear in the response of the WWW-Authenticate header sent to the server in. 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.</p> <p>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. 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.haASMoreElements ()) {stri Ng headername = (string) Headernames.nextelement (); out.println ("<tr> <td>" headername); out.println ("<td>" </p> <p>request.getHeader (headerName));} out.println ( "</ TABLE> \n </ BODY> </ HTML>");} public void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doGet (request ,}}}} | Form data overview If you have used the web search engine, or browse online bookstores, stock prices, ticket information, may pay attention to some weird URLs, such as "http: // host / path? User = Marty Hall & Origin = BWI & DEST = LAX. This URL is located behind the question mark, ie "User = Marty Hall & Origin = BWI & DEST = LAX" is form data, which is the most common method of sending web page data to the server program. For the GET request, the form data is attached to the question mark of the URL (as shown in the above example); for the POST request, form data is sent to the server with a separate row. Previously, from this form of data extraction, the required form variables were one of the troublesome things in CGI programming. First, the data extraction method of the GET request and the POST request is different: for the GET request, it is usually extracted by the Query_String environment variable; for the POST request, the data is generally extracted by standard input. Second, the programmer must be responsible for truncating the variable name-variable pair at the "&" symbol, then separating the variable name (left side) and variable value (equal sign right). Third, the variable value must be performed on the URL anti-encoding operation. Because the letters and numbers are sent in the original form, the spaces are converted into a plus sign, and the other characters are converted into "% xx" form, where XX is the character ASCII represented by hexadecimal (or ISO Latin " 1) Code value. For example, if the domain value named "USERS" in the HTML form is "~ Hall, ~ Gates, and ~ McNEAL", the data sent to the server is "UserS =% 7EHALL% 2C % 7EGATES% 2C AND % 7emcnealy) ". Finally, the fourth causes the fourth result of the analysis of the analysis form data is that the variable value may be omitted (eg "param1 = val1 & param2 = & param3 = val3"), and there is also one variable to have more than one value, that is, the same variable Among the above (such as "param1 = val1 & param2 = VAL2 & param1 = val3). One of the benefits of Java Servlet is that all of the above parsed operations can be done automatically. Just simply call the getParameter method of HTTPSERVLETREQUEST, providing the name of the form variable in the call parameter (case sensitive), and the GET request and the POST request are identical.</p> <p>The return value of the getParameter method is a string, which is the corresponding value specified in the parameter, the corresponding value is obtained by the countercodes (can be used directly). If the specified form variable exists, but no value, getParameter returns an empty string; returns NULL if the specified form variable does not exist. If the form variable may correspond to multiple values, you can use GetParameterValues ​​to replace GetParameter. GetParameterValues ​​can return a string array. Finally, although the servlet is likely to use the form variables of those known words in practical applications, it is often very useful in debugging environments, which can be easily implemented using the GetParameRnames method. . getParameRNames returns an enumeration, each of which can be converted to a string that calls getParameter. 4.2 Instance: Reading three tables Unit is a simple example, which reads three tables monologous param1, param2, and param3, and lists their values ​​in the form of an HTML list. Note that although the response type (including the content type, status, and other HTTP header information) must be specified before sending the answer content, but the servlet does not require any requirements. In addition, we can easily make the servlet to process the GET request, and can handle the POST request, which only needs to call the Doget method in the dopost method, or override the service method (Service method call doget, dopost, dohead, etc. ). This is a standard method in actual programming because it only needs little additional work, but it can increase the flexibility of client encoding. If you are used to using traditional CGI methods, read POST data through standard input, then there are similar methods in the servlet, namely GetReader or GetInputStream upon httpservletRequest, but this method is too troublesome for ordinary form variables. However, if you want to upload files, or POST data is sent through a dedicated client instead of an HTML form, then this method is used. Note When you read the POST data in a second method, you cannot read these data again with GetParameter.</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 below An example looks for all the variable names sent by the form and put them in the table, no value or a variable with multiple values. 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.</p> <p>Since NexTelement returns an Object, the program converts it into a string and uses this string to call GetParameterValues. getParameterValues ​​returns a string array if this array has only one element and is equal to the empty string, indicating that this form variable does not value, and servlet outputs "no value" in a slope body; if the number of elements is greater than 1, how many of this form is more Values, servlets output these values ​​in the form of an HTML list; the servlet puts the variable value into the form in other cases. ShowParameters.java Note that ShowParameters.java uses servletutilities.java described earlier.</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 (Paramvalu E.LENGTH () == 0) Out.print ("<i> no value </ i>); else out.print (paramvalue);} else {outputln (" <ul> "); for INT i = 0; i <paramvalues.length; i ) {Out.println ("<li>" paramvalues ​​[i]);} out.println ("</ ul></p> <p>");}} Out.println (" </ TABLE> \n </ BODY> </ HTML> ");} public void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doGet (request, response); }} The test form is the form Postform.html to send data to the servlet described above. Like all forms containing password input domains, the form sends data with the Post method. We can see that doget and dopost are implemented in the servlet. The two methods have been convenient for form making.</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> <</p> <p>INPUT TYPE = "Radio" name = "cardtype" value = "discover"> 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 the 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.</p> <p>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 . 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> <p>For example, if the main directory of the servlet is C: \javawebserver\servlets, the name of the package (ie, the subdirectory name under the main directory) is Hall, under Windows, the compilation process is as follows: DOS> set classpath = C: \javawebserver\servlets ;% Classpath% DOS> CD C: \javawebserver\servlets\hall DOS> Javac Yourservlet.java The second compilation package is to enter the servlet home directory, perform "Javac Directory ..." (Windows) or "Javac Directory / YourServlet.java" (UNIX). For example, again assume that the servlet home directory is C: \javawebserver\servlets, the name of the package is Hall, the compilation process in Windows is as follows: DOS> CD C: \javawebserver\servlets dos> Javac Hall Hall WOURSERVLET.JAVA Note Under Windows, Most JDK 1.1 version of Javac requires the directory name to add to the slope (\). JDK1.2 has corrected this problem, but because many web servers still use JDK 1.1, a large number of servlet developers are still using JDK 1.1. Finally, Javac has a high-level option for supporting the source code and the .class file, you can use Javac's "-d" option to install the .class file to the Directory required by the web server. 3.2.3 Running Servlet Under Java Web Server, servlet should be placed in the servlets subdirectory of the JWS installation directory, and the URL calling servlet is http: // host / servlet / servletname. Attention The name of the subdirectory is servlets (with "S"), and the URL uses "servlet". Since the HelloWorld Servlet is placed in the package Hall, then the URL calling it should be http: //host/servlet/hall.helloworld. Methods for installing and calling servlets on other servers may be slightly different. Most web servers also allow definition of the alias of the servlet, so servlets may also call URLs in http: //host/any-path/any-file.html. How to configure how to configure the server type, please refer to the server documentation. 3.3 Output HTML's servlets most servlets output HTML, rather than outputting plain text as above. There are two additional steps to output HTML to do: telling the browser next to the HTML; modify the PrintLn statement to construct a legitimate HTML page. The first step is done by setting the Content-Type response header.</p> <p>In general, the response can be set through the setHeader method of HTTPSERVLETRESPONSE, but since the set content type is a very frequent operation, the Servlet API provides a dedicated method setContentType. Note that the setting response should be performed before sending content via the PrintWriter. Here is an example: HelloWWW.java package hall; import java.io. *; import javax.servlet *; import javax.servlet.http *; public class HelloWWW extends HttpServlet {public void doGet (HttpServletRequest request, HttpServletResponse response).. throws ServletException, IOException {response.setContentType ( "text / html"); PrintWriter out = response.getWriter (); out.println ( "! <DOCTYPE HTML PUBLIC \" - // W3C // DTD HTML 4.0 " " Transitional // EN \ "> \N" "<html> \n" "<head> <title> Hello WWW </ title> </ head> \n" "<body> \N" "<H1 > Hello WWW </ h1> \n " " </ body> </ html> ");}} 3.4 Several HTML tool functions Output HTML through the PrintLn statement is inconvenient, fundamental solution is to use JavaServer Pages (JSP ). However, for standard servlets, since there are two parts (DOCTYPE and HEAD) in the web page, they can be encapsulated by tool functions. Although most mainstream browsers ignore the DOCTYPE line, it is strictly that the HTML specification is required to have DOCTYPE lines, which helps the HTML syntax checkter check the HTML document legality according to the declared HTML version. In many web pages, the Head section only contains <title>. Although many experienced writers will contain many Meta tags and style declarations in HEAD, but here only consider the simplest case. The following Java method only accepts the page title as a parameter, then outputs the DOCTYPE, Head, Title section of the page.</p> <p>List is as follows: ServletUtilities.java package hall; public class ServletUtilities {public static final String DOCTYPE = "<! DOCTYPE HTML PUBLIC \" - // W3C // DTD HTML 4.0 Transitional // EN\ ">"; public static String headWithTitle ( String title) {return (Docty "\N" "<html> \n" "<head> <title>" title "</ title> </ head> \n");} // Other The code of the tool function is introduced later} HellowW2.java below is the Hellowww2: package hall to rewrite the HellowWW class after servletutilities; import javax.Servlet. *; Import javax.servlet.http. *; public class HelloWWW2 extends HttpServlet {public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {response.setContentType ( "text / html"); PrintWriter out = response.getWriter (); out.println (ServletUtilities.headWithTitle ("Hello WWW") "<body> \N" "<h1> Hello WWW </ h1> \n" "</ body> </ html>");}} Installing the Servlet and JSP development tools Learn Servle T and JSP development, first you have to prepare a development environment that conforms to Java Servlet 2.1 / 2.0 and JavaServer Pages1.0 / 1.1 specification. Sun offers free JavaServer Web Development Kit (JSWDK), you can download from http://java.sun.com/products/servlet/. After installing JSWDK, you have to tell Javac, where to find the Servlet and JSP classes when compiling files. The JSWDK Installation Guide has a detailed description of this, but mainly to join servlet.jar and jsp.jar to ClassPath.</p> <p>ClassPath is an environment variable indicating how Java is looking for class files. If you do not set ClassPath, Java is looking for classes in the current directory and standard system library; if you settle ClassPath, don't forget to include the current directory (ie, in classpath ". "). In addition, in order to avoid name conflicts to install and other developers to servlets on the same web server, it is best to put their own servlet into the package. At this point, there is a lot of convenience to ClassPath in the top-level directory in the package hierarchy. Please refer to the details below. 2.2 Installation Support Servlet Web Server In addition to development tools, you have to install a web server that supports Java Servlet, or installs a servlet package on an existing web server. If you are using the latest web server or application server, it is likely that it already has all necessary software. Check the web server document, or visit http://java.sun.com/products/servlet/industry.html View the list of server software that supports servlet. Although the final run Servlet is often a business-grade server, it is enough to develop and test with a free system that can run on the desktop. Below is a few of the current most popular products. Apache Tomcat. Tomcat is an official reference implementation of Servlet 2.2 and JSP 1.1 specification. Tomcat can be used separately as a small servlet, a JSP test server, or can also be integrated into the Apache Web server. Until 2000, Tomcat is only the only server that supports Servlet 2.2 and JSP 1.1 specification, but many other servers have announced their support. Tomcat and Apache are free. However, fast, stable Apache servers have a bit troublesome, Tomcat has the same shortcomings. Compared with other business-grade Servlet Engines, the workload of Tomcat is obviously more than one. For details, see http://jakarta.apache.org/. JavaServer Web Development Kit (JSWDK). JSWDK is an official reference implementation of Servlet 2.1 and JSP 1.0. The JSWDK can be separate as a small servlet, a JSP test server before deploying Servlet and JSP applications to officially running their servers. JSWDK is also free and has good stability, but its installation and configuration is also more complicated. For details, see http://java.sun.com/products/servlet/download.html. Allaire Jrun. JRun is a servlet and JSP engine that can be integrated into Netscape Enterprise or FastTrack Server, IIS, Microsoft Personal Web Server, low version of Apache, O'Eilly's WebSite or Starnine Web Star. Up to 5 concurrently connected restrictions are free, there is no restriction in commercial versions, and the functions such as the remote management console are added. See http://www.allaire.com/products/jrun/ for details. New Atlanta's servletexec servletexec is a fast servlet and JSP engine that integrates to most popular web servers, support platforms include Solaris, Windows, Macos, HP-UX, and Linux.</p> <p>ServleTexec can be downloaded and used for free, but many advanced features and management tools can only be used after purchasing licenses. New Atlanta also offers a free servlet debugger that works in many popular Java IDEs. See http://newatlanta.com/ for details. GEFION LiteWebserver (LWS) LWS is a free small web server that supports Servlet 2.2 and JSP 1.1. Gefion also has a free Wai Chiolrunner plugin that uses the plugin to add Servlet 2.2 and JSP 1.1 support for Netscape FastTrack and Enterprise Server. See http://www.gefionsoftware.com/. Sun's Java Web Server. This server is written in Java, and is one of the Web servers that first provides a complete support for Servlet 2.1 and JSP 1.0 specification. Although Sun has now turned to Netscape / I-Planet Server, Java Web Server is no longer developed, but it is still a popular servlet, JSP learning platform. To get a free trial version, please visit http://www.sun.com/software/jwebserver/try/. Java servlet and its characteristics servlet are Java technology to answer CGI programming. The servlet program runs in the server side, dynamically generates a web page. Compared to traditional CGIs and many other similar CGI technologies, Java servlets have higher efficiency, easier to use, more powerful, better portability, saving more investment (more important, servlet programmers The income is higher than the Perl programmer :-): Efficient. In the traditional CGI, each request will start a new process. If the CGI program itself has a short period of execution, the overhead required to start the process is likely to exceed the actual execution time. In the servlet, each request is processed by a lightweight Java thread (not the heavyweight operating system process). In the traditional CGI, if there is a request to the same CGI program, the code of the CGI program is repeated in memory in memory; for servlet, the request is N thread, only one servlet Class code. In terms of performance optimization, servlets have more choices than CGI, such as buffering previous calculations, maintaining the activity of the database connection, and so on. Convenience. Servlet provides a large number of utility routines, such as automatically parsing and decoding HTML form data, reading, and setting up HTTP headers, processing cookies, tracking session status, etc. Powerful. In servlet, many tasks that use traditional CGI programs are easy to complete. For example, servlets can interact directly with the web server, while ordinary CGI programs cannot. Servlets are also capable of sharing data between individual programs, making it easy to implement the functions such as database connection pools. It is good to be portable. Servlet is written in Java, servlet API has a perfect standard. Therefore, servlet written for I-Planet Enterprise Server can be ported to Apache, Microsoft IIS or WebStar without any substantial changes. Almost all mainstream servers support the servlet directly or through the plugin. Save investment.</p> <p>Not only is there many cheap or even free web servers available for personal or small-scale websites, but also for existing servers, if it doesn't support servlet, add this part of the function is often free (or only very small investment). 1.2 JSP and its Features JavaServer Pages (JSP) are a technique that implements normal static HTML and dynamic HTML mixed encoding. For details on the JSP basic concept, see "JSP Technical Introduction". Many of the pages generated by the CGI program are still still static HTML, and the dynamic content appears only in several parts of the page. However, most CGI technology, including servlets and variants, always generates the entire page via the program. JSP makes we can create these two parts, respectively. For example, the following is a simple JSP page: <! Doctype html public "- // w3c // DTD HTML 4.0 Transitional // en"> <html> <head> <title> Welcome to the online store </ title> </ HEAD> <body> <h1> Welcome </ h1> <small> Welcome, <! - The user name for the first visit is "new user" -> <% out.println (utils.getusernamefromcookie (request));% > To set up account information, click <a href="account-settings.html"> here </a> </ small> <p> page of the rest of the content. </ Body> </ html> The following is a simple comparison of JSP and other similar or related technologies: JSP and Active Server Pages (ASP) Compared to Microsoft ASPs are similar technologies similar to JSP. JSP and ASP have the advantages of two aspects. First, the dynamic part is written in Java, not the VB Script or other Microsoft language, not only more powerful and easier to use. Second, JSP applications can be ported to other operating systems and non-Microsoft web servers. JSP and pure servlets have not increased any functionality that cannot be used in nature than the JSP. However, writing static HTML in JSP is more convenient, do not have to use the PrintLn statement to output each line HTML code. More importantly, with the separation of the content and appearance, the task of different nature in the page can be conveniently separated: For example, the page design expert is HTML design, and the space for the servlet programmer is inserted into the dynamic content. The JSP and server-side include (Server-Side Include, SSI) compared to SSI is a widely supported technology that introduces external codes in static HTML. JSP support is more perfect in this regard because it can generate dynamic content with servlet instead of independent programs.</p></div><div class="text-center mt-3 text-grey"> 转载请注明原文地址:https://www.9cbs.com/read-114672.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="114672" 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.075</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 = 'daCiDCLf_2F2_2BAR3tqKsHZuJ6izsIDGHFjoq9ImuWy85ISHUGoZyDpF3vB0674x2F_2B81ZhRIUOo_2FBerjo7Ki3Tsg_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>