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")%> i> JSP page file usually with .jsp is extension, and can be installed to any place where a normal web page can be installed. Although the JSP page is more like a normal web page, the JSP page is more like a servlet, but in fact, JSP will eventually be converted into a regular servlet, and the static HTML directly outputs the output stream associated with the Servlet Service method. The conversion process of JSP to Servlet generally is performed when the first page request appears. So if you want the first user to wait too long because the JSP page is converted to servlet, I hope that the servlet has been properly compiled and loaded, and you can request this page after installing the JSP page. Also note that many web servers allow define alias, so a URL that looks to the HTML file is actually pointing to the servlet or JSP page. In addition to ordinary HTML code, other components embedded in JSP pages mainly have the following three: scripting element, command (Directive), Action. The script elements are used to embed Java code, which will become part of the SERVLET that is converted; the JSP instruction is used to control the structure of the servlet as a whole; the action is used to introduce an existing component or control the JSP engine. To simplify scripting elements, JSP defines a set of variables (predefined variables) that can be used (predefined variables), such as REQUEST in the front code segment is one of them. Note This article is based on JSP 1.0 specification. Compared with the 0.92 version, the new version of JSP made a lot of major changes. Although these modifications will only make JSP better, it should be noted that the JSP page of 1.0 is almost not compatible with the early JSP engines. 11.2 JSP Syntax Summary Table JSP Element Syntax Description Remarks JSP Expression <% = Expression%> Calculate the expression and output the result. Equivalent XML expression is:
JSP Scriptlet <% Code%> Insert the code of the service method. Equivalent XML expression is:
JSP: UseBean action
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 " "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" " TABLE> \N" "< / BODY> HTML> ");} 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) Table border = 1 align = center> \N " " | |||||||||
cgi variable name | value "); for (int i = 0; i " varname " | " 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.
| 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. 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 " " " title " h1> \N " " Request method: b> " Request.getMethod () " Header Value "; Enumeration Headernames = Request.getHeadernames (); While (Headernames.haASMoreElements ()) {stri Ng headername = (string) Headernames.nextelement (); out.println (" | " headername); out.println (" | "
| 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. The return value of the getParameter method is a string, which is the corresponding value specified in the parameter, the corresponding value is obtained by the countercodes (can be used directly). If the specified form variable exists, but no value, getParameter returns an empty string; returns NULL if the specified form variable does not exist. If the form variable may correspond to multiple values, you can use GetParameterValues to replace GetParameter. GetParameterValues can return a string array. Finally, although the servlet is likely to use the form variables of those known words in practical applications, it is often very useful in debugging environments, which can be easily implemented using the GetParameRnames method. . getParameRNames returns an enumeration, each of which can be converted to a string that calls getParameter. 4.2 Instance: Reading three tables Unit is a simple example, which reads three tables monologous param1, param2, and param3, and lists their values in the form of an HTML list. Note that although the response type (including the content type, status, and other HTTP header information) must be specified before sending the answer content, but the servlet does not require any requirements. In addition, we can easily make the servlet to process the GET request, and can handle the POST request, which only needs to call the Doget method in the dopost method, or override the service method (Service method call doget, dopost, dohead, etc. ). This is a standard method in actual programming because it only needs little additional work, but it can increase the flexibility of client encoding. If you are used to using traditional CGI methods, read POST data through standard input, then there are similar methods in the servlet, namely GetReader or GetInputStream upon httpservletRequest, but this method is too troublesome for ordinary form variables. However, if you want to upload files, or POST data is sent through a dedicated client instead of an HTML form, then this method is used. Note When you read the POST data in a second method, you cannot read these data again with GetParameter. ThreeParams.java package hall; import java.io. *; import javax.servlet *;. Import javax.servlet.http *;. Import java.util *;. Public class ThreeParams extends HttpServlet {public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {response.setContentType ( "text / html"); PrintWriter out = response.getWriter (); String title = "request read three parameters"; out.println (ServletUtilities.headWithTitle (title) " \N" "" " " Since NexTelement returns an Object, the program converts it into a string and uses this string to call GetParameterValues. getParameterValues returns a string array if this array has only one element and is equal to the empty string, indicating that this form variable does not value, and servlet outputs "no value" in a slope body; if the number of elements is greater than 1, how many of this form is more Values, servlets output these values in the form of an HTML list; the servlet puts the variable value into the form in other cases. ShowParameters.java Note that ShowParameters.java uses servletutilities.java described earlier. package hall; import java.io. *; import javax.servlet *;. import javax.servlet.http *;. import java.util *;. public class ShowParameters extends HttpServlet {public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {response.setContentType ( "text / html"); PrintWriter out = response.getWriter (); String title = "read all request parameters"; out.println (ServletUtilities.headWithTitle (title) " \N " "" "
|