Tenth talks about JSP and servlet

xiaoxiao2021-03-06  60

Course index

1. What is the difference between dynamic web pages and static pages? 2. What is a web application? 3. What is a servlet, what is the difference between the general java program? 4. What is JSP, and what is the relationship with Java? 5. What is the difference between JSP and Servlet? 6. Main uses of JSP and Servlet? 10.1 Concept, configuration and operation of servlet

10.1.1 Concepts of Java Servlets Java Servlet are a Java component specifically to write web server applications. All Java-based server-side programming is built above the servlet. Servlets in J2EE are already a standard component.

A package associated with servlet in J2EE is javax.servlet, where the most basic servlet is declared as an interface javax.servlet: interface servlet, which is a SERVLET's highest level of abstraction, which is independent of the network protocol. Also in the Javax.Servlet, a class javax.servlet: Class GenericServlet, this class implements a servlet interface and is not related to the agreement. This class is a universal parent class that builds other and protocol associated servlet subtypes (at least HTTPSERVLET is inherited from it, which can also see this from its name).

That is to say, the network protocol applied by the servlet can be a variety of, such as HTTP, FTP, SMTP, Telnet, etc., but now, only HTTP services have formed standard Java components. Corresponding packages have two javax.servlet.http and javax.servlet.jsp, respectively correspond to the servlet and JSP programming we have to explain. We usually say the servlet programming is mainly for HTTP's servlet programming, which is the class in the javax.servlet.http package (typical is httpservlet class), and the concept of Java Servlet programming is wider. Here we also use servlets to use servlet to refer to HTTP Servlet, which readers need to understand. Since JSP is ultimately converted to servlet code through the JSP engine, and servlet programming and general Java programming is not a big difference, just understand certain specifications, so we will explain the servlet's programming, so It is a great advantage to understand JSP later, although JSP is simple to be simple although it is in use. At present, the servlet engine is generally a third-party plug-in. It connects to the web server through a certain approach, the servlet engine identifies the HTTP request interception to the servlet request, while other HTTP requests are made by the web server in a usual way. Processing, the Servlet engine will load the appropriate servlet to memory. If the servlet has not yet run, a thread that can be used is assigned to process the request, and then return the servlet's output to a requesting web client. Java servlet and java applet are just the corresponding two program types, and the applet is running on the client, executing within the browser, and servlet runs inside the server, start running through the client submitted, the reader can make simple in the learning process Comparison.

Since servlet is written in Java, it has a cross-platform feature with java, so the Servlet program is not related to the platform, and the same servlet can be performed on different web servers, etc., regardless of the Apache, IIS. The underlying operating system is Windows, Solaris, Mac, Linux or other operating systems that support Java. Servlet is the same as a normal Java program, is executed by the JVM after being compiled into one by one. Compared to traditional CGI, although CGI is directly executed with local code, because each client issued a request, the server must start a new program to handle the request, which imposes high loads to server resources, especially if CGI When writing in the scripting language, such as Perl, the server must also start the language interpretation program, the more the program, the more memory, the more memory, the more affected system performance. Servlet runs in the Java virtual machine from the servlet engine, wakes up from the client, and is different from the CGI. In the virtual machine to load a servlet, you can handle new requests, each new request uses the memory. The same copy of the servlet, so the efficiency is higher than the CGI. If you use a server-side script, such as ASP, PHP, language interpreter is a built-in program, so you can speed up the server's operation, but efficiency is more efficient than the servlet that is not accurate. The actual use has also proved that servlet is a high efficiency server-side program, which is ideal for developing a web server application. Java servlet has a wide range of applications. Not light can handle the client's request, with the powerful feature of Java, use servlets to achieve a large number of server-side management maintenance features, as well as a variety of special tasks, such as, and process multiple requests, transfer requests, proxy, etc. 10.1. .3 servlet's operating environment

Typical servlet running environments include JSWDK, Tomcat, Resin, etc. These are free software, suitable for learning Servlet and JSP. They come with a simple HTTP Server, just simply configure it, you can also bind them to commonly used web servers, such as Apache, IIS, etc., providing small-scale web services. There are also some commercial large and medium-sized support servlet and JSP web servers, such as Jrun, Web Sphere, Web Logic, etc., configurations are more complicated, not suitable for beginners. But the function is more powerful, and the conditionable readers can try it.

10.1.7 Compilation of servlet

Servlet's compilation and general Java programs are exactly the same, and no special parameters are required when using Javac compile. As long as the servlet is written is correct, the class file generated after compiling can be run as a servlet. Simple example:

