Servlet and JSP tutorial

xiaoxiao2021-03-06  14

Servlet and JSP Tutorial (1) -Servlet and JSP Overview

First, Servlet and JSP Overview

1.1 Java servlet and its characteristics

Servlet is 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.

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 characteristics

JavaServer Pages (JSP) is a technique that implements normal static HTML and dynamic HTML mixed encoding. See "JSP Technical Introduction" instructions for JSP basic concepts.

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:

Welcome to the online store </ title> </ head></p> <p><Body></p> <p><H1> Welcome </ h1></p> <p><Small> Welcome,</p> <p><! - The username of the first visit is "new user" -> <% out.println (utils.getusernamefromcookie (request));%></p> <p>To set an account information, please click</p> <p><a href="account-settings.html"> here </a </ small></p> <p><P></p> <p>The rest of the page. .</p> <p></ Body> </ html></p> <p>Below is a simple comparison of JSP and other similar or related technologies:</p> <p>JSP and Active Server Pages (ASP)</p> <p>Microsoft's ASP is a similar technology 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.</p> <p>JSP and pure servlet</p> <p>JSP does not increase any functionality that cannot be implemented in nature. 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.</p> <p>JSP and server-side include (Server-Side Include, SSI)</p> <p>SSI is a technique that is widely supported in a static HTML introduces external code. JSP support is more perfect in this regard because it can generate dynamic content with servlet instead of independent programs. In addition, SSI is actually only used in simple containers, rather than facing "real" programs that can handle form data and access databases.</p> <p>JSP and JavaScript compared to JavaScript</p> <p>JavaScript can dynamically generate HTML on the client. Although JavaScript is useful, it can only handle dynamic information based on the client environment. In addition to cookies, HTTP status and form submission data are unavailable for JavaScript. In addition, JavaScript cannot access server-end resources, such as databases, directory information, and more.</p> <p>Servlet and JSP Tutorial (2) - Setting development, operating environment</p> <p>Second, set development, operating environment</p> <p>2.1 Install Servlet and JSP Development Tools</p> <p>To learn Servlet and JSP development, you must first prepare a development environment that meets Java Servlet 2.2 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/.</p> <p>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. 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.</p> <p>2.2 Installing the web server supporting servlet</p> <p>In addition to the development tool, 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.</p> <p>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.</p> <p>Apache Tomcat.</p> <p>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.</p> <p>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/.</p> <p>JavaServer Web Development Kit (JSWDK).</p> <p>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.</p> <p>Allaire Jrun.</p> <p>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`elly 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.</p> <p>New Atlanta's servletexec</p> <p>ServletExec is a quick servlet and JSP engine that integrates to most popular web servers, support platforms include Solaris, Windows, MacOS, HP-UX, and Linux. 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's LiteWeb Server (LWS)</p> <p>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/.</p> <p>Sun's Java Web Server.</p> <p>The 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/.</p> <p>Servlet and JSP Tutorial (3)</p> <p>If a class wants to be a servlet, it should inherit from httpservlet, sending one or all of the DOGET, DOPOST method based on the data. DOGET and DOPOST methods have two parameters, which are HTTPSERVLETREQUEST types and httpservletResponse types, respectively. HTTPServletRequest provides methods for accessing information about the request, such as form data, HTTP request head, and more. In addition to providing methods for specifying HTTP response status (200, 404, etc.), response head (Content-type, set-cookie, etc.), is the most important thing that it provides a PrintWriter for sending data to the client . For simple servlets, most of its work is to generate a page sent to the client via the PrintLn statement.</p> <p>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).</p> <p>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.</p> <p>3.2 Simple servlet for outputting plain text</p> <p>Here is a simple servlet that outputs plain text.</p> <p>3.2.1 HelloWorld.java</p> <p>Package Hall;</p> <p>Import java.io. *;</p> <p>Import javax.servlet. *;</p> <p>Import javax.servlet.http. *;</p> <p>Public class helloworld extends httpservlet {</p> <p>Public void doget (httpservletRequest request, httpservletResponse response)</p> <p>Throws servletexception, ioException {</p> <p>PrintWriter out = response.getwriter ();</p> <p>Out.println ("Hello World");</p> <p>}</p> <p>}</p> <p>3.2.2 Compilation and installation of servlet</p> <p>The specific details of the installed servlet on different web servers may be different, please refer to the web server documentation to learn 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.</p> <p>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.</p> <p>For beginners who have not used bags, let's introduce two methods of the class inside the compilation package.</p> <p>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. For example, if the servlet's home directory is C: \javawebserver\serven, the name of the package (ie, the subdirectory name under the main directory) is Hall, under Windows, the compilation process is as follows:</p> <p>DOS> SET CLASSPATH = C: \javawebserver\servlets;% classpath%</p> <p>DOS> CD C: \javawebserver\servlets\hall</p> <p>DOS> javac yourservlet.java</p> <p>The method of servlet in the second compilation package is to enter the servlet home directory, perform "Javac Directory ..." 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, and the compilation process in Windows is as follows:</p> <p>DOS> CD C: \javawebserver\serven</p> <p>DOS> javac hall \yourrseervlet.java</p> <p>Note Under Windows, most JDK 1.1 version of Javac requires the directory name to rendezon (\). 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.</p> <p>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 Run servlet</p> <p>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.</p> <p>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.</p> <p>3.3 Servlets Output HTML</p> <p>Both of the 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.</p> <p>The first step is done by setting the Content-Type response header. 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:</p> <p>Hellowwww.java</p> <p>Package Hall;</p> <p>Import java.io. *;</p> <p>Import javax.servlet. *;</p> <p>Import javax.servlet.http. *;</p> <p>Public class hellowwww extends httpservlet {</p> <p>Public void doget (httpservletRequest Request,</p> <p>Httpservletresponse response</p> <p>Throws servletexception, ioException {</p> <p>Response.setContentType (Text / HTML ");</p> <p>PrintWriter out = response.getwriter ();</p> <p>Out.println ("<! doctype html public \" - // w3c // DTD HTML 4.0 " </p> <p>"Transitional // eN\"> \n " </p> <p>"<Html> \n" </p> <p>"<Head> <title> Hello WWW </ title> </ head> \n" </p> <p>"<Body> \n" </p> <p>"<H1> Hello WWW </ h1> \n" </p> <p>"</ Body> </ html>");</p> <p>}</p> <p>}</p> <p>3.4 Several HTML Tools Functions</p> <p>Output HTML via the PrintLn statement is not convenient, the 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.</p> <p>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.</p> <p>The following Java method only accepts the page title as a parameter, then outputs the DOCTYPE, Head, Title section of the page. The list is as follows:</p> <p>ServletUtilities.java</p> <p>Package Hall;</p> <p>Public class servletutilities {</p> <p>Public static final string docType =</p> <p>"<! Doctype html public \" - // w3c // DTD HTML 4.0 Transitional // EN \ ">"</p> <p>Public static string headwithtitle (String Title) {</p> <p>Return (DOCTYPE "\N" </p> <p>"<Html> \n" </p> <p>"<Head> <title>" title "</ title> </ head> \n");</p> <p>}</p> <p>// The code for other tool functions is introduced later this article</p> <p>}</p> <p>Hellowww2.java</p> <p>Below is the HellowW2 obtained after the use of servletUtilities after rewriting the HellowWW class:</p> <p>Package Hall;</p> <p>Import java.io. *;</p> <p>Import javax.servlet. *;</p> <p>Import javax.servlet.http. *;</p> <p>Public class hellowwww2 extends httpservlet {</p> <p>Public void doget (httpservletRequest Request,</p> <p>Httpservletresponse response</p> <p>Throws servletexception, ioException {</p> <p>Response.setContentType (Text / HTML ");</p> <p>PrintWriter out = response.getwriter ();</p> <p>Out.println (ServletUtilities.Headwithtitle ("Hello WWW") </p> <p>"<Body> \n" </p> <p>"<H1> Hello WWW </ h1> \n" </p> <p>"</ Body> </ html>");</p> <p>}</p> <p>}</p> <p>Servlet with JSP Tutorial (4)</p> <p>Fourth, deal with form data</p> <p>4.1 Form Data Overview</p> <p>If you have used the web search engine, or browse online bookstores, stock prices, ticket information, may pay attention to some weird URLs, such as "http: // host / path? User = marty hall & origin = bwi & dest = LAX" . This URL is located behind the question mark, ie "User = Marty Hall & Origin = BWI & DEST = LAX" is form data, which is the most common method of sending web page data to the server program. For the GET request, the form data is attached to the question mark of the URL (as shown in the above example); for the POST request, form data is sent to the server with a separate row. Previously, from this form of data extraction, the required form variables were one of the troublesome things in CGI programming. First, the data extraction method of the GET request and the POST request is different: for the GET request, it is usually extracted by the Query_String environment variable; for the POST request, the data is generally extracted by standard input. Second, the programmer must be responsible for truncating the variable name-variable pair at the "&" symbol, then separating the variable name (left side) and variable value (equal sign right). Third, the variable value must be performed on the URL anti-encoding operation. Because the letters and numbers are sent in the original form, the spaces are converted into a plus sign, and the other characters are converted into "% xx" form, where XX is the character ASCII represented by hexadecimal (or ISO Latin " 1) Code value. For example, if the domain value named "USERS" in the HTML form is "~ Hall, ~ Gates, and ~ McNEAL", the data sent to the server is "UserS =% 7EHALL% 2C % 7EGATES% 2C AND % 7emcnealy) ". Finally, the fourth causes the fourth result of the analysis of the parsing form data is that the variable value may be omitted (such as "param1 = var_ param2 = & param3 = val3"), and it is possible that a variable has more than one value, that is, the same variable Among the above (such as "param1 = val1 & param2 = VAL2 & param1 = val3).</p> <p>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.</p> <p>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 Example: Read three table single variables</p> <p>Here is a simple example that reads three form variable param1, param2, and param3, and lists them 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.</p> <p>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.</p> <p>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.</p> <p>Note When you read the POST data in a second method, you cannot read these data again with GetParameter.</p> <p>Threeparams.java</p> <p>Package Hall;</p> <p>Import java.io. *;</p> <p>Import javax.servlet. *;</p> <p>Import javax.servlet.http. *;</p> <p>Import java.util. *;</p> <p>Public class threeparams extends httpservlet {</p> <p>Public void doget (httpservletRequest Request,</p> <p>Httpservletresponse response</p> <p>Throws servletexception, ioException {</p> <p>Response.setContentType (Text / HTML ");</p> <p>PrintWriter out = response.getwriter ();</p> <p>String Title = "Read three request parameters";</p> <p>Out.println (servletutilities.headwithtitle (title) </p> <p>"<Body> \n" </p> <p>"<H1 align = center>" Title "</ h1> \n" </p> <p>"<Ul> \N" </p> <p><Li> param1: "</p> <p> Request.GetParameter ("param1") "\n" </p> <p><Li> param2: "</p> <p> Request.getParameter ("param2") "\N" "<li> param3:"</p> <p> Request.GetParameter ("param3") "\n" </p> <p>"</ Ul> \n" </p> <p>"</ Body> </ html>");</p> <p>}</p> <p>Public void dopost (httpservletRequest Request,</p> <p>Httpservletresponse response</p> <p>Throws servletexception, ioException {</p> <p>DOGET (Request, Response);</p> <p>}</p> <p>}</p> <p>4.3 Example: Output All Form Data</p> <p>The following example looks for all the variable names sent by the form, and put them in the table, no value or variables with multiple values ​​are highlighted.</p> <p>First, the program gets all the variable names through the GetParameterNames method of HTTPSERVLETREQUEST, and getParameterNames returns an enumeration. Next, the program uses a loop to traverse this Enumeration, determine when to end the loop via HasMELEMENTS, use the nextElement to get the enumerations in the enumeration. Since NexTelement returns an Object, the program converts it into a string and uses this string to call GetParameterValues.</p> <p>getParameterValues ​​returns a string array if this array has only one element and is equal to the empty string, indicating that this form variable does not value, and servlet outputs "no value" in a slope body; if the number of elements is greater than 1, how many of this form is more Values, servlets output these values ​​in the form of an HTML list; the servlet puts the variable value into the form in other cases.</p> <p>Showparameters.java</p> <p>Note that ShowParameters.java uses servletutilities.java described earlier.</p> <p>Package Hall;</p> <p>Import java.io. *;</p> <p>Import javax.servlet. *;</p> <p>Import javax.servlet.http. *;</p> <p>Import java.util. *;</p> <p>Public class showparameters extends httpservlet {</p> <p>Public void doget (httpservletRequest Request,</p> <p>Httpservletresponse response</p> <p>Throws servletexception, ioException {</p> <p>Response.setContentType (Text / HTML ");</p> <p>PrintWriter out = response.getwriter ();</p> <p>String Title = "Read all request parameters";</p> <p>Out.println (servletutilities.headwithtitle (title) </p> <p>"<Body bgcolor = \" # fdf5e6\ "> \n" </p> <p>"<H1 align = center>" Title "</ h1> \n" "<Table Border = 1 Align = Center> \N" </p> <p>"<Tr bgcolor = \" # ffad00\ "> \n" </p> <p>"<TH> Parameter Name <TH> Parameter Value");</p> <p>Enumeration paramnames = request.getParameterNames ();</p> <p>While (paramnames.hasmoreElements ()) {</p> <p>String paramname = (string) paramnames.nextelement ();</p> <p>Out.println ("<TR> <TD>" paramname "\ N <TD>");</p> <p>String [] Paramvalues ​​= Request.getParameterValues ​​(paramname);</p> <p>IF (paramvalues.length == 1) {</p> <p>String Paramvalue = paramvalues ​​[0];</p> <p>IF (paramvalue.length () == 0)</p> <p>Out.print ("<i> NO value </ i>);</p> <p>Else</p> <p>Out.print (Paramvalue);</p> <p>} else {</p> <p>Out.println ("<UL>");</p> <p>For (int i = 0; i <paramvalues.length; i ) {</p> <p>OUT.PRINTLN ("<li>" paramvalues ​​[i]);</p> <p>}</p> <p>Out.println ("</ ul>");</p> <p>}</p> <p>}</p> <p>Out.println ("</ Table> \ N </ Body> </ html>");</p> <p>}</p> <p>Public void dopost (httpservletRequest Request,</p> <p>Httpservletresponse response</p> <p>Throws servletexception, ioException {</p> <p>DOGET (Request, Response);</p> <p>}</p> <p>}</p> <p>Test form</p> <p>Here is a form Postform.html that sends data to the servlet described above. Just like all forms containing password input domains, the table sends data with the POST method. We can see that the two methods of doget and dopost have brought convenience to form production in the servlet.</p> <p><! Doctype html public "- // w3c // DTD HTML 4.0 Transitional // En"></p> <p><Html></p> <p><HEAD></p> <p><Title> Example Form </ Title></p> <p></ HEAD></p> <p><Body bgcolor = "# fdf5e6"> <h1 align = "center"> with post method to send data form </ h1></p> <p><Form action = "/ servlet / hall.showparameters"</p> <p>Method = "POST"></p> <p>Item Number:</p> <p><Input Type = "Text" Name = "itemnum"> <br></p> <p>Quantity:</p> <p><Input Type = "text" name = "quantity"> <br></p> <p>Price Each:</p> <p><Input Type = "text" name = "price" value = "$"> <br></p> <p><Hr></p> <p>First Name:</p> <p><Input Type = "text" name = "firstname"> <br></p> <p>Last Name:</p> <p><Input Type = "text" name = "lastname"> <br></p> <p>Middle Initial:</p> <p><Input type = "text" name = "initial"> <br></p> <p>Shipping address:</p> <p><Textarea name = "address" ROWS = 3 cols = 40> </ textarea> <br></p> <p>Credit Card: <br></p> <p><Input Type = "Radio" name = "cardType"</p> <p>Value = "Visa"> VISA <br></p> <p><Input Type = "Radio" name = "cardType"</p> <p>Value = "Master Card"> Master Card <br></p> <p><Input Type = "Radio" name = "cardType"</p> <p>Value = "AMEX"> American Express <br></p> <p><Input Type = "Radio" name = "cardType"</p> <p>Value = "Discover"> Discover <br></p> <p><Input Type = "Radio" name = "cardType"</p> <p>Value = "Java SmartCard"> Java SmartCard <br></p> <p>Credit Card Number: <input type = "password" name = "cardnum"> <br></p> <p>REPEAT CREDIT CARD NUMBER:</p> <p><INPUT TYPE = "PASSWORD" NAME = "cardNum"> <BR> <BR></p> <p><Center></p> <p><Input Type = "Submit" value = "submit order"></p> <p></ Center></p> <p></ Form></p> <p></ Body></p> <p></ Html></p> <p>Servlet with JSP Tutorial (5) - Read HTTP Request Head</p> <p>V. Read HTTP request header</p> <p>5.1 HTTP Request First Overview</p> <p>The HTTP client (such as a browser) must specify the request type when sending a request to the server (typically GET or POST). If necessary, the client can also choose to send other request heads. Most requested heads are not required, except for Content-Length. Content-length must appear for POST requests.</p> <p>Here are some of the most common request heads:</p> <p>Accept: The browser acceptable MIME type.</p> <p>Accept-charset: The browser acceptable character set.</p> <p>Accept-encoding: Browser can decode data encoding, such as Gzip. Servlets are able to return to Gzip's browsers to returns the Gzip encoded HTML page. This can reduce download time by 5 to 10 times in many cases.</p> <p>Accept-language: The language type of the browser wants to use when the server provides more than one language version.</p> <p>Authorization: Authorized information, usually appears in a response to the WWW-Authenticate header sent to the server.</p> <p>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.</p> <p>Content-length: Indicates the length of the text of the request message.</p> <p>Cookie: This is one of the most important request headers, see the discussion in the chapter of "Cookie Processing" later.</p> <p>From: Request the sender's Email address, use some special web clients, the browser will not use it.</p> <p>Host: The host and port in the initial URL.</p> <p>If-modified-since: Only returns it only when the requested content is modified after the specified date, otherwise returns the 304 "Not Modified" response.</p> <p>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.</p> <p>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.</p> <p>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.</p> <p>For complete, detailed descriptions of HTTP headers, see http specifications http://www.w3.org/protocols/.</p> <p>5.2 Read the request head in the servlet</p> <p>It is very convenient to read the HTTP header in the servlet, just call the GetHeader method for 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.</p> <p>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.</p> <p>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".</p> <p>5.3 Example: Output All Request Head</p> <p>The following servlet instance outputs all the 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</p> <p>Package Hall;</p> <p>Import java.io. *;</p> <p>Import javax.servlet. *;</p> <p>Import javax.servlet.http. *;</p> <p>Import java.util. *;</p> <p>Public class showrequestheaders extends httpservlet {</p> <p>Public void doget (httpservletRequest Request,</p> <p>Httpservletresponse response</p> <p>Throws servletexception, ioException {</p> <p>Response.setContentType (Text / HTML ");</p> <p>PrintWriter out = response.getwriter ();</p> <p>String Title = "Show all request headers";</p> <p>Out.println (servletutilities.headwithtitle (title) </p> <p>"<Body bgcolor = \" # fdf5e6\ "> \n" </p> <p>"<H1 align = center>" Title "</ h1> \N" "<b> Request method: </ b>" </p> <p>Request.getMethod () "<br> \N" </p> <p><B> Request Uri: </ b> " </p> <p>Request.getRequesturi () "<br> \n" </p> <p><B> Request Protocol: </ b> " </p> <p>request.getProtocol () "<BR> <BR> \n" </p> <p>"<Table border = 1 align = center> \n" </p> <p>"<Tr bgcolor = \" # ffad00\ "> \n" </p> <p>"<TH> Header Name <TH> Header Value");</p> <p>Enumeration headernames = Request.getHeadernames ();</p> <p>While (Headernames.hasMoreElements ()) {</p> <p>String headername = (string) Headernames.nexTelement ();</p> <p>Out.println ("<TR> <TD> Headername);</p> <p>Out.println ("<TD>" Request.getHeader (HeaderName));</p> <p>}</p> <p>Out.println ("</ Table> \ N </ Body> </ html>");</p> <p>}</p> <p>Public void dopost (httpservletRequest Request,</p> <p>Httpservletresponse response</p> <p>Throws servletexception, ioException {</p> <p>DOGET (Request, Response);</p> <p>}</p> <p>}</p> <p>Servlet and JSP Tutorial (6) - Access CGI Variables</p> <p>6. Access CGI variables</p> <p>6.1 Overview of CGI Variables</p> <p>If you are using traditional CGI programming to learn Java servlet, perhaps the concept of "CGI variable". The CGI variable brings together various information about the request:</p> <p>Part is from HTTP request commands and request heads, such as Content-Length Heads;</p> <p>Part is from the socket itself, such as the name and IP address of the host;</p> <p>There is also a portion of the server installation configuration, such as the URL to the actual path.</p> <p>6.2 Servlet equivalence of standard CGI variables</p> <p>The following table assumes that the Request object is an HttpServletRequest type object that provides the Doget and dopost methods. CGI variable meanings from doget or dopost</p> <p>Auth_Type If the Authorization header is provided, the specific mode is specified here (Basic or Digest). Request.GetAuthType () Content_length is only used for POST requests, indicating the number of bytes sent. Strictly speaking, equivalent expression should be string.valueof (Request.getContentLength ()) (return a string). But more common is to return the same integer with Request.getContentLength ().</p> <p>Content_Type If specified, it means the type of the following data. Request.getContentType ()</p> <p>Document_root with http: // host / corresponding path. GetServletContext (). getRealPath ("/")</p> <p>Note that the equivalence expression in the low version servlet specification is request.getRealPath ("/").</p> <p>HTTP_XXX_YYY visits any HTTP header. Request.getHeader ("XXX-YYY")</p> <p>Additional path information in the PATH_INFO URL, that is, after the servlet path in the URL, the part before the string is queried. Request.getPathInfo ()</p> <p>Path_Translated path information after mapping the actual path of the server. Request.getPathTranslated ()</p> <p>Query_String This is a query string that is attached to the URL of the string, and 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 ()</p> <p>Remote_addr issues the IP address of the requesting client. Request.getRemoteAddr ()</p> <p>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 ()</p> <p>Remote_User If the Authorization header is provided, it represents its part of the user. It represents the name of the user who issues a request. Request.getRemoteuser ()</p> <p>Request_method request type. Usually GET or POST. But occasionally also appear in HEAD, PUT, DELETE, OPTIONS, or Trace. Request.getMethod ()</p> <p>The part of the Script_name URL calls servlet does not contain additional path information and query strings. Request.getServletPath ()</p> <p>Server_name web server name. Request.getServerName ()</p> <p>The port of the Server_Port server listening. 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.</p> <p>Server_Protocol Requests the protocol name and version of the command (ie HTTP / 1.0 or HTTP / 1.1). Request.GetProtocol ()</p> <p>The name and version of the Server_Software Servlet engine. GetServletContext (). getServerInfo ()</p> <p>6.3 Example: Read CGI Variables</p> <p>Below this servlet creates 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</p> <p>Package Hall;</p> <p>Import java.io. *;</p> <p>Import javax.servlet. *;</p> <p>Import javax.servlet.http. *;</p> <p>Import java.util. *;</p> <p>Public class showcgivariables extends httpservlet {</p> <p>Public void doget (httpservletRequest Request,</p> <p>Httpservletresponse response</p> <p>Throws servletexception, ioException {</p> <p>Response.setContentType (Text / HTML ");</p> <p>PrintWriter out = response.getwriter ();</p> <p>String [] Variables =</p> <p>{{"Auth_type", request.getauthtype ()},</p> <p>{"Content_length", String.Valueof (Request.GetContentLength ())},</p> <p>{"Content_Type", request.getContentType ()},</p> <p>{"Document_Root", GetServletContext (). GetRealPath ("/")},</p> <p>{"Path_info", Request.getPathInfo ()},</p> <p>{"Path_Translated", request.getPathtranslated ()},</p> <p>{"Query_String", request.getQueryString ()},</p> <p>{"Remote_addr", request.getRemoteAddr ()},</p> <p>{"Remote_host", request.getRemotehost ()},</p> <p>{"Remote_user", request.getRemoteuser ()},</p> <p>{"Request_Method", Request.getMethod ()},</p> <p>{"Script_name", request.getServletPath ()},</p> <p>{"Server_name", request.getServerName ()},</p> <p>{"Server_Port", String.Valueof (Request.getServerPort ())},</p> <p>{"Server_Protocol", request.getProtocol (),</p> <p>{"Server_software", getServletContext (). GetServerInfo ()}</p> <p>}</p> <p>String title = "Display CGI variable";</p> <p>Out.println (servletutilities.headwithtitle (title) </p> <p>"<Body bgcolor = \" # fdf5e6\ "> \n" </p> <p>"<H1 align = center>" Title "</ h1> \n" </p> <p>"<Table border = 1 align = center> \n" </p> <p><Tr bgcolor = \ "# ffad00\"> \N " " <tH> CGI Variable Name <TH> Value ");</p> <p>For (int i = 0; i <variables.length; i ) {</p> <p>String varName = variables [i] [0];</p> <p>String varValue = variables [i] [1];</p> <p>IF (VARVALUE == Null)</p> <p>Varvalue = "<i> NOT Specified </ i>";</p> <p>Out.println ("<TR> <TD>" VarName "<TD>" VARVALUE);</p> <p>}</p> <p>Out.println ("</ Table> </ Body> </ HTML>");</p> <p>}</p> <p>Public void dopost (httpservletRequest Request,</p> <p>Httpservletresponse response</p> <p>Throws servletexception, ioException {</p> <p>DOGET (Request, Response);</p> <p>}</p> <p>}</p> <p>Servlet and JSP Tutorial (7) -HTTP Answer Status</p> <p>Seven, HTTP response status</p> <p>7.1 Status Code Overview</p> <p>When a web server responds to a request for a browser or another client, its response is generally consisting of the following parts: a status line, a few responses, an empty line, content document. Here is the simplest answer:</p> <p>HTTP / 1.1 200 ok</p> <p>Content-Type: Text / Plain</p> <p>Hello World</p> <p>The status line contains a short description information corresponding to the HTTP version, status code, and status code. In most cases, all responses other than Content-Type are optional. However, Content-Type is required, which describes the MIME type of the back document. Although most responses include a document, there are also some do not include, such as responding to the HEAD request never comes with a document. There are many status code actually used to identify a request for failure, which does not contain documents (or only a short error message description).</p> <p>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.</p> <p>7.2 Set status code</p> <p>As mentioned earlier, the HTTP response status line 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.</p> <p>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.</p> <p>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.</p> <p>7.3 HTTP 1.1 status code and its meaning</p> <p>The table below shows the common HTTP 1.1 status code and their corresponding status information and meanings.</p> <p>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</p> <p>100 Continue Initial request has been accepted, the customer should continue to send the rest of the request. (HTTP 1.1 new)</p> <p>101 Switching Protocols Server Converses the request to the customer to another protocol (HTTP 1.1 new)</p> <p>200 ok Everything is normal, the reply document requested for GET and POST is followed behind. If you don't have to set status code, the servlet uses the 202 status code by default.</p> <p>The 201 CREATED server has created a document, and the Location header gives its URL.</p> <p>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).</p> <p>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.</p> <p>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).</p> <p>206 Partial Content The customer sent a GET request with the Range header, which completed it (HTTP 1.1 new).</p> <p>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.</p> <p>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.</p> <p>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:</p> <p>First, the code is more concise.</p> <p>Second, use SendRedirect, servlet automatically construct a page containing new links (for old browsers that cannot be redirected).</p> <p>Finally, SendRedirect can handle relative URLs, automatically convert them into absolute URLs.</p> <p>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.</p> <p>Strictly speaking, we can only assume that the browser will automatically redirect when the original request is Get. See 307.</p> <p>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).</p> <p>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.</p> <p>305 USE Proxy Customer Request documents should be extracted by the proxy server indicated by the Location header (HTTP 1.1 new).</p> <p>307 Temporary Redirect and 302 (Found) are the same. Many browsers are incorrectly responding to the 302 response to redirect, even if the original request is POST, even if it actually only responds to the POST request is 303, it can be redirected. For this reason, HTTP 1.1 has increased by 307 to more clear the regional division of state code: When the 303 response occurs, the browser can follow the redirected GET and POST requests; if it is 307 response, the browser can only follow Redirection to the GET request.</p> <p>Note that there is no corresponding constant for the status code in HTTPSERVLETRESPONSE. (HTTP 1.1 new)</p> <p>400 Bad Request requests a syntax error.</p> <p>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.</p> <p>404 NOT FOUND Unable to find resources for the specified location. This is also a common response, HTTPSERVLETRESPONSE provides the corresponding method: Senderror (Message).</p> <p>405 Method Not ALLOWED Request Method (GET, POST, HEAD, DELETE, PUT, TRAC, etc.) do not apply to the specified resource. (HTTP 1.1 new)</p> <p>406 Not Acceptable The specified resource is already found, but its MIME type and customer are not compatible (HTTP 1.1 new) in the Accpet header.</p> <p>407 Proxy Authentication Required Similar to 401, the customer must first authorize the proxy server. (HTTP 1.1 new)</p> <p>408 Request Timeout In the wait time of the server license, customers have not issued any requests. Customers can repeat the same request later. (HTTP 1.1 new)</p> <p>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)</p> <p>410 Gone requested documents are 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)</p> <p>411 Length Required Server cannot handle requests unless the customer sends a Content-Length header. (HTTP 1.1 new)</p> <p>412 Precondition Failed Request Some prerequisites fails (HTTP 1.1 new).</p> <p>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).</p> <p>414 Request Uri Too Long Uri is too long (HTTP 1.1 new).</p> <p>416 Requested Range Not Satisfiable server does not satisfy the Range header specified in the request. (HTTP 1.1 new)</p> <p>The 500 Internal Server Error server encountered unexpected situations and cannot complete the customer's request.</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.</p> <p>502 BAD GATEWAY Server As a gateway or agent, in order to complete the request to access the next server, the server returns an illegal response.</p> <p>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.</p> <p>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)</p> <p>505 HTTP Version Not Supported Server does not support the HTTP version indicated in the request. (HTTP 1.1 new) 7.4 instance: Access multiple search engines</p> <p>The following example uses two other common status codes other than 200: 302 and 404.302 Set by SendRedirect method, 404 is set by Senderror method.</p> <p>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.</p> <p>Searchengines.java</p> <p>Note: This servlet is to use the SearchSpec class given later, and the features of SearchSpec is to construct the URL that is fit with different search engines.</p> <p>Package Hall;</p> <p>Import java.io. *;</p> <p>Import javax.servlet. *;</p> <p>Import javax.servlet.http. *;</p> <p>Import java.net. *;</p> <p>Public class seat searchengines extends httpservlet {</p> <p>Public void doget (httpservletRequest Request,</p> <p>Httpservletresponse response</p> <p>Throws servletexception, ioException {</p> <p>// getParameter automatically decodes the URL encoded query string. Due to us</p> <p>/ / To send the query string to another, use it again</p> <p>// Urlencoder for URL encoding</p> <p>String searchString =</p> <p>Urlencoder.Encode (Request.GetParameter ("SearchString"));</p> <p>String NumResults =</p> <p>Request.getParameter ("NumResults");</p> <p>String searchengine =</p> <p>Request.getParameter ("Searchengine");</p> <p>SearchSpec [] commonspecs = searchspec.getCommonspecs ();</p> <p>For (int i = 0; i <commitpecs.length; i ) {</p> <p>SearchSpec searchspec = commonspecs [i];</p> <p>IF (SearchSpec.getname (). Equals (Searchengine)) {</p> <p>String URL =</p> <p>Response.EncodeURL (SearchSpec.makeurl (SearchString,</p> <p>NumResults)));</p> <p>Response.sendRedirect (URL);</p> <p>Return;</p> <p>}</p> <p>}</p> <p>Response.senderror (response.sc_not_found,</p> <p>"NO Recognized.");</p> <p>}</p> <p>Public void dopost (httpservletRequest Request,</p> <p>Httpservletresponse response</p> <p>Throws servletexception, ioException {</p> <p>DOGET (Request, Response);</p> <p>}</p> <p>}</p> <p>SearchSpec.java</p> <p>Package Hall;</p> <p>Class searchspec {private string name, baseurl, numResultssuffix</p> <p>Private static searchspec [] commonspecs =</p> <p>{New SearchSpec ("Google",</p> <p>"http://www.google.com/search?q=",</p> <p>"& num ="),</p> <p>New SearchSpec ("Infoseek",</p> <p>"http://infoseek.go.com/titles?qt=",</p> <p>"& nh ="),</p> <p>New SearchSpec ("Lycos",</p> <p>"http://lycospro.lycos.com/cgi-bin/pursuit?query=",</p> <p>"& maxhits ="),</p> <p>New SearchSpec ("Hotbot",</p> <p>"http://www.hotbot.com/?mt=",</p> <p>"& DC =")</p> <p>}</p> <p>Public SearchSpec (String Name,</p> <p>String BaseURL,</p> <p>String NumResultssuffix) {</p> <p>THIS.NAME = Name;</p> <p>this.baseurl = baseurl;</p> <p>THIS.NUMRESULTSSUFFIX = NumResultssuffix;</p> <p>}</p> <p>Public String Makeurl (String SearchString, String NumResults) {</p> <p>Return (BaseURL SearchString NumResultssuffix NumResults);</p> <p>}</p> <p>Public string getname () {</p> <p>Return (Name);</p> <p>}</p> <p>Public static searchspec [] getcommonspecs () {</p> <p>Return (CommonsPecs);</p> <p>}</p> <p>}</p> <p>Searchengines.html</p> <p>Here is the HTML form that calls the above servlet.</p> <p><! Doctype html public "- // w3c // DTD HTML 4.0 Transitional // En"></p> <p><Html></p> <p><HEAD></p> <p><Title> Access Multiple Search Engines </ Title></p> <p></ HEAD></p> <p><Body bgcolor = "# fdf5e6"></p> <p><Form action = "/ servlet / hall.searchengines"></p> <p><Center></p> <p>search for the keyword:</p> <p><Input Type = "text" name = "searchstring"> <br></p> <p>Several query results are displayed per page:</p> <p><Input Type = "text" name = "NumResults"</p> <p>Value = 10 size = 3> <br></p> <p><Input Type = "Radio" Name = "Searchengine"</p> <p>Value = "Google"> Google |</p> <p><Input Type = "Radio" Name = "Searchengine"</p> <p>Value = "Infoseek"></p> <p>Infoseek |</p> <p><Input Type = "Radio" Name = "Searchengine"</p> <p>Value = "Lycos"></p> <p>Lycos |</p> <p><Input Type = "Radio" Name = "Searchengine"</p> <p>Value = "Hotbot"></p> <p>Hotbot</p> <p><br></p> <p><Input Type = "Submit" Value = "Search"></p> <p></ Center></p> <p></ Form></p> <p></ Body></p> <p></ Html></p> <p>Servlet and JSP Tutorial (8)</p> <p>8. Set an HTTP response</p> <p>8.1 HTTP response header outline</p> <p>The WEB server's HTTP response is generally composed of the following: a status line, one or more responses, one blank, content document. Setting the HTTP response head tends to combine the status code in the setting status line. 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.</p> <p>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.</p> <p>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.</p> <p>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.</p> <p>HttpservletResponse also provides a simple way to set up common responses, as follows:</p> <p>SetContentType: Set the Content-Type header. Most servlets use this method.</p> <p>SetContentLength: Sets Content-Length Head. This function is useful for browsers that support persistent HTTP connections.</p> <p>AddCookie: Set a cookie (there is no setcookie method in the Servlet API, because response often contains multiple set-cookie headers).</p> <p>In addition, as described in the previous section, the SendRedirect method sets the local code 302 will also set the location header.</p> <p>8.2 Common responses and their meaning</p> <p>For detailed and complete descriptions of HTTP headers, see http://www.w3.org/protocols/ specification.</p> <p>Response</p> <p>Which request methods (such as GET, POST, etc.) are supported by the Allow server.</p> <p>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 take advantage of your persistent connection, you can write the output document to ByteArrayoutputstram. After you are finished, you will then put this value into the Content-Length header, and finally send content via ByteaRrayStream.writto (Response.getputStream ().</p> <p>Content-Type indicates what MIME type belongs to the document later. The servlet defaults to Text / Plain, but it usually needs to be explicitly designated as Text / HTML. Since CONTENT-TYPE is often set, HTTPSERVLETRESPONSE provides a dedicated method setContentTyep.</p> <p>Date current GMT time. You can use SetDateHeader to set this head to avoid the trouble of conversion time format.</p> <p>When expires should think that the document has expired, no longer cache it?</p> <p>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.</p> <p>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.</p> <p>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").</p> <p>Note that this feature is usually achieved by setting <meta http-equiv = "refresh" content = "5; URL = http:// host / path">, 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.</p> <p>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 <meta http-equiv = "refresh" ...>.</p> <p>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.</p> <p>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.</p> <p>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\ ").</p> <p>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,.</p> <p>8.3 instance: Automatic refresh page when content changes</p> <p>The following servlet 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.</p> <p>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.</p> <p>Primenumbers.java</p> <p>Note that the servlet is to use servletUtilities.java given in the previous. 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 code.)</p> <p>Package Hall;</p> <p>Import java.io. *;</p> <p>Import javax.servlet. *;</p> <p>Import javax.servlet.http. *;</p> <p>Import java.util. *;</p> <p>Public class primenumbers extends httpservlet {</p> <p>Private static vector primelistVector = new vector ();</p> <p>Private static int maxprimelists = 30;</p> <p>Public void doget (httpservletRequest request, httpservletResponse response)</p> <p>Throws servletexception, ioException {</p> <p>INT NUMPRIMES = ServletUTILITIES.GETINTPARAMETER (Request, "Numprimes", 50);</p> <p>Int Numdigits = ServletUtilities.GetintParameter (Request, "Numdigits", 120);</p> <p>Primelist Primelist (PrimelistVector, Numprimes, Numdigits);</p> <p>IF (primelist == null) {</p> <p>Primelist = New Primelist (Numprimes, Numdigits, True);</p> <p>Synchronized (PrimelistVector) {</p> <p>IF (PrimelistVector.Size ()> = maxprimelists)</p> <p>PrimelistVector.removeElementat (0);</p> <p>PrimelistVector.Addelement (Primelist);</p> <p>}</p> <p>}</p> <p>Vector currentprimes = primelist.getprimes ();</p> <p>Int numcurrentprimes = currentprimes.size ();</p> <p>INT NUMPRIMESREMAINING = (Numprimes - NumcurrentPrimes);</p> <p>Boolean islastResult = (NumprimeSremeSremaining == 0);</p> <p>IF (! islastresult) {</p> <p>Response.setHeader ("Refresh", "5");</p> <p>}</p> <p>Response.setContentType (Text / HTML ");</p> <p>PrintWriter out = response.getwriter ();</p> <p>String title = "some" Numdigits "-digit princime number";</p> <p>Out.println (servletutilities.headwithtitle (title) </p> <p>"<Body bgcolor = \" # fdf5e6\ "> \n" </p> <p>"<H2 align = center>" Title "</ h2> \n" </p> <p>"<H3> Primes Found with" Numdigits </p> <p>"or more Digits:" NumcurrentPrimes ". </ h3>");</p> <p>IF (IslastResult)</p> <p>Out.println ("<b> done search. </ b>");</p> <p>Else</p> <p>Out.println ("<B> STILL LOOKING FOR NUMPRIMESREMAING </p> <p>"More <Blink> ... </ BLINK> </ B>"); Out.Println ("<ol>");</p> <p>For (int i = 0; i <number) {i ) {</p> <p>Out.println ("<li>" CurrentPrimes.Elementat (i));</p> <p>}</p> <p>Out.println ("</ ol>");</p> <p>Out.println ("</ Body> </ HTML>");</p> <p>}</p> <p>Public void dopost (httpservletRequest Request,</p> <p>Httpservletresponse response</p> <p>Throws servletexception, ioException {</p> <p>DOGET (Request, Response);</p> <p>}</p> <p>// Check if there is a similar type request (already completed, or being calculated).</p> <p>// If there is, return an existing result instead of the new background thread.</p> <p>Private primelist Findprimelist (Vector PrimelistVector,</p> <p>Int Numprimes,</p> <p>INT NUMDIGITS) {</p> <p>Synchronized (PrimelistVector) {</p> <p>For (int i = 0; i <primelistVector.size (); i ) {</p> <p>Primelist primes = (primelist) PrimelistVector.eMentat (i);</p> <p>IF ((Numprimes == Primes.NUMPRIMES ()) &&</p> <p>(Numdigits == Primes.Numdigits ()))))</p> <p>Return (Primes);</p> <p>}</p> <p>Return (NULL);</p> <p>}</p> <p>}</p> <p>}</p> <p>PrimenumBers.html</p> <p><! Doctype html public "- // w3c // DTD HTML 4.0 Transitional // En"></p> <p><Html></p> <p><HEAD></p> <p><Title> Best Calculation </ Title></p> <p></ HEAD></p> <p><Center></p> <p><Body bgcolor = "# fdf5e6"></p> <p><Form action = "/ servlet / hall.primenumbers></p> <p><B> To calculate several prime numbers: </ b></p> <p><Input Type = "text" name = "numprimes" value = 25 size = 4> <br></p> <p><B> Number of digits per prune: </ b></p> <p><Input Type = "text" name = "numdigits" value = 150 size = 3> <br></p> <p><Input Type = "Submit" Value = "Start Calculation"> </ form></p> <p></ Center></p> <p></ Body></p> <p></ Html></p> <p>Servlet and JSP Tutorial (9)</p> <p>Nine, handling cookie</p> <p>9.1 Overview of Cookies</p> <p>Cookie is a small amount of plain text information sent by the server to the browser. When the user enters the same web server, the browser sends 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.</p> <p>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.</p> <p>9.2 Servlet's cookie API</p> <p>To send cookies to the client, servlet To create one or more cookies (2.1 sections) with the appropriate name and value, set various properties (2.2) through cookie.setxxx, pass Response.addcookie (cookie) Add cookies to your response head (Section 2.3).</p> <p>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.</p> <p>9.2.1 Creating a cookie</p> <p>Call the constructor of the cookie object to 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:</p> <p>[] () =, "/? @:;</p> <p>9.2.2 Reading and setting the cookie properties</p> <p>Before adding cookies, you can view or set up a variety of properties for cookies. These methods are described in the following summary:</p> <p>Getcomment / setcomment</p> <p>Get / set the annotation of cookies.</p> <p>GetDomain / setdomain</p> <p>Get / set the field for cookies. Generally, cookies only returns the same server that is identical to the server name transmitted. Using the method here, you 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, .gra) must contain two points, national domains (such as .com.cn, .edu. UK) must contain three points.</p> <p>GetMaxage / SetMaxage</p> <p>Get / set the time before the cookie expires, in seconds. If this value is not set, the cookie is only valid within the current session, that is, valid before the user closes the browser, and these cookies are not saved on the disk. See below with the instructions on LongliveDCookie. GetName / SetName</p> <p>Get / set the name of the cookie. Essentially, the names and values ​​are two parts we have always cared. Since the GetCookies method of HTTPSERVLETREQUEST returns a Cookie object array, therefore usually uses a loop to access this array to find a specific name, and then check its value with getValue.</p> <p>getPath / setPath</p> <p>Get / set the path to the cookie. If the path is not specified, the cookie will return to all the pages in the current page where the current page is located and its subdirectory. The method here can be used to set some more general conditions. For example, someCookie.SetPath ("/"), at which time all pages on the server can receive the cookie.</p> <p>GetSecure / SetSecure</p> <p>Get / set a boolean value that represents whether cookies can only be sent by encrypted connections (ie, SSL).</p> <p>GetValue / SetValue</p> <p>Get / set the value of the cookie. 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.</p> <p>Getversion / setVersion</p> <p>Get / set the version of the protocol complied with Cookies. The default version 0 (complies with the original Netscape specification); version 1 follows RFC 2109, but has not been widely supported.</p> <p>9.2.3 Set cookies in your response</p> <p>Cookies can join the set-cookie response head with the AddCookie method of HTTPSERVLETRESPONSE. Below is an example:</p> <p>Cookie UserCookie = New Cookie ("User", "UID1234);</p> <p>Response.addcookie (UserCookie);</p> <p>9.2.4 Read Save to Client Cookies</p> <p>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.</p> <p>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.</p> <p>9.3 Several cookie tool functions</p> <p>Here is a few tool functions. Although these functions are simple, it is useful when dealing with cookies.</p> <p>9.3.1 Get the cookie value of the specified name</p> <p>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,</p> <p>String cookiename,</p> <p>String defaultValue) {</p> <p>For (int i = 0; i <cookies.length; i ) {</p> <p>Cookie cookie = cookies [i];</p> <p>IF (cookiename.equals (cookie.getname ())))</p> <p>Return (cookie.getValue ());</p> <p>}</p> <p>Return (DefaultValue);</p> <p>}</p> <p>9.3.2 Automatically saved cookies</p> <p>Below is the code of the LONGLIVEDCOOKIE class. If you want the cookie to save automatically when the browser exits, you can use this LONGLIVEDCOOKIE class to replace standard Cookie classes.</p> <p>Package Hall;</p> <p>Import javax.servlet.http. *;</p> <p>Public class longlivedcookie extends cookie {</p> <p>Public static final int seconds_per_year = 60 * 60 * 24 * 365;</p> <p>Public longlivedcookie (string name, string value) {</p> <p>Super (Name, Value);</p> <p>SetMaxage (Seconds_Per_Year);</p> <p>}</p> <p>}</p> <p>9.4. Example: Customized Search Engine Interface</p> <p>The following 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.</p> <p>Searchenginesfrontend.java</p> <p>This servlet constructs a user interface that is mainly composed of 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.</p> <p>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.</p> <p>Package Hall;</p> <p>Import java.io. *;</p> <p>Import javax.servlet. *;</p> <p>Import javax.servlet.http. *;</p> <p>Import java.net. *;</p> <p>Public class seat searchenginesfrontend extends httpservlet {</p> <p>Public void doget (httpservletRequest Request,</p> <p>HttpservletResponse response) throws servletexception, ioException {</p> <p>Cookie [] cookies = Request.getCookies ();</p> <p>String searchString =</p> <p>ServletUtilities.getCookieValue (cookies,</p> <p>"searchstring",</p> <p>"Java programing");</p> <p>String NumResults =</p> <p>ServletUtilities.getCookieValue (cookies,</p> <p>"NumResults",</p> <p>"10");</p> <p>String searchengine =</p> <p>ServletUtilities.getCookieValue (cookies,</p> <p>"Searchengine",</p> <p>"google");</p> <p>Response.setContentType (Text / HTML ");</p> <p>PrintWriter out = response.getwriter ();</p> <p>String title = "searching the web";</p> <p>Out.println (servletutilities.headwithtitle (title) </p> <p>"<Body bgcolor = \" # fdf5e6\ "> \n" </p> <p>"<H1 align = \" center \ "> Searching the Web </ h1> \n" </p> <p>"\N" </p> <p>"<Form action = \" /Servlet/hall.customizedsearchengines\ "> \n" </p> <p>"<Center> \n" </p> <p>"Search String: \N" </p> <p>"<Input type = \" text\ "name = \" SearchString\ "\n" </p> <p>"Value = \" SearchString "\"> <br> \N " </p> <p>"Results to show per page: \n" </p> <p>"<Input type = \" text\ "name = \" NumResults\ "\n" </p> <p>"Value =" NumResults "size = 3> <br> \N" </p> <p><Input Type = \ "Radio \" Name = \ "Searchengine\" \N " " Value = \ "Google \" " </p> <p>Checked ("Google, Searchengine) "> \N " </p> <p>"Google | \N" </p> <p>"<Input type = \" Radio\ "name = \" Searchengine\ "\n" </p> <p>"Value = \" infoseek\ "" </p> <p>Checked ("Infoseek", Searchengine "> \N" </p> <p>"Infoseek | \n" </p> <p>"<Input type = \" Radio\ "name = \" Searchengine\ "\n" </p> <p>"Value = \" lycos \ "" </p> <p>Checked ("Lycos", Searchengine "> \N" </p> <p>"LYCOS | \ N" </p> <p>"<Input type = \" Radio\ "name = \" Searchengine\ "\n" </p> <p>"Value = \" hotbot \ " </p> <p>Checked ("Hotbot", Searchengine "> \N" </p> <p>Hotbot \ N " </p> <p>"<br> \n" </p> <p><Input Type = \ "Submit \" Value = \ "Search\"> \N " </p> <p>"</ Center> \n" </p> <p>"</ Form> \n" </p> <p>"\N" </p> <p>"</ Body> \n" </p> <p>"</ Html> \n");</p> <p>}</p> <p>Private string checked (String name1, string name2) {</p> <p>IF (Name1.Equals (name2))</p> <p>Return ("Checked");</p> <p>Else</p> <p>Return ("");</p> <p>}</p> <p>Customizedsearchengines.java</p> <p>The front searchenginesfrontend servlet sends the data to the CustomizedSearchengines Servlet. In this case, in many ways, the example is similar to the example of the HTTP status code, distinguishably, in addition to constructing a URL for the search engine and sends a redirect response to the user, it is necessary to send a cookies that saves user data.</p> <p>Package Hall;</p> <p>Import java.io. *;</p> <p>Import javax.servlet. *;</p> <p>Import javax.servlet.http. *;</p> <p>Import java.net. *;</p> <p>Public class customizedsearchengines extends httpservlet {</p> <p>Public void doget (httpservletRequest Request,</p> <p>Httpservletresponse response</p> <p>Throws servletexception, ioException {</p> <p>String searchString = Request.getParameter ("SearchString");</p> <p>Cookie searchStringCookie =</p> <p>New LonglivedCookie ("SearchString", SearchString;</p> <p>Response.addcookie (SearchStringCookie);</p> <p>SearchString = Urlencoder.Encode (SearchString);</p> <p>String NumResults = Request.GetParameter ("NumResults");</p> <p>Cookie NumResultscookie =</p> <p>New LonglivedCookie ("NumResults", NumResults;</p> <p>Response.addcookie (NumResultscookie);</p> <p>String searchengine = request.getParameter ("Searchengine");</p> <p>Cookie SearchengineCookie =</p> <p>New LonglivedCookie ("Searchengine", Searchengine;</p> <p>Response.addcookie (SearchengneCookie);</p> <p>SearchSpec [] commonspecs = searchspec.getCommonspecs ();</p> <p>For (int i = 0; i <commitpecs.length; i ) {</p> <p>SearchSpec searchspec = commonspecs [i];</p> <p>IF (SearchSpec.getname (). Equals (Searchengine)) {</p> <p>String URL =</p> <p>SearchSpec.makeurl (SearchString, NumResults);</p> <p>Response.sendRedirect (URL);</p> <p>Return;</p> <p>}</p> <p>}</p> <p>Response.senderror (response.sc_not_found,</p> <p>"NO Recognized.");</p> <p>}</p> <p>Public void dopost (httpservletRequest Request,</p> <p>Httpservletresponse response</p> <p>Throws servletexception, ioException {</p> <p>DOGET (Request, Response);</p> <p>}</p> <p>Servlet and JSP Tutorial (10) - Session Status</p> <p>Ten, session state</p> <p>10.1 Conversational Status Overview</p> <p>The "Stateless" feature of the HTTP protocol has brought a series of issues. 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?</p> <p>This issue generally has three solutions:</p> <p>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 cookie interface, there are still some cumbersome details that require processing:</p> <p>Save the session identifier from other cookies.</p> <p>Set a suitable invalidation time for cookies (for example, a session that interrupts more than 24 hours should be resended).</p> <p>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.)</p> <p>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.</p> <p>Hidden form fields. The HTML form can contain the following input domain: <input type = "hidden" name = "session" value = "...". This means that when the form is submitted, the names and data of the hidden domain are also included in GET or POST data, we can take advantage of this mechanism to maintain session information. However, this method has a big shortcoming that all pages are dynamically generated, because the core of the entire problem is that every session must have a unique identifier.</p> <p>Servlet provides us with a different solution: httpsession API. The HTTPSession API is a high-level session status tracking interface based on cookie or URL overwriting mechanism: if the browser supports cookie, use cookies; if the browser does not support the cookie or the cookie function is shut down, the URL rewriting method is automatically used. Servlet developers do not need to care about the details, and do not need to process cookies or attach information behind the URL, the API automatically provides a place where servlet developers can easily store session information.</p> <p>10.2 Session Status Tracking API</p> <p>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, check with a session related information, save information in the session object, And release the session object when the session is completed or aborted. 10.2.1 Viewing the currently requested session object</p> <p>View the currently requested session object implementation 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:</p> <p>HttpSession session = request.getations (TRUE);</p> <p>10.2.2 Viewing information about and sessions</p> <p>The HTTPSession object is generated on the server, automatically associates the requested sender via the cookie or URL. 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.</p> <p>API version 2.2 is recommended getAttribute instead of 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.</p> <p>However, because there is only a few commercial servlet engines support 2.2, we still use GetValue in the examples. This is a typical example. It is assumed that ShoppingCart is a class saved in the purchase of product information:</p> <p>HttpSession session = request.getations (TRUE);</p> <p>ShoppingCart PreviousItems =</p> <p>SHOPPINGCART) Session.getValue ("Previoustems");</p> <p>IF (Previoustems! = NULL) {</p> <p>DOSMETHINGWITH (PreviouS);</p> <p>} else {</p> <p>PreviousItems = new shoppingcart (...);</p> <p>DOSMELSEWITH (PreviouS);</p> <p>}</p> <p>Most of us are looking for values ​​associated with it based on a particular name, but you can also call GetValueNames to get the name of all properties. 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.</p> <p>Although developers are often the data saved to session objects, there are still other information.</p> <p>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.</p> <p>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.</p> <p>GetLastAccesseedTime: This method returns to the customer's last time the request is measured in milliseconds, from 1970.01.01 (gmt).</p> <p>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.</p> <p>10.2.3 Save data in the session object</p> <p>As mentioned above, reading the information stored in the session is used to use the getValue method (or, for the 2.2 version of the servlet specification, using getaTribute). 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 sample code is as follows:</p> <p>HttpSession session = request.getations (TRUE);</p> <p>Session.putValue ("ReferringPage", Request.getHeader ("Referer");</p> <p>ShoppingCart PreviousItems =</p> <p>SHOPPINGCART) Session.getValue ("Previoustems");</p> <p>IF (previousItems == null) {</p> <p>PreviousItems = new shoppingcart (...);</p> <p>}</p> <p>String itemid = Request.getParameter ("itemid");</p> <p>PreviousItems.AddenTry (catalog.geeTEntry (itemid));</p> <p>Session.putValue ("PreviousItems", PreviouSItems);</p> <p>10.3 Example: Display Session Information</p> <p>The following example generates a web page and displays information about the current session in this page.</p> <p>Package Hall;</p> <p>Import java.io. *;</p> <p>Import javax.servlet. *;</p> <p>Import javax.servlet.http. *;</p> <p>Import java.net. *;</p> <p>Import java.util. *;</p> <p>Public class showsession extends httpservlet {</p> <p>Public void doget (httpservletRequest Request,</p> <p>Httpservletresponse response</p> <p>Throws servletexception, ioException {</p> <p>HttpSession session = request.getations (TRUE);</p> <p>Response.setContentType ("text / html"); printwriter out = response.getwriter ();</p> <p>String title = "searching the web";</p> <p>String heading;</p> <p>Integer AccessCount = new integer (0) ;;</p> <p>IF (session.isnew ()) {</p> <p>Heading = "Welcome, Newcomer";</p> <p>} else {</p> <p>Heading = "Welcome Back";</p> <p>Integer OldaccessCount =</p> <p>// Use GetAttribute in Servlet API 2.2 instead of getValue</p> <p>(Integer) Session.getValue ("AccessCount");</p> <p>IF (OldaccessCount! = NULL) {</p> <p>AccessCount =</p> <p>NEW integer (OldaccessCount.intValue () 1);</p> <p>}</p> <p>}</p> <p>// Using Putattribute in Servlet API 2.2</p> <p>Session.putValue ("AccessCount", AccessCount;</p> <p>Out.println (servletutilities.headwithtitle (title) </p> <p>"<Body bgcolor = \" # fdf5e6\ "> \n" </p> <p><H1 align = \ "center \"> heading "</ h1> \n" </p> <p><H2> Information on Your session: </ h2> \n " </p> <p>"<Table border = 1 align = center> \n" </p> <p>"<Tr bgcolor = \" # ffad00\ "> \n" </p> <p>"<TH> Info Type <TH> Value \ N" </p> <p><Tr> \n " </p> <p>"<TD> iD\N" </p> <p>"<TD>" session.getid () "\n" </p> <p><Tr> \n " </p> <p>"<TD> CREATION TIME \ N" </p> <p>"<TD>" New Date (session.getcreationTime ()) "\n" </p> <p><Tr> \n " </p> <p>"<TD> TIME OF LAST Access \" "<TD>" New Date (session.getlastaccessedTime ()) "\N" </p> <p><Tr> \n " </p> <p>"<TD> Number of Previous Accesses\ N" </p> <p>"<TD>" AccessCount "\N" </p> <p>"</ Table> \n" </p> <p>"</ Body> </ html>");</p> <p>}</p> <p>Public void dopost (httpservletRequest Request,</p> <p>Httpservletresponse response</p> <p>Throws servletexception, ioException {</p> <p>DOGET (Request, Response);</p> <p>}</p> <p>}</p> <p>Servlet and JSP Tutorial (11) -JSP and Syntax Summary</p> <p>Eleven, JSP and syntax summary</p> <p>11.1 Overview</p> <p>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".</p> <p>Thanks for Ordering</p> <p><I> <% = Request.getParameter ("Title")%> </ i></p> <p>JSP page files are usually in .jsp extension, and can be installed to any places where ordinary web pages can be stored. 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.</p> <p>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.</p> <p>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.</p> <p>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.</p> <p>11.2 JSP Syntax Summary Table JSP Element Syntax Description Remarks</p> <p>JSP expression <% = expression%> Calculates the expression and outputs the result. Equivalent XML expression is:</p> <p><JSP: Expression></p> <p>EXPRESSION</p> <p></ Jsp: expression></p> <p>The predefined variables that can be used include: Request, Response, Out, Session, Application, Config, PageContext. These predefined variables can also be used in the JSP scriptlet.</p> <p>JSP Scriptlet <% Code%> Insert the code of the service method. Equivalent XML expression is:</p> <p><JSP: Scriptlet></p> <p>code</p> <p></ Jsp: Scriptlet></p> <p>JSP declarations <%! Code%> The code is inserted into the servlet class (outside the service method). Equivalent XML expression is:</p> <p><JSP: Declaration></p> <p>code</p> <p></ Jsp: Declaration></p> <p>Page Instruction <% @ page att = "val"%> Global instructions for the Servlet engine. Equivalent XML expression is</p> <p><JSP: Directive.Page Att = "VAL" \>.</p> <p>The legal properties are as follows, with bold representing the default value:</p> <p>Import = "package.class"</p> <p>ContentType = "Mime-Type"</p> <p>Isthreadsafe = "True | FALSE"</p> <p>session = "True | FALSE"</p> <p>Buffer = "Size KB | NONE"</p> <p>Autoflush = "True | FALSE"</p> <p>Extends = "package.class"</p> <p>INFO = "Message"</p> <p>ErrorPage = "URL"</p> <p>iSerrorPage = "True | FALSE"</p> <p>Language = "java"</p> <p>Include Directive <% @ include file = "URL"%> When the JSP is converted to servlet, the specified file on the local system should be included. Equivalent XML expression is: <JSP: Directive.Include</p> <p>FILE = "URL" \>.</p> <p>The URL must be relative URL.</p> <p>Using JSP: Include Actions You can introduce files when requested (instead of JSP to servlet).</p> <p>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 ->.</p> <p>JSP: Include Action <JSP: Include</p> <p>Page = "Relative URL"</p> <p>FLUSH = "true" /> 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.</p> <p>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).</p> <p>JSP: Usebean action <jsp: usebean att = val * /> or</p> <p><Jsp: usebean att = val *></p> <p>...</p> <p></ Jsp: usebean> Find or instantiate a Java Bean. Possible properties include:</p> <p>ID = "name"</p> <p>Scope = "Page | Request</p> <p>Sense | Application "</p> <p>Class = "package.class"</p> <p>TYPE = "package.class"</p> <p>Beanname = "package.class"</p> <p>JSP: setProperty action <jsp: setProperty att = val * /> Settings the properties of the bean. You can set a determined value or specify the attribute value from the request parameters. Legal properties include:</p> <p>Name = "beanname"</p> <p>Property = "PropertyName | *"</p> <p>Param = "parametername"</p> <p>Value = "VAL"</p> <p>JSP: getProperty action <jsp: getproperty</p> <p>Name = "PropertyName"</p> <p>Value = "VAL" /> extracts and outputs the properties of the bean.</p> <p>JSP: Forward Action <JSP: Forward</p> <p>Page = "relative URL" /> Go to another page.</p> <p>JSP: Plugin action <JSP: Plugin</p> <p>Attribute = "value" *></p> <p>...</p> <p></ Jsp: plugin> Generates Object or Embed tags based on the browser type to run the Java Applet through Java Plugin.</p> <p>11.3 About Template Text (Static HTML)</p> <p>Many times, a large part of the JSP page is composed of static HTML, which is also known as "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.</p> <p>Servlet with JSP Tutorial (12) - Script elements, instructions, and predefined variables</p> <p>twelve,</p> <p>12.1 JSP script elements</p> <p>The JSP script element is used to insert Java code, which will appear in the servlet generated by the current JSP page. Script elements have three formats:</p> <p>Expression format <% = expression%>: Calculate expressions and output its results.</p> <p>Scriptlet format <% Code%>: Insert the code into the service method of the servlet.</p> <p>Declaration format <%! Code%>: Add the declaration to the servlet class (outside of any method).</p> <p>Let's explain their usage in detail.</p> <p>12.1.1 JSP Expression</p> <p>JSP expressions are used to insert Java data directly into the output. The syntax is as follows:</p> <p><% = Java expression%></p> <p>The result obtained by calculating the Java expression is converted into a string and then inserted into the page. Calculates when running (when the page is requested), all information related to the request can be accessed. For example, the following code shows the date / time of the page being requested:</p> <p>Current Time: <% = new java.util.date ()%></p> <p>To simplify these expressions, JSP predefines a set of object variables that can be used directly. Later, we will detail these implied statements, but for JSP expressions, the most important objects and their types are as follows:</p> <p>REQUEST: httpservletRequest;</p> <p>Response: httpservletresponse;</p> <p>Session: HttpSession associated with Request</p> <p>OUT: PrintWriter (with buffered version, jspwriter), used to send the output to the client</p> <p>Below is an example:</p> <p>Your hostname: <% = request.getremotehost ()%></p> <p>Finally, if XML is used, the JSP expression can also be written as follows:</p> <p><JSP: Expression></p> <p>Java Expression</p> <p></ Jsp: expression></p> <p>Remember that XML elements are different from HTML. XML is sensitive, so it is sure to use lowercase. For instructions on XML syntax, see "XML Tutorial"</p> <p>12.1.2 JSP Scriptletlet</p> <p>If the task you want to complete is more complicated than inserting a simple expression, you can use JSP Scriptlet. JSP Scriptlet allows you to insert any Java code into the servlet. The JSP Scriptlet syntax is as follows:</p> <p><% Java code%></p> <p>As with JSP expressions, Scriptlet can also access all predefined variables. For example, if you want to output content to the result page, you can use the OUT variable:</p> <p><%</p> <p>String querydata = request.getQueryString (); out.println ("attached get data: querydata);</p> <p>%></p> <p>Note that the code in the scriptlet will be moved to the servlet, while the Scriptlehead front and the static HTML (template text) will be converted to a PrintLn statement. This means that the Java statement in the scriptlet is not a complete, no closing block will affect the static HTML outside the Scriptlet. For example, the following JSP fragment mixes template text and scriptlet:</p> <p><% IF (Math.random () <0.5) {%></p> <p>Have a <b> nice </ b> day!</p> <p><%} Else {%></p> <p>Have a <b> lousy </ b> day!</p> <p><%}%></p> <p>The above JSP code will be converted into the following servlet code:</p> <p>IF (Math.random () <0.5) {</p> <p>Out.println ("Have a <b> nice </ b> day!");</p> <p>} else {</p> <p>Out.println ("Have a <b> lousy </ b> day!");</p> <p>}</p> <p>If you want to use characters "%>" inside the Scriptlet, you must write "% \>". Also, please note that <% code%> XML equation is:</p> <p><JSP: Scriptlet></p> <p>Code</p> <p></ Jsp: Scriptlet></p> <p>12.1.3 JSP declaration</p> <p>The JSP declaration is used to define methods and member variables inserted into the servlet class. The syntax is as follows:</p> <p><%! Java code%></p> <p>Since the declaration does not have any output, they tend to be used with JSP expressions or scriptlets. For example, the following JSP code snippet outputs the number of times the current page is requested since the server starts (or the servlet class is changed and reloaded):</p> <p><%! Private int accesscount = 0;%></p> <p>Since the server startup, the number of page access is:</p> <p><% = accesscount%></p> <p>Like Scriptlet, if you want to use strings "%>", you must use "% \>" instead. Finally, <%! Code%> XML equation is:</p> <p><JSP: Declaration></p> <p>Code</p> <p></ Jsp: Declaration></p> <p>12.2 JSP Directive</p> <p>The JSP instruction affects the overall structure of the servlet class, and its syntax is generally as follows:</p> <p><% @ Directive Attribute = "Value"%></p> <p>Alternatively, multiple properties of the same instruction can be combined, for example:</p> <p><% @ Directive Attribute1 = "Value1" Attribute2 = "Value2"</p> <p>...</p> <p>Attributen = "Valuen"%></p> <p>The JSP instruction is divided into two types: The first is the Page instruction to complete the following tasks: Import the specified class, custom servlet's superclass, etc .; the second is the Include command to convert in JSP file Other files are introduced when servlet. The JSP specification also mentioned the Taglib directive, its purpose is to let JSP developers can define their own tags, but JSP 1.0 does not support this instruction, and it is hoped that it will become one of the main improvements of JSP 1.1.</p> <p>12.2.1 Page Directive</p> <p>The role of the Page instruction is to define one or more attributes below, which are sensitive.</p> <p>Import = "package.class", or import = "package.class1, ..., package.classn":</p> <p>What packages are used to specify import, for example: <% @ page import = "java.util. *"%>. Import is the only attribute that allows you to appear.</p> <p>Contenttype = "mime-type" or contenttype = "mime-type; charset = character-set":</p> <p>This property specifies the output MIME type. The default is Text / HTML. For example, the following instructions:</p> <p><% @ Page contenttype = "text / plain"%>.</p> <p>The same is the same as the Scriptlet effect:</p> <p><% Response.setContentType ("text / plain");%></p> <p>Isthreadsafe = "True | FALSE"</p> <p>The default value indicates that the servlet is handled in a standard manner, that is, if the developer has synchronized access to the instance variable, handle multiple requests simultaneously by a single servlet instance. If the value FALSE is valued, it indicates that the servlet should implement SingLethReadModel, request, or an entry one by one, or multiple parallel requests are processed by different servlet instances.</p> <p>session = "True | FALSE"</p> <p>Default TRUE indicates that predefined variable session should be bound to existing sessions. If there is no existing session, create new and bound Session variables. If the value False indicates that the session will not be used, trying to access the variable session will cause the JSP to convert to servlet.</p> <p>Buffer = "Size KB | NONE"</p> <p>This property specifies the cache size of JSPWRITE OUT. The default value is related to the server, but at least 8 kb should be 8 KB.</p> <p>Autoflush = "True | FALSE"</p> <p>Default True indicates that it is refreshed if the cache is full. Autoflush rarely takes a false value, and the false value indicates that the exception is thrown if the cache is full. If buffer = "none", AutoFlush does not take a false value.</p> <p>Extends = "package.class"</p> <p>This attribute indicates which superclass uses the servlet to be generated. Use this property should be very careful because the server may already be used in a custom super class. INFO = "Message"</p> <p>This attribute defines a string that can be extracted through the GetServletInfo method.</p> <p>ErrorPage = "URL"</p> <p>This property specifies a JSP page, all unusuals that are not captured by the current page are processed by the page.</p> <p>iSerrorPage = "True | FALSE"</p> <p>This attribute indicates whether the current page can be used as an error handling page for another JSP page. The default value FALSE.</p> <p>Language = "java"</p> <p>This property is used to indicate the language used. There is no need to pay attention to this property because the default Java is the currently available language.</p> <p>The XML syntax of the definition instruction is:</p> <p><Jsp: Directive.directiveType Attribute = Value /></p> <p>For example, the following instructions:</p> <p><% @ Page Import = "java.util. *"%></p> <p>Its XML equation is:</p> <p><Jsp: Directive.page Import = "java.util. *" /></p> <p>12.2.2 Include Directive</p> <p>The include instruction is used to introduce other files when the JSP page is converted to servlet. The instruction syntax is as follows:</p> <p><% @ Include file = "relative URL"%></p> <p>The URL specified here is the URL relative to the JSP page that issues the reference instruction. However, like the relative URL in the usual sense, you can use the URL starting with "/" to tell the system to treat the URL as starting from the root of the Web server. . The content containing the file is also a JSP code, that is, the included file can contain static HTML, scripting elements, JSP instructions, and actions.</p> <p>For example, each page of many websites has a small navigation bar. Because there are many problems in the HTML framework, navigation bars often produce with a table top or on the left, and the same HTML code repeatedly appears on each page of the entire website. The include directive is an ideal way to implement this feature. Using the include directive, developers don't have to copy navigation HTML code into each file, so that maintaining maintains more easily.</p> <p>Since the include instruction is introduced when the JSP is converted to servlet, if the navigation bar changes, all JSP pages that use the navigation bar must be re-converted into servlet. If the navigation strip changes are not frequent, and you want to include the operation with as good efficiency, using the include directive is the best choice. However, if the navigation strip changes very frequent, you can use the JSP: Include action. JSP: Include Action The specified file will be referenced when the JSP page request appears, refer to the specific instructions later in this article.</p> <p>12.3 Example: Application of Script Elements and Instructions</p> <p>Below is a simple example of using JSP expressions, scripTlets, declarations, and instructions.</p> <p><! Doctype html public "- // w3c // DTD HTML 4.0 Transitional // En"></p> <p><Html></p> <p><HEAD></p> <p><Title> javaServer Pages </ Title></p> <p></ HEAD></p> <p><Body bgcolor = "# fdf5e6" text = "# 000000" link = "# 000EE" VLINK = "# 551a8b" alink = "# ff0000"></p> <p><Center></p> <p><Table Border = 5 BGColor = "# EF8429"></p> <p><TR> <TH Class = "Title"></p> <p>JSP application example </ table></p> <p></ Center></p> <p><P></p> <p>Here are some dynamic content generated by various JSP functions:</p> <p><Ul></p> <p><Li> <b> expressions. </ B> <br></p> <p>Your host name: <% = request.getRemoteHost ()%>.</p> <p><Li> <b> JSP scripTlet. </ B> <br></p> <p><% Out.println ("query string:" </p> <p>Request.getQueryString ());%></p> <p><Li> <b> declaration (and expression). </ B> <br></p> <p><%! Private int accesscount = 0;%></p> <p>Since the server starts: <% = accesscount%></p> <p><Li> <b> instructions (and expressions). </ B> <br></p> <p><% @ Page Import = "java.util. *"%></p> <p>Current date: <% = new Date ()%></p> <p></ Ul></p> <p></ Body></p> <p></ Html></p> <p>12.4 JSP predefined variable</p> <p>To simplify the JSP expression and the Scriptlet code, JSP provides eight predefined variables (or implied objects). These variables are Request, Response, Out, Session, Application, Config, PageContext, and Page.</p> <p>12.4.1 Request</p> <p>This is the HTTPSERVLETREQUEST that requests associated, through it can view request parameters (call getParameter), request type (GET, POST, HEAD, etc.), as well as the requested HTTP header (cookie, referer, etc.). Strictly speaking, if the request is used by other protocols other than HTTP, the request can be a subscar class of ServletRequest (not httpservletRequest), but it is hardly used in practice.</p> <p>12.4.2 Response</p> <p>This is the HttpServletResponse associated with answers. Note that due to the output stream (see the OUT below) is buffered, the output content has been sent to the client, and the normal servlet does not allow the HTTP status code, but it is legal in JSP. 12.4.3 OUT</p> <p>This is a PrintWriter used to send content to the client. However, in order to make the Response object more practical, OUT is PrintWriter with cache function, ie jspwriter. JSP allows the cache to be adjusted by the buffer attribute of the PAGE instruction, or even shut down the cache.</p> <p>OUT is generally only used within the scriptlet because the JSP expression is automatically sent to the output stream, rarely needs to reference the OUT.</p> <p>12.4.4 Session</p> <p>This is the HTTPSession object that is associated with the request. We have already introduced the automatic creation of the session, and we know, this object is also automatically bound. Even if there is no session reference. But there is an exception, this is if you use the session property of the PAGE instruction to turn the session, at which point the reference to the session variable will cause the JSP page to convert to servlet.</p> <p>12.4.5 APPLICATION</p> <p>This is a servletContext, or it can be obtained via GetServletConfig (). GetContext ().</p> <p>12.4.6 Config</p> <p>This is the servletconfig object of the current page.</p> <p>12.4.7 PageContext</p> <p>Mainly used to manage the properties of the page.</p> <p>12.4.8 Page</p> <p>It is the synonym of this, which is not currently used. It is placeholder for Java is no longer a unique JSP programming language.</p> <p>Servlet and JSP Tutorial (13) -JSP Action</p> <p>Thirteen, JSP action</p> <p>JSP Actions use the XML syntax format tag to control the behavior of the Servlet Engine. Using JSP actions can be dynamically inserted into files, reuse the JavaBean components, redirect the user to another page, generate HTML code for the Java plugin.</p> <p>JSP actions include:</p> <p>JSP: incrude: Introduces a file when the page is requested.</p> <p>JSP: Usebean: Find or instantiate a JavaBean.</p> <p>JSP: setProperty: Sets the properties of JavaBean.</p> <p>JSP: getProperty: Outputs the properties of a JavaBean.</p> <p>JSP: Forward: Turn the request to a new page.</p> <p>JSP: Plugin: Generate Object or Embed tags based on the browser type.</p> <p>13.1 JSP: INCLUDE Action</p> <p>This action inserts the specified file into the page being generated. The syntax is as follows:</p> <p><Jsp: include page = "relative url" flush = "true" /></p> <p>The include instruction has been introduced before, which is introduced when the JSP file is converted to servlet, and the JSP: Include action here is different, and the time inserted into the file is when the page is requested. JSP: The file introduction time of the incrude action determines its efficiency to be slightly worse, and the reference file cannot contain some JSP code (for example, the HTTP header can not be set), but its flexibility is much better.</p> <p>For example, the following JSP page plugs 4 news summary into a "what`s new?" Page. When you change the news summary, you only need to change these four files, but the primary JSP page can not be modified:</p> <p>Whatsnew.jsp</p> <p><! Doctype html public "- // w3c // DTD HTML 4.0 Transitional // En"></p> <p><Html> <head></p> <p><Title> what`s new </ title></p> <p></ HEAD></p> <p><Body bgcolor = "# fdf5e6" text = "# 000000" link = "# 000EE"</p> <p>VLINK = "# 551a8b" alink = "# ff0000"></p> <p><Center></p> <p><Table Border = 5 BGColor = "# EF8429"></p> <p><TR> <TH Class = "Title"></p> <p>What`s new at jspnews.com </ table></p> <p></ Center></p> <p><P></p> <p>Here Is A Summary of Our Four Most News Stories:</p> <p><O></p> <p><Li> <jsp: include page = "news / item1.html" Flush = "true" /></p> <p><Li> <jsp: include page = "news / item2.html" Flush = "true" /></p> <p><Li> <jsp: include page = "news / item3.html" Flush = "true" /></p> <p><Li> <jsp: include page = "news / item4.html" flush = "true" /></p> <p></ Ol></p> <p></ Body></p> <p></ Html></p> <p>13.2 JSP: Usebean Action</p> <p>JSP: UseBean action is used to load a JavaBean that will be used in the JSP page. This feature is very useful because it allows us to play both the Java component reuse, and avoid the loss of JSP distinguish between servlets. JSP: The easiest syntax of usebean action is:</p> <p><Jsp: usebean id = "name" class = "package.class" /></p> <p>The meaning of this line code is: "Create an instance of the class specified by the class property, then bind it to its name by the ID attribute given." However, just as you will see, define a scope property allows the bean to associate more pages. At this point, JSP: UseBean action only creates a new object instance without the same ID and Scope, and it is necessary to get a reference to the existing bean.</p> <p>After getting a bean instance, the attribute to modify the bean can be performed by JSP: SetProperty action, or the object variable named ID attribute can be used in the Scriptlet, and the properties are explicitly modified by calling the object. This makes us remember that when we say "a bean has a type X" foo ", it means" this class has a getfoo method with a return value type X, and there is a setfoo method to X-type value Parametric ". Details of the JSP: SetProperty action are discussed later. But now you must know, we can provide one value directly through the value attribute of JSP: setProperty action, or by declare the property value from the specified request parameter through the PARAM property, you can also list the BEAN property indicating that it should be The same name variable from the request parameter.</p> <p>Reading the bean property in the JSP expression or Scriptlet is implemented by calling the corresponding getxxx method, or more generally, using the JSP: getProperty action.</p> <p>Note that class files containing beans should be placed in the server formally stored in the Directory of the Java class, rather than retaining the directory of the class that can be loaded automatically after the modification. For example, for Java Web Server, the classes used by Beans and all beans should be placed in the classs directory, or when the package into the JAR file, put the lib directory, but should not put it under servlets.</p> <p>Here is a very simple example, its function is to load a bean, then set / read its Message property.</p> <p>Beantest.jsp</p> <p><! Doctype html public "- // w3c // DTD HTML 4.0 Transitional // En"></p> <p><Html></p> <p><HEAD></p> <p><Title> Reusing JavaBeans in JSP </ Title></p> <p></ HEAD></p> <p><Body></p> <p><Center></p> <p><Table border = 5></p> <p><TR> <TH Class = "Title"></p> <p>Reusing JavaBeans in JSP </ Table></p> <p></ Center></p> <p><P></p> <p><Jsp: usebean id = "test" class = "Hall.SIMPLEBean" /></p> <p><JSP: setProperty Name = "Test"</p> <p>Property = "Message"</p> <p>Value = "Hello WWW" /></p> <p><H1> Message: <i></p> <p><Jsp: getproperty name = "test" property = "message" /></p> <p></ I> </ h1></p> <p></ Body></p> <p></ Html></p> <p>SimpleBean.java</p> <p>The Beantest page used a SimpleBean. SimpleBean's code is as follows:</p> <p>Package Hall;</p> <p>Public class SimpleBean {</p> <p>Private string message = "no message specified"; public string getMessage () {</p> <p>Return (Message);</p> <p>}</p> <p>Public void setmessage (string message) {</p> <p>THIS.MESSAGE = Message;</p> <p>}</p> <p>}</p> <p>13.3 Further stations about JSP: Usebean</p> <p>The easiest way to use Bean is to load beans with the following code:</p> <p><Jsp: usebean id = "name" class = "package.class" /></p> <p>Then via JSP: SetProperty and JSP: getProperty modifies and extracts the properties of the bean. However, there must be two points. First, we can also instantiate beans with the following format:</p> <p><JSP: usebean ...></p> <p>Body</p> <p></ Jsp: usebean></p> <p>It means that only the Body section is only performed when the first instantiation bean is performed, and if it is used to use the existing bean instance, the Body section is not executed. As will be introduced below, JSP: UseBean does not always mean create a new bean instance.</p> <p>Second, in addition to ID and CLASS, JSP: USEBean has three other properties, namely: scope, type, beanname. The following table briefly explains the usage of these attributes. Attribute usage</p> <p>ID Named Reference The bean variable. If you can find the identical bean instance of ID and Scope, JSP: UseBean action will use an existing bean instance instead of creating a new instance.</p> <p>Class Specifies the full package name of the bean.</p> <p>Scope Specifies which of which is available in the context, one of the four values ​​below: Page, Request, Session, and Application.</p> <p>The default value is Page, indicating that the bean is only available within the current page (saved within the current page).</p> <p>Request means that the bean is valid within the current customer request (saved within the servletRequest object).</p> <p>Session indicates that the bean is valid for all pages in the current HTTPSession.</p> <p>Finally, if application is valued, the bean is valid for all pages with the same servletContext.</p> <p>Scope is important because JSP: UseBean instantizes new objects only when there is no object with the same ID and Scope; if the ID and Scope are the same object, use existing objects directly, this Anything between the JSP: USEBean starts tag and end tags will be ignored.</p> <p>TYPE specifies the type of variable that references the object, it must be the name of the bean class, a super class name, one of the interface names implemented by this class. Remember that the name of the variable is specified by the id attribute.</p> <p>BeanName Specifies the name of the bean. If the Type property and the beanName property are provided, the Class property is allowed to omit.</p> <p>13.4 JSP: SETPROPERTY Action</p> <p>JSP: setProperty is used to set the properties of the instantiated Bean object, there are two usage. First, you can use JSP: setProperty outside the JSP: UseBean element, as shown below:</p> <p><Jsp: usebean id = "myname" ... /></p> <p>...</p> <p><Jsp: setproperty name = "myname"</p> <p>Property = "SomeProperty" ... /> This time, regardless of the existing bean, it is a new BEAN instance, and JSP: setProperty will execute. The second usage is to put JSP: setProperty into the JSP: UseBean element, as shown below:</p> <p><JSP: Usebean ID = "MyName" ...></p> <p>...</p> <p><Jsp: setproperty name = "myname"</p> <p>Property = "SomeProperty" ... /></p> <p></ Jsp: usebean></p> <p>At this point, JSP: SetProperty will only be executed when a new Bean instance is used, and JSP: setProperty is not executed if you use an existing instance.</p> <p>JSP: SetProperty action has the following four properties: Property Description</p> <p>The name name attribute is required. It means which bean is to set the property.</p> <p>The Property property is required. It indicates which property to set. There is a special usage: if the value of the Property is "*", the request parameters that match all the names and bean property names will be passed to the corresponding attribute set method.</p> <p>The Value Value property is optional. This property is used to specify the value of the bean property. String data automatically converts into numbers through standard Valueof methods in the target class, Boolean, Boolean, Byte, Byte, Char, Character. For example, the property value of the Boolean and Boolean types (such as "True") converted through the attribute value of the Boolean.ValueOf conversion, the INT, and Integer types (such as "42") via Integer.Valueof.</p> <p>Value and Param cannot be used at the same time, but can be used any one.</p> <p>Param Param is optional. It specifies which request parameter as the value of the bean property. If there is no parameters of the current request, what is not done, the system does not pass NULL to the set method of the bean property. Therefore, you can let the bean provide the default attribute value, and only modify the default attribute value when the request parameter is clearly specified.</p> <p>For example, the following code segment indicates that if there is a NumItems request parameter, set the value of the NumberOfItems property to the value of the request parameter NumItems; otherwise, nothing.</p> <p><Jsp: setproperty name = "Orderbean"</p> <p>Property = "NumberofItems"</p> <p>PARAM = "NumItems" /></p> <p>If Value and PARAM are omitted, its effect is equivalent to providing a param and its value is equal to the value of Property. Further, this kind of thought of automatic assignment of automatic assignment by using the request parameter and attribute name, you can also specify "*" in the Property (name of the bean property), then omit value and param. At this point, the server will view all bean properties and request parameters, if the names are the same, automatically assign.</p> <p>Below is an example of using JavaBean calculations. If there is a Numdigits parameter in the request, the value is passed to the Numdigits property of the bean; Numprimes is similar.</p> <p>JSPprimes.jsp</p> <p><! Doctype html public "- // w3c // DTD HTML 4.0 Transitional // En"> <html></p> <p><HEAD></p> <p><Title> Using JavaBean </ Title> in JSP></p> <p></ HEAD></p> <p><Body></p> <p><Center></p> <p><Table border = 5></p> <p><TR> <TH Class = "Title"></p> <p>Use JavaBean </ Table> in JSP></p> <p></ Center></p> <p><P></p> <p><Jsp: usebean id = "primetable" class = "hall.numberedprimes" /></p> <p><Jsp: setproperty name = "primetable" Property = "Numdigits" /></p> <p><Jsp: setProperty name = "primeTable" property = "numprimes" /></p> <p>Some <JSP: getProperty Name = "Primetable" Property = "Numdigits" /></p> <p>Digit Primes:</p> <p><Jsp: getproperty name = "primetable" Property = "numberedlist" /></p> <p></ Body></p> <p></ Html></p> <p>Note: The code of NumberedPrimes is omitted.</p> <p>13.5 JSP: GetProperty action</p> <p>JSP: getProperty action extracts the value of the specified bean property, converts into a string, and then output. JSP: getProperty has two essential properties, namely: name, represents the name of the bean; Property, indicates which attribute to extract. Here is an example, more examples can be found in the forebel.</p> <p><JSP: Usebean ID = "Itembean" ... /></p> <p>...</p> <p><Ul></p> <p><Li> Number of items:</p> <p><Jsp: getproperty name = "itembean" property = "numItems" /></p> <p><Li> Cost of Each:</p> <p><Jsp: getproperty name = "itembean" property = "unitcost" /></p> <p></ Ul></p> <p>13.6 JSP: Forward Action</p> <p>JSP: Forward action turns the request to another page. JSP: Forward tag has only one attribute Page. The PAGE property contains a relative URL. The value of the PAGE can be given directly, or it can be dynamically calculated when the request is requested, as shown in the following example:</p> <p><Jsp: forward page = "/ utils / errorreporter.jsp" /> <jsp: forward point = "<% = somejavaExpression%>" /></p> <p>13.7 JSP: Plugin Action</p> <p>JSP: Plugin action is used to insert the Object or Embed element necessary to run Java Applet through the Java plugin according to the type of browser.</p> <p>Appendix: JSP annotation and character reference agreement</p> <p>Here are some special tags or characters, you can use them to insert a comment or may be considered a character with a special meaning. Grammatical use</p> <p><% - Comment -%> JSP annotation, also known as "hidden comments". The JSP engine will ignore it. All JSP script elements, instructions, and actions within the tag will not work.</p> <p><! - Comment -> HTML Note, also known as "Output Note", directly appearing in the result html document. All JSP script elements, instructions, and motion in the mark are executed normally.</p> <p><\% Actually wants to use "<%" place in the template text (static HTML).</p> <p>% \> Actually use "%>" where "%>" is actually used in the scripting element.</p> <p>\` Use single quotes within the properties of single quotes. However, you can use both single quotes or double quotes, and another quotation marks will have ordinary meaning.</p> <p>\ "Double quotes within the properties of the double quotes. See" \` "</p> <p>Java servlet</p> <p>And JSP Tutorial Directory (1-11)</p> <p>1 Overview</p> <p>1.1 Java servlet and its characteristics</p> <p>1.2 JSP and its characteristics / R</p> <p>2 installation</p> <p>2.1 Install Servlet and JSP Development Tools</p> <p>2.2 Installing the web server supporting servlet</p> <p>3 servlet</p> <p>3.1 SERVLET basic structure</p> <p>3.2 Simple servlet for outputting plain text</p> <p>3.2.1 HelloWorld.java</p> <p>3.2.2 Compilation and installation of servlet</p> <p>3.2.3 Run servlet</p> <p>3.3 Servlets Output HTML</p> <p>3.4 Several HTML Tools Functions</p> <p>4 form</p> <p>4.1 Form Data Overview</p> <p>4.2 Example: Read three table single variables</p> <p>4.3 Example: Output All Form Data</p> <p>5 http request head</p> <p>5.1 HTTP Request First Overview</p> <p>5.2 Read the request head in the servlet</p> <p>5.3 Example: Output All Request Head</p> <p>6 CGI variable</p> <p>6.1 Overview of CGI Variables</p> <p>6.2 Servlet equivalence of standard CGI variables</p> <p>6.3 Example: Read CGI Variables</p> <p>7 status code</p> <p>7.1 Status Code Overview</p> <p>7.2 Set status code</p> <p>7.3 HTTP 1.1 status code and its meaning</p> <p>7.4 Example: Access Multiple Search Engines</p> <p>8 http response</p> <p>8.1 HTTP response header outline</p> <p>8.2 Example: Automatic refresh page when content changes /</p> <p>9 cookie</p> <p>9.1 Overview of Cookies</p> <p>9.2 Servlet's cookie API</p> <p>9.2.1 Creating a cookie</p> <p>9.2.2 Reading and setting the cookie properties</p> <p>9.2.3 Set cookies in your response</p> <p>9.2.4 Read Save to Client Cookies</p> <p>9.3 Several cookie tool functions</p> <p>9.3.1 Get the cookie value of the specified name</p> <p>9.3.2 Automatically saved cookies</p> <p>9.4 Example: Customized Search Engine Interface</p> <p>10 session</p> <p>10.1 Conversational Status Overview</p> <p>10.2 Session Status Tracking API</p> <p>10.2.1 Viewing the currently requested session object</p> <p>10.2.2 Viewing information about and sessions</p> <p>10.2.3 Save data in the session object</p> <p>10.3 Example: Display Session Information</p> <p>11 JSP11.1 JSP overview</p> <p>11.2 JSP syntax summary table</p> <p>11.3 About Template Text (Static HTML)</p> <p>12 JSP basic content and directive / r</p> <p>12.1 JSP script elements</p> <p>12.1.1 JSP Expression</p> <p>12.1.2 JSP Scriptletlet</p> <p>12.1.3 JSP declaration</p> <p>12.2 JSP Directive</p> <p>12.2.1 Page Directive</p> <p>12.2.2 Include Directive</p> <p>12.3 Example: Application of Script Elements and Instructions</p> <p>12.4 JSP predefined variable</p> <p>12.4.1 Request</p> <p>12.4.2 Response</p> <p>12.4.3 OUT</p> <p>12.4.4 Session</p> <p>12.4.5 APPLICATION</p> <p>12.4.6 Config</p> <p>12.4.7 PageContext</p> <p>12.4.8 Page</p> <p>13 JSP advanced content</p> <p>13.1 JSP: INCLUDE Action</p> <p>13.2 JSP: Usebean Action</p> <p>13.3 Further stations about JSP: Usebean</p> <p>13.4 JSP: SETPROPERTY Action</p> <p>13.5 JSP: GetProperty Action / R</p> <p>13.6 JSP: Forward Action</p> <p>13.7 JSP: Plugin Action</p> <p>Appendix: JSP annotation and character reference agreement</p></div><div class="text-center mt-3 text-grey"> 转载请注明原文地址:https://www.9cbs.com/read-47047.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="47047" 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.043</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 = 'b_2FnKK_2BUGaoq_2B2OLgvY073WHdzy89BcUGx_2BzzZRaM8KTiRtfLa2D_2Bx7ymMtigpCoZtwEpuP0OkhDizvzXXW5z0w_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>