Import java.io. *; import java.util. *; import javax.servlet.http. *; import javax.servlet. *; // Import the necessary package public class Helloservlet Extends httpservlet {// All servlets must be derived from httpservlet Public void doget (httpservletRequest Req, httpservletResponse res) throws servleTexception, ioException // doget () is the core of this servlet, a place for a request for request ("text / html"); // Set the corresponding type to text / html printwriter PW = res. Getwriter (); // Get the output stream PW.Println from httpservletResponse (""); PW .println (""); PW.Println (""); PW .println (" Hello, World! "); PW.Println (" "); PW.Println (" "); PW.Println ("

Hello, World! "); PW.Println (" ") ; // The above statement is to print html text to the client PW.Close (); // Turn http ServletResponse enables the web server to know the corresponding end} public helloservlet () {} // Constructor, can not}

10.2 Application Example of Servlet

10.2.1 Method for interacting with a form of servlet

The form is a means of using the most widely transmitted information in HTML. Make a clear of the interaction of servlets and forms, racing a bridge between the client and the server. Servlet interacts with the form in the HTTPServlet class. There are several unplearated methods in the HTTPServlet class, you can define the contents of the method, but you must use the method name correctly to make HTTP Server requests the customer requests the correct map to the corresponding function. DoHeader is used to handle the Header request Doget to process GET requests, or automatically support the Header request dopost to process the POST request DODELETE for processing the service method for delete requests Httpservlet, when it receives an Options request When it automatically calls the DoOptions method, call Dotrace when receiving a TRACE request. DoOptions default execution is the automatic decision what kind of HTTP is selected and returned which information. Two parameters must be taken when using these methods. The first containing data from the client httpservletRequest. The second parameter contains the corresponding HTTPSERVLETRESPONSE of the client. An HTTPSERVLETREQUEST object provides the request HTTP header data, and the client's data is allowed. How to get these data depends on the HTTP request method. Regardless of the HTTP mode, you can return the parameter value of a specific name with the getParameterValues ​​method.

(HTTPSERVLETREQUEST, the HTTPSERVLETRESPONSE interface is inherited in the servletRequest and servletResponse interface, and the getParameterValues ​​and getWriter methods are methods in their ancestral interface) For HTTP GET requests, the getQueryString method will return a parameter value that can be used to anatomical analysis. There are two ways to use HTTP POST, PUT, and DELETE requests. HTTPSERVLETREQUEST has two ways to select: If you are text data, you can get BufferedReader to get data by getReader; if it is binary data, you can get ServletInputStream to get data. For the respective client, an HttpservletResponse object provides two ways to return data to the user: one is to get a printwriter with the getWriter method for returning text data; another method is to get servletoutputstream with the GetOutputStream method for returning binary data. . Before using Writer or OutputStream, you should set the header (HTTPSERVLETRESPONSE), and then send the corresponding body portion to the user with Writer or OutputStream. After the completion, turn off the Writer or OutputStream so that the server knows that the corresponding is over.

Example: PrintWriter out = response.getwriter (); out.println ("Request Uri:" Request.getRequesturi () "
");

We know that all coding methods are the same on the same machine. The general Chinese platform is GB2312. The English platform is ISO-8859-1, but the two machines on the network do not guarantee that their coding mode is the same. At this time, there is a problem that there may be garbled. When performing HTTP network transmission, the unified encoding method is ISO-8859-1, if it is still problematic if it is transmitted in accordance with local coding, this is also an imperfect place when servlet is realizing network transmission, it There is no transition to the ISO-8859-1, so it will appear in direct printing. In principle, anywhere in the print string is required to be encoded, but the Western character corresponds to the same coding in different character sets, so that it does not need to be converted when printing a Western character. This troubles may be changed in the SERVET subsequent specification. Different from the form data submitted from the network, the servlet is automatically encoded, so the NAME string variable obtained in the program is GB2312 encoded, and it is also necessary to convert it properly on the client. Character encoding conversion common method is String native_encoded = "Chinese string"; // / / Local encoded string Byte [] Byte_Array = native_encoded.getbytes (); // Get local encoded byte array String net_encoded = new string (native_encoded , "ISO-8859-1"); // Generate ISO-8859-1 Code: Out.Println (New String (" Your Name: "). GetBytes (), "ISO-8859-1));

10.2.3 Controlling the session with a servlet

The maintenance of the session state is the problem that the development of web applications must face. There are a variety of ways to solve this problem. If you use the cookies, the Hidden Type of form fields, or directly add status information to the URL, there is a servlet itself A httpsession interface supports the maintenance of the session state, where we mainly introduce the management of session state based on this interface.

The SESSION is in order to fill the limitations of the HTTP protocol. Note how the HTTP protocol works - the user issues a request, the server responds, this client and server connection are discrete, discrete. The HTTP protocol cannot provide a function of allowing the server to track user requests. After the server is completed in response to the user's request, the server cannot continue to remain connected to the browser. From the server, each request is independent, so the HTTP protocol is considered a stateless protocol, and when the user switches between multiple homepages, the server cannot know his identity. The appearance of session is to make up for this limitations. With the session, you can save his information when a user is switched between multiple homepages. This makes many things that I can't do before. Each visitors will receive a session separately at the time of the visitor from the time of a particular home page. Java servlet defines an HTTPSession interface, the implementation of the Session function, using the session in the servlet as follows: (1) GetSession method using httpservletRequest gets the current SESSION, if current does not define session, create a new session, You can also use the method getsession (2) to write the session variable. You can use the method httpsession.setttribute (name, value) to store a message to the session. You can also use httpsession.putValue (name, value), but this method is outdated. (3) Read the session variable. You can use the method httpsession.getattribute (name) to read a variable value in the session, if Name is a variable that is not defined, then returns NULL. It should be noted that the variable type read from getAttribute is Object, you must use forced type conversion, such as: string uid = (string) session.getattribute ("UID"); you can also use httpsession.getValue (Name), but this The method has been out of time. (4) Turn off the session. After using the session at the time, you can use the session.invalidate () method to close the session. But this is not strict. Because the servlet engine is automatically turned off after a while, SEESI. HttpSession session = request.getations (TRUE);

// Parameter True means creating a new Date Created = New Date (session.getcreationTime ()) when there is no session; // gets the time created by the session object Out.println ("ID" session.GetId () "
"); // Get the session ID, and print out.println (" create: " created
"); // Print session creation time session.setttribute ("UID", "12345678" ); // Add variables UID = 12345678 session.setattribute ("name", "tom"); // add variables in session Name = Tom10.2.2. Servlet lifecycle with the client's Applet, servlet (here The concept of servlet returns to the most original meaning) also follows the strict life cycle. There are three types of events in life of each servlet instance, which correspond to three methods that are woken up by the servlet engine: 1. INIT (). When the servlet is first loaded, the servlet engine calls this servlet's init () method, only calls once. If a sevlet requires special initialization needs. Then the servlet writer can override the method to perform the initialization task. This is an optional method. If a servlet does not need to initialize, the init method of its parent class will be called by default. The system guarantees that the servlet does not call any requests before the init method is successfully completed. 2. Service (). This is the most important method of servlet, which is a place that truly handles the request. For each request, the servlet engine calls the Service method of the servlet and passes the servlet request object and the servlet response object to it. 3. DESTROY (). This is the option to be in the INIT, and when the servlet is about to be uninstalled, this method is used to clear and release the resources allocated in the init method.

The lifecycle of the servlet can be summarized as the following steps: (1) Loading a servlet, this operation is generally dynamically executed. However, servlets typically provide a management option to enforce loading and initialize specific servlet (2) Server to create a servlet instance (3) Server call server, a client request to arrive at Server (5) Server Create a request object (6) Server Create a response object (7) Server to activate the service method of the Server, transfer request and response object as a parameter (8) Service method obtains information about the request object, processing request, access to other Resources, access required information (9) Service method uses a method of responding to an object. Remove the response back to Server and finally reach the client. The Service method may activate other methods to process the request. For example, doget, dopost, or other programmers have developed by DOGET, DOPOST or other programmers (10) For more client requests, Server creates new requests and response objects, still activation of this servlet service method, passed the two objects as parameters to it So repeating the above cycle, but no need to call the init method again, servlet is generally only initialized (11) When Server does not need servlet, such as the Server call servlet Destroy10.3 JSP introduction 10.3.1 JSP the concept of

JSP (Java Server Pages?) Is an advocacy of Sun Microsystems, many companies involved in a dynamic web technology standard. It is in an HTML code, inserts a JSP tag (TAG) and Java program (Scriptlet), which constitutes a JSP page, its extension is .jsp. When the client requests a JSP file, the web server executes the JSP file and then returns to the customer in the HTML format. The JSP has been mentioned that JSP is only constructing a high-level dynamic web page on servlet. Therefore, from the conceptual, relative servlet, JSP does not have any new things, if the reader understands the previous servlet is very understanding Then, the concept of JSP can be said that it is exactly the same as servlet, but it is slightly different in realization.

10.3.2 JSP advantages

1. One compile, multiple times, run, the code's execution efficiency is a JSP script language is a Java language, so it has all the features of the Java language. At the same time, JSP also supports most platforms. When the JSP is first requested, the JSP page is converted to servlet, and then compiled into a .calss file, later (unless the page has a change or web server is restarted), the JSP page is not re-re-re-re-requisition. Compile, but directly execute the compiled .class file, so the execution efficiency is particularly high. 2. Reusability of components can be reused, cross-platform JavaBeans and EJB (Enterprise JavaBeans) components, providing convenience for the development of JSP programs, we can put complex handles (such as dynamic content displayed in the page, and database) Operation) is placed in the component. These components can be used multiple times, which greatly reduces the recipients rewritten in the JSP page. 3. Separate the generation and display of the content to use JSP technology, and the web page developer can use the HTML or XML identity to design and format the final page. Use the JSP identifier or the script to generate dynamic content on the page. The statement that generates dynamic content is typically packaged in the JavaBean component, the EJB component, or JSP script segment. In this way, the designer and page programmers of the page can be processed synchronously. At the same time, by viewing the source file, you can't see the JSP identifier, you can't see the JavaBean and EJB components, or you can protect the code of the source program. 10.3.3 JSP operation mode

The JSP general mode is: When the server is started, the web server first judges whether it is a JSP page request when the web browser is sent. If the page is just a general HTML / XML page request, pass the HTML / XML page code directly to the web browser. If the requested page is a JSP page, the JSP page is checked by the JSP engine. If the page is the first request, or the JSP engine converts this JSP page code to servlet if the page is requested, or is being modified. Code, then the JSP engine calls the server-side Java compiler JavaC.exe to compile the servlet code, turn it into a range code (.class) file, then call the Java virtual machine to execute the bytecode file, then execute the result Pass it to the web browser. If the JSP page is not first requested, and is not modified, the JAVA virtual machine is called directly by the JSP engine to execute the compiled bytecode .class file, then send the result to the web browser. The above is a schematic diagram of a JSP operation.

(For example: In the RESIN server, put an add.jsp file in a doc / directory, http://127.0.0.1:8080/add.jsp. System will be in Doc / Web when seeing this page in the browser. -Inf / work / _jsp directory generated _add__jsp.class, _add__jsp.java, _add__jsp.java.smap three files.)

From here we are not difficult to see the relationship between JSP and Servlet, the JSP engine is responsible for translating the JSP page into a servlet, so JSP is completely servlet at the bottom layer (referring to the original concept, not httpservlet). We mentioned that JSP programming corresponds to javax.servlet.jsp, more precisely, this package is for JSP engine, it needs to be used when doing translation, we need to involve it when writing JSP pages The use of this package. Why do servlets have to implement a JSP on the high level? This problem is related to the annoyance of the servlet itself. If you use servlet to control the appearance of the page, it will be a very headache. Use JSP to hand over the annoying print task to the JSP engine, programmers can concentrate Logic control above. There will be further comparisons behind.

10.3.8 JSP Directive (1) Let's start explaining the syntax of JSP. From essentially JSP or Java program, because it will eventually be translated into servlet to compile into a Class file execution. However, since JSP is an embedded Java program, some special symbols still need to learn. Below we are listed in one by one, readers don't have to be more important, they will be familiar with them. 1. HTML Note This comment can be seen by viewing the source file by viewing the source file. JSP grammar: ] -> Example 1 Displayed in the client page source program: Example 2 -> Display in the client page source program To: Description Use any effective JSP expression in the comment. The expression is dynamic, which will be assigned when the user first calls the page or that the page is later reused. After the JSP engine is executed after the expression in the HTML annotation, the results of its execution will be inserted directly into the expression displayed. The result is then output to the client together with other content in the HTML annotation. The content between is not seen on the browser, but you can see this comment by viewing the source file by viewing the source file. 2. JSP comment JSP comment As the documentation of the JSP page, the comment is not seen in the client by viewing the source file. That is, the comment is not sent to the client. JSP grammar: <% - Note -%> Note: In JSP comments, you cannot use -%>, but if you must use it, you can avoid it by using -% />. 3. Statement in the JSP page scripting language declared variable or method JSP syntax: <%! Declaration; [declaration;] ...%> example <%! Int i = 8;%> <%! Int N, m, k , J;%> <%! String s = new string ("Hello");%> Description In the JSP file, one or more variables and methods can be declared at a time, and they are separated by a semicolon. When using Java languages ​​when declaring, you must comply with Java language specification. Note: (i) Variables must be declared first before you can use it. (Ii) The statement must end at the end of the semicolon, but it is not available in the expression. (Iii) Variables or methods in the package imported by the PAGE instruction can be used directly in the primary JSP file. (Iv) Under normal circumstances, the effective range of a statement is this page. However, if the JSP source file contains some static files with the instruction or the include instruction, the valid range of the declaration will expand, that is, the declaration is also valid in the static file. However, if you use the instruction in the JSP source file to include a dynamic file, the statement in the primary JSP file will not work in this dynamic file.

4. Expression can use any valid expressions in the JSP script language. JSP syntax: <% = expression%> Example 1: <%! String s = new string ("hello");%> <% = java.lang.math.random ()%> description expressions are used to evaluate, and then its value is converted to a string, and inserted This expression is displayed in the JSP file. And you can use an expression in text. Expression tags can contain any valid expressions that meet the Java language specification, but pay attention to: The semicolon cannot be used as the end of the expression, however, in the script paragraph <% ...%> tag, the expression requires a semicolon as a semicolon end. 5. Script Section In the JSP page scripting language, the script is included in the JSP page script language contains a valid code snippet. JSP syntax: <% code segment%> Example 1: <% = java.lang.math.random ()%> <% for (int i = 0; i <8; i ) {Out.println (i);} %> <% Long n = 6666; application.setttribute ("maxNumber", long.toTOString (n)); Out.println (Application.getaTribute ("MaxNumber"));%> Describe in the script segment can declare multiple variables And methods. Can use any effective expressions. Objects that can be used with any JSP implied objects or any objects that use the tag. You can use the Java language if you can use the Java language, and you must comply with the Java language program specification. Explanation: If the script segment has an output statement, the output content is stored in the OUT object and outputs it to the JSP page via the OUT object. 10.3.8 JSP instructions (2) 1. The Include instruction This instruction is used to include a file of a text or code. JSP syntax: <% @ include file = "relativeurl"%> example: random display in random.jsp in: <% @ include file = "random.jsp"%> random.jsp The content is: <% = java.lang.math.random () * 10000%> Displayed in the page: Random.JSP number is: 2148.093521070482 Description Include instruction Insert a text in the JSP file And code files. The files included can be a JSP file, an HTML file, or a text file. If the file being included is a JSP file, the JSP engine is compiled after the JSP file, and the resulting result will be inserted into the location of the include instruction in the primary JSP file. If the included file is an HTML file or text file, the JSP engine does not compile it, and inserts its content directly into the location of the INCLUDE instruction in the primary JSP file.

The included is static, that is, the file being included, and the result is also inserted into the primary JSP file, and the primary JSP file will continue to perform the content below the include Directive. Note: (1) You cannot contain , , , or tag in the file being included. Because the entire contents of the files being included will be inserted into the JSP file where the include instructions are in the JSP file, these tags will conflict with the same tags in the JSP file. (2) If the files included are vocal, the primary JSP page will be recompiled. Properties: file = "relativeURL" file is the path name that is included. It is part of a URL, no protocol, port number or domain name. Such as: "Error.jsp" /templates/onlinestore.html "/beans/calendar.jsp" If the relative URL starts with "/", this path It is for the JSP application context, and the JSP application context is a javax.servlet.ServletContext object stored in the Application object. If the relative URL begins with a directory or file name, this path is relative to the path where the current JSP file is located. 2. Page instruction Defines global properties of the entire JSP page. JSP syntax: <% @ page [language = "java"] [extens = "package.class"] [import = "{package.class | package. *}, ..."] [session = "true | false" ] [Buffer = "None | 8KB | SIZEKB"] [Autoflush = "true | false"] [isthreadsafe = "true | false"] [info = "text"] [errorpage = "relativeurl"] [contenttype = "MIMETYPE [ Charset = Characterset] "| Text / HTML; Charset = ISO-8859-1"] [ISERRPAGE = "true | false"]%> example: <% @ Page ContentType = "text / html; charSet = GB2312"%%% > <% @ Page import = "java.sql. *, Java.lang. *"%> <% @ Page buffer = "8KB" Autoflush = "false"%> <% @ Page ErrorPage = "error.jsp"% > Description: The scope of the PAGE instruction is the entire JSP file and the JSP file with any static file included in the , the entire JSP file and these static files are called a "translation unit". Note: Page The instruction does not apply to any dynamic containment file. You can use multiple PAGE instructions in a "translation unit".

But every property can only be used once, in addition to import (because the Import property, the IMPORT statement of the Java program language is very similar, you can use it multiple times, you can use the import command multiple times in the Java language). Whether you put the PAGE directive in any location of the JSP file or the file being included, its scope is entire "panning unit". However, a good designer is often placed on the top of the file. Language = "Java" in the script segment of the JSP file, the language used in the declaration, and expressions. "Java" is now allowed. Extends = "package.class" This property is used to indicate the full name of the Java class file. Be careful when using this property because it limits the ability of the JSP engine to compile files.

Import = "{package.class | package. *}, ..." The list of one or more packages that are imported with a comma in the JSP file. These packages (and their classes) can be used in the script segment, expressions, declarations, and tags of the JSP file. You must put the import property in front of the label of the class that is arrived. If you want to import multiple packages, you can open each package with a comma after IMPORT, or you can use multiple Imports in a JSP file.

Session = "true | false" This property is used to determine if the JSP page uses http session. If this value is true, the sessions references the current or new session. If this value is false, in the JSP file, you cannot use Session object. The default is True.

Buffer = "None | 8KB | SIZEKB" Sets the size of the Buffer buffer when the OUT object uses the compiled JSP page to be used for the customer web browser. Its default is 8KB. If you specify the size of the buffer buffer, this output will not be less than the size you specify.

Autoflush = "true | false" This property indicates whether it is automatically refreshed when the buffer is full. If the value is true (the default value is true), it is automatically refreshed. If the value is false, an error will occur when the buffer overflows. And if the value of the buffer attribute is set to none, the value of the Autoflush property cannot be set to false.

Isthreadsafe = "true | false" assumes that this value is set to True, and multiple threads can access a JSP page at the same time. If this value is false, the JSP engine can only respond to a user's request at a time. The default is TRUE.

INFO = "text" About the author, version, and copyright information, you can check the details of this information through the javax.sevlet.servlet.getServletInfo () method.

ErrorPage = "RelativeURL" This property is used to set the path name of the JSP file for processing an exception event. If this pathname is start with "/", this pathname is the JSP application document root directory and is determined by the web server. Otherwise, this path is relative to the current JSP file.

iSerrorPage = "true | false" JSP file displays the error page. If this value is True, you can use the exception Exception object. If this value is false (the default is also false), in the JSP file, the Exception object cannot be used.

ContentType = "MIMETYPE [; Charset = CharacterSet] |" Text / HTML; Charset = ISO-8859-1 "MIME TYPE and CHARACTER ENCODING used in JSP files are requested to respond to the client. You can use any MIME TYPE or CHARACTER SET (character set) in the JSP engine. The default MIME TYPE is Text / HTML, and the default character set is ISO-8859-1.3. Element transfers the client's request to an HTML file, a JSP file or script segment. JSP syntax: description: tab The request object is transferred from a JSP file to another file processing. Special Note: JSP Engine is no longer executed by the code below the primary JSP page . Note: If the output of the JSP file is set to buffer output (ie the default PAGE command value or directly setting the buffer size), the buffer is cleared before the request is transferred. If the output is set to a non-buffer output (ie, set buffer = none with the PAGE instruction), and the output area already has content, the element will be used, which will result in illegal exceptions. Attributes

Page = "{relativeURL | <% = expression%>}" This property is used to set the associated URL of the file to be transferred. This URL does not include the protocol name, port number, or domain name, relative to the current JSP file. If it is an absolute address (starting with "/", the path is determined by your web or application server.

4. obtains the value of the bean property to display in the result page. JSP syntax: Example: program code Bean as: package AccessDatabase; public class Readdate {private String username = "changcheng"; public String void getUsername () {return UserName;}}}}}} The content of the JSP file is: get the value of the property name UserName from the bean : The display result is: Value obtained from the bean named User: changcheng Description: Use Before you have to create or call a bean instance for elements. The tag is a getxxx () method for obtaining a javabeans property value, equivalent to calling a attribute in the bean. Property: Name = "beanStanceName" in the name of the bean instance declared in the tag. Property = "PropertyName" bean name. Description: When using the element: , username must be the properties in bean (READDATE), and you must have getUsername in this bean. ) Method, otherwise it will be wrong when compiling.

5. In the JSP file, it contains a static or dynamic file. JSP syntax example: attribute: tag allows you to include one Static file or dynamic file. After a static file is executed, its content is inserted in the primary JSP page. A dynamic file responds to the request and inserts the execution result into the JSP page. Tags can handle two file types, when you don't know that this file is a static or dynamic file, it is very convenient to use this tag. When the Include action is executed, the JSP engine will then perform the file code left in the JSP file. Page = "{relativeURL | <% = expression%>}" This property indicates that the file-related URL is included; the URL cannot include the protocol name, port number, or domain name. This URL is absolutely or relative to the current JSP file. If it is an absolute address (starting with "/", the path is determined by your web or application server

Flush = "true" In the JSP file, Flush = "true" is often set because it is not a default.

6. Download a plugin plugin to the client to execute Applet or Bean JSP syntax: [ [] ] [ Text Message for User ] example:

Unable to load applet < / p> element passes the parameters and its value to the Applet or Bean when the computer is started. If PLUGIN is not started, the element will provide a message to the user. If PLUGIN starts, the applet or bean does not start, Plugin often pops up a Window window, the user explains the reason for the error. Property: type = "bean | applet" plugin will execute the type of object. You must specify the bean or applet because this property does not have the default. Code = "ClassFileName" Plugin will execute the name of the Java class file. Keep the .class extension in the file name. The file name is a directory named in the CodeBase property.

CodeBase = "classfileDirectoryName" contains a relative or absolute address of the directory name of the Applet code. If this value is not provided, the path to the JSP file of will be used.

Name = "InstanceName" bean or the name of the Applet instance, the same JSP file can communicate with each other by it. Archive = "uritoarchive, ..." A list of paths separated by commas, which indicates the location of class files loaded with class loaders. The class-loader is a directory named in the CodeBase property.

Align = "Bottom | Top | Middle | LEFT | Right" Applets or beans The location of the image displayed in the bean is based on such rows in the JSP result page. This line is included in the JSP file containing Row. The results of different values ​​are as follows: Bottom aligns the bottom of the image with the baseline of the next text. TOP aligns the top of the image with the top of the next text line. Middle aligns the vertical center of the image to the baseline of the next text line. Left allows the image to align the image. Right makes the image right right.

Height = "DisplayPixels" width = "DisplayPixels" Applet or Bean is displayed in pixels, which does not include any windows and dialogs that Applets or beans pop-up.

Hspace = "Leftrightpixels" vSpace = "Topbottompixels" Applet or bean is the size of the distance between the images (or up and down) of the image displayed in pixels. Generally a very small non-zero value. JREVERSION = "JreversionNumber | 1.1" version of the Java runtime environment (JRE) requested by the Applet or Bean. The default value is 1.1

NSPLUGINURL = "URLTOPLUGIN" User needs to download the URL of the JRE plugin when using the Netscape Navigator browser. It is a complete URL address, with protocol name, port number, and domain name.

IEPLUGINURL = "URLTOPLUGIN" User needs to download the URL of the JRE plugin when using the Internet Explorer browser. It is a complete URL address, with protocol name, port number, and domain name.

[] Parameters and values ​​passing to applet or beans. To deliver multiple parameters and values, you can use multiple tabs in elements. Applets get parameters through the java.applet.applet.getParameter method.

Text Message for User Displayed to the user's text information if the PLUGIN plugk cannot be used

7. Sets one or more attribute values ​​of the bean. JSP syntax:

Example: attribute: Tab is used to set the attribute value in the JavaBean component. Before you use Elements, you must use the tag to declare this bean. The value of Name in is consistent with the value of the ID in . The value of the general setting attribute has three methods: (i) Using the method, you can request all values ​​in the user request (these values ​​are generally the elements in the customer form. The value, and as the parameter stored in the Request object) and the matching attribute assignments in the bean. At this point, the name of the attribute in the bean must be the same as the name of the element in the client form. (ii) Use the method, with a specific value in the request object or the property assigns or does not match Attribute assignment. (iii) Use the method, the value of the value or expression of the character string is directly set to bean Attribute properties and usage: name = "beanStanceName" in the tag instance name. Name's value must be consistent with the value of the ID in . Property = "*" This property is used to set the value of the bean property at once. The value of the elements in the client form is assigned to the matching attribute assignment in the BEAN. Also, if the bean has a property without the form element corresponding to it, this property will not be set.

Property = "PropertyName" [param = "parametername"] When the value of one element in the form is assigned to the bean, and the element name and the attribute name are different, you must specify a parameter with param.

8. Call or create a bean specified name and use range. JSP syntax: | > Other tags } example: >

Property: Tag first calls a specified name and the range of beans, if this bean does not exist, create the bean. Properties and usage

ID = "BeanInstanceName" is called or created by the name. You can use the variable name in the expressions of the JSP file. If the bean has been created by another , the ID value must be the same as the ID number used in the original tag.

Scope = "Page | Request | Session | Application" Defines the range of beans. The default value is Page. BEAN must be used within its designated range, otherwise it will be wrong.

Class = "package.class" Specifies which class in which package is present in the storage location of the bean. This class cannot be an abstract class, and there is a public, there is no parameter constructor. Packages and class names are strictly sized.

Class = "package.class" type = "package.class" Type value can be as class, such as superclass or the type of interface implemented.

The above is some syntax to write JSP. The reader does not have to master the mastery. When you need it, you will naturally be skilled in use. 10.3.9 Hidden objects in JSP (1) Since JSP is embedded language, you cannot explicitly pass some must pass, such as the Request object, response object, etc., so a few implicit is provided in the JSP specification. Objects to implement the folding function. The so-called implicit object is that everyone will use a name to refer to a particular object. When writing JSP, it can be used without explicitly declaration. The JSP engine is responsible for adding implicit objects when explaining. Explain the .java file. Commonly used implied objects include Application, Session, Request, Response, Out, Page, Exception, PageContext. 1. The session object has been mentioned in the servlet section, and the web server will automatically create a session object when the customer first access the web server publishing directory (a web server has one or more "publishing directory"), the web server automatically creates a session object. And assign the unique ID number, customers can save some of the information they need to the session object for use. The Session object refers to the object obtained by the GetSession method. In JSP, it is an implicit object, and the reader of the session object can see the Servlet API.

2. Application object When the web server starts, the web server automatically creates the Application object. Once an Application object is created, it will always exist until the web server is turned off. Therefore, Application objects can realize data sharing between multiples. A web server often has multiple publishers. When the web server starts, it automatically creates an Application object for each publishing directory, which is independent, and and the publishing directory corresponds. Application lifecycle: Start from the web server to the web server to close. Application ranges in the life cycle: All web files from the same release directory A can be operated on the Application objects of "and publishing directory A", and all customers accessing the publishing directory A share an Application Object. Therefore, when the data information is stored in the application, all customers who have access to the publishing directory A can access them and implement data sharing between multiples. The base class of the Application object is: javax.servlet.servletContext class. Application can be obtained with the getServletContext () method in this class. See the Servlet API for specific methods.

3. The REQUEST object Request object is primarily used to obtain data information transfer between the client and multiple web pages submitted in the form. At the same time, it can also obtain the parameters of the web server. Corresponding to the Request object in the servlet parameter. The base class of the Request object is: javax.servlet.servletRequest If the transfer protocol is HTTP, it is a Javax.Servlet.httpservletRequest specific method to see the Servlet API.

4. The Respose object RESE object is primarily used to output information to the client, respond to the client's request. The response object in the servlet parameter is corresponding. The base class of the Respose object is: javax.servlet.ServletResponse If the transfer protocol is http. For javax.servlet.httpservletResponse. See the Servlet API for specific methods. 5. OUT object OUT object is used to output data to the client. The OUT object base class is: javax.servlet.jspwriter class, which is slightly different from the PrintWriter obtained by HttpservletResponse in the servlet, but it is only inherited from Writer, so it is basically the same. See the Servlet API for specific methods.

6. Page Object Page object is an instance of the current JSP page itself. Its type is: java.lang.object. Its method is the method in the object class. Such as: Class getClass () returns an object to the representation of the class corresponding to the runtime, so that the corresponding information can be obtained. String toString () Returns the string representation of the current object. Page objects can be replaced with this in the current page. 7. Exception object When an exception or error occurs during an execution process, an Exception object is automatically generated. After the current page is set by <% @ page isrrorpage = "true"%>, you can use this Exception object to find page error messages. The type of Exception object is: java.lang.exception class. The common method of Exception object is: String getMessage () Returns the error message of the page, if not, return null void printstackTrace () in the form of standard error output stream, print and display Current Exception object and its execution track. 10.4 JSP and Servlet combination

When using JSP technology development sites, it is not emphasized using servlet. ,Why is this? The application of servlet is no problem, it is ideal for server-side processing and programming. But if you use servlet to handle a lot of HTML text, it will be a cumbersome thing. This kind of thing is more suitable for machine, otherwise it is a waste of programmers. So the servlet is more suitable for processing the backend transaction, and the effect of the front end is more appropriate to implement JSP. Early JSP standards give two ways to use JSP. These methods can be summarized as JSP mode 1 and JSP mode 2, and the main difference is to handle a large number of requests. In Mode 1, the JSP page responds to requests and returns the processing results. There is still a separation of views and content here, as all data rely on beans to process. Although mode 1 can meet the needs of small applications, it does not meet the needs of large applications. A large number of mode 1, often leads to a large number of Script and Java code. Especially when the business logic needs to be processed is very complicated, the situation will become very serious. Maybe this is not a big problem for Java programmers. But if the developer is a front interface design person, in large projects, this is very common, the development and maintenance of the code will be difficult. In any item, this mode will always lead to unclear responses and project management difficulties. The following figure is a schematic of the mode 1:

JSP mode 2 is an implementation for dynamic content, combined with servlet and JSP technology. It utilizes the original advantages of two technologies, using JSP to express the page, using servlet to complete a large amount of processing, servlet play a controller's role and responsible for responding to customer request. Next, servlet creates the bean and objects required by the JSP, and decides which JSP page to the user according to the user's behavior. It is important to note that there is no commercial processing logic in the JSP page, which is just a simple retrieval of the Beans or objects previously created, and then insert the dynamic content into a predefined template. From the viewpoint of development, this model has a clearer page manifestation, a clear developer role division, can fully utilize interface designers in the development team. In fact, the more complicated projects, the better the use of mode 2 is more prominent. Use mode 2, JSP and servlets can be separated at the maximum amplitude of the function. The correct use mode 2 causes a centralized control servlet, and only the displayed JSP page is completed. On the other hand, the implementation of mode 2 is complicated, and therefore, in a simple application, mode 1 can be considered. Here is a schematic of the mode 2:

Web

Which model used in the construction is very important in advance, only a lot of experience can make the correct and effective choice. In short, the website is not only the problem of technology, and the overall plan is very important, readers are learning

JSP

with

Servlet

At the same time, it should pay more attention to the essence of absorbing ideas, and the technology is time, but thought is always valuable.

转载请注明原文地址:https://www.9cbs.com/read-118239.html

New Post(0)