Tenth talks about JSP and servlet

zhaozj2021-02-16  53

10.1 Concept, configuration and operation of servlet

10.1.1 Concept of Java Servlet

Java Servlet is a Java component designed to write network server applications. All Java-based server-side programming is built above the servlet.

Servlets in J2EE are already a standard component. Let's meet, how the servlet is a structure in Java's package, which will help us understand the concept of servlet.

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. Readers who have used CGI must know the role of the CGI program, the functions to be implemented by servlets, but the CGI is the same, it is more convenient and efficient. If the reader is not very clear about the above concept, it doesn't have to worry, through learning the following content, there is a sense of understanding, then come back to see, there will be more gains.

10.1.2 SERVLET's advantages and applications

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. Unlightened can handle the client's request, with the powerful features of Java, use servlets to implement 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.

In actual use, readers will have more opportunities to learn about the latest application of Servlet, here we only introduce basic applications.

10.1.3 Servlet's operating environment In order to run servlet, first of course, a JVM is required to provide basic support for Java, usually need to install JRE (Java Runtime Environment) or JDK (Java Develop Kit, JRE is a subset).

Second, we need the support of the Servlet API. The average Servlet engine comes with the servlet API, as long as we install the servlet engine, or automatically install the servlet related package after you support the servlet's web server.

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. Behind we will explain how to configure a simple web server that supports Servlet and JSP.

10.1.4 Servlet and CGI environment variable

When using CGI, the most important content is the environment variable of the CGI interface. The CGI specification lists 19 environment variables. Although other environment variables, such as HTTP_COOKIE (for query site information) is not part of the specification, but is also commonly used. Since Java is running in JVM, the environment variable cannot be directly accessed directly on the server. Since the CGI environment variable is established by the web server, and the user can query the variable value with other methods, Java does not access the environment variables. Java Servlet API defines several methods that have found most information in the CGI environment variable.

Some information is an integral part of the HTTP title, and the GetHeader () method in the HTTPServletRequest class can be easily acquired. Use special methods to query other information. Java unavailable CGI environment variables are GATEWAY_INTERFACE. This variable contains the CGI version when used in the CGI program. This variable information in Java servlet is irrelevant.

The above content is for readers with CGI programming experience, through comparison, can help readers can understand the servlet. Use readers who don't know anything to CGI. 10.1.5 SERVLET security

Java servlets can use security protocols including SSL. Servlet is closely linked to Java's internal security measures, such as directly accessing memory. With security managers, users can define access to other resources, such as files, directories, and local area networks. The Java Servlet supports code symbols to better control the programs to entrust each servlet to execute.

Java's security mechanism itself is more complicated. We can only make simple explanations here, otherwise they will win. Specific analysis See chapter on Java security.

10.1.6 management of servlet

For most users, servlet is easier to manage than CGI programs and server scripts. Servlet is compiled in the form of a Java class. Java adopts components that are capable of saving in the Directory tree in a Java Archive (.jar) file, Java Archive (.jar) file provides a management class, such as Sun's Servlet Management Platform for Sun's Java Web Server. Some servers and third-party products provide a graphical user interface for managing servlets.

The specific Servlet management is a more complex thing, especially for a large system. For beginners, just master the basic configuration of a servlet, it is possible to make it function properly. More advanced techniques To truly master more practices.

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.

10.1.8 Running servlet with servlet runner

Before you really start writing servlet, let's introduce a simple servlet engine - RESIN. Currently, the Web server that supports servlet is not less than ten, RESIN is a simple and easy servlet runtime, which is very suitable for beginners. Since the servlet engine of each manufacturer is different, the configuration method is also a thousand words, it is impossible to general theory, but the writing method of the servlet is the same, so the reader does not have to care too much about the server configuration method, just know how to make your servlet normal operation. It is OK, put more attention on the servlet writing.

Resin comes with a Servlet Runner and HTTP Server, so you have to build a simple web environment, and RESIN is already enough, no additional support software is required. RESIN can not be installed and can be used after decompression. There are several subdirectory in the resin directory, and the bin directory stores executable files. To start HTTP Server and Servlet Runner only need to click on Httpd.exe and Srun.exe, four windows will appear after startup, respectively HTTP Server standard output, check / stop control, and standard output, check / stop control. The Conf directory is stored in the configuration file of the Resin Servlet Runner, which is the key to configuring the entire web environment, including the configuration of the Servlet and the configuration of the JSP you want to use. The DOC directory is the default publishing directory, that is, the HTTP Server comes with this directory is the root directory in this directory.

Below we use the simplest HelloWorld example to explain how to configure RESIN, so that it can run the servlet program, and also start with the servlet. The procedure is as follows: //Helloservlet.java import java.io. *; import java.util. *; Import javax.servlet.http. *; Import javax.servlet. *; // Import the necessary package public class helloservlet Extends httpservlet { // All Servlet public void doGet must derive from HttpServlet (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException // doGet () is the core of the Servlet, local real process requests {res.setContentType ( "text / html"); / / Set the corresponding type for text / html printwriter PW = res. maxWriter (); // Get the output stream from HttpservletResponse

PW.Println (""); PW.Println (""); PW.Println (""); PW.Println (""); PW.Println (""); PW. Println (""); PW.Println ("

Hello, World! "); PW.Println (" "); // The above statement is to print html text to the client PW.Close (); // Close httpservletResponse so that the web server knows the corresponding end} public helloservlet () {} // Constructor, can not}

This is the easiest servlet program. The entire class is derived from httpservlets, just like Applet, this derived relationship is necessary. This servlet must implement the Doget () method (because it is accessed by the address as a static page, this way is called GET request in HTTP, and there will be more specific explanations in the back), this is this servlet truly process request. Where is the main body of the entire servlet, just like the RUN () method of the line. DOGET () has two parameters HTTPSERVLETREQUEST REQ and HTTPSERVLETRESPONSE RES. HTTPSERVLETREQUEST contains various information of the customer request, and HTTPSERVLETRESPONSE is packaged in the server response, mainly processing the output of the client. This program is very simple. If you have some concepts of network programming and HTML, it is easy to understand. Compiling the above programs through Javac, we can get helloservlet.class, let's run this servlet by configuring RESIN. As mentioned earlier If you don't modify the RESIN configuration file, DOC is the Resin default publishing directory. Web_INF / CLASSES in the publisher is Resin default classpath, readers as long as they copy their own servlet to this directory, RESIN can identify, of course, as long as copying effective systems or user's classpath, RESIN can be found. . We copied helloservlet.class to the web_inf / class directory. Next, you need to modify the Resin.conf file under the confedor to configure our servlet. Readers can use any text editor you are familiar with to open the profile. Find, add the following configuration statements (can refer to existing statements) servlet-class = 'helloservlet'

This way when the client generates / hello request, RESIN can direct this request to the Helloservlet, which can run normally, we can also use the following configuration statements

In this case, there is no mapping of the name of the servlet. The system will default to use servlet-name as a class lookup, so servlet-name must fill in the correct class name, and cannot be a free name. About RESIn more configuration information, interested readers can refer to Resin's help documentation, here is no longer described here.

Below we launched HTTP Server and Servlet Runner (by double-click httpd.exe and srun.exe). This way we can access this servlet through your browser. Open your browser, such as IE, type http: // localhost: 8080 / hello in the address bar, we can open a web page:

By viewing the source code, we can get the following results Hello, World!

Obviously these texts are information we print to the client in servlet, in the HTTP head content = text / html is also set in the program.

Through such a simple HelloWorld program, the reader's basic configuration method of the Working principle of servlet should have a probably understanding. If the reader has questions about this example, be sure to make a clear study.

10.2 Application Example of Servlet

Above we have explained the basic concepts of servlets and introduced a running environment and its configuration method. Here we start explaining the specific application of servlets in writing web applications. 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. Using the Doget method in our first example, because through the address access, the corresponding way is Get.

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.

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.

Let's take an example of using httpservletRequest and httpservletResponse to get and print client information:

//Requestinfo.java import java.io. *; import javax.servlet. *; Import javax.servlet.http. *;

public class RequestInfo extends HttpServlet {public void doGet (HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException // GET request processing method {response.setContentType ( "text / html"); // first set Header, provided here only ContentType A PrintWriter Out = response.getwriter (); // Get text output Writer // below print-related HTML OUT.PRINTLN ("); out.println (" "); out.println (" "); OUT. Println (""); out.println (""); Out.println ("

Request Information Example ");

Out.println ("Request Uri:" Request.getRequesturi () ""); // Print Request Path Out.println ("Protocol:" Request.GetProtocol () "); // Print Protocol Name Out.println ("PathInfo:" Request.getPathInfo () ""); // Print extra path information Out.println ("Remote Address:" Request.getRemoteAddr ()); // Print the client's address If there is no printing IP address out.println ("); out.println (" "); out.close (); // Turn Writer}

Public void dopost (httpservletRequest request, httpservletResponse response "throws oewception, servletexception {// If the POST request type, the GET type response function doget (Request, Response) is also called;}}

Use our way to configure it in RESIN in RESIN, and our results are as follows:

One example is a good explanation of a so-called dynamic web page and a static web page. For the above example, each customer see is different, and the static web page is for every customer. immutable.

10.2.2 Example of servlet and form interaction

Above we introduced how servlet interacts with a form, and provides an example of obtaining client information from the HTTP request header. Below we give an example of interacting with a list of servlets submitted by HTTP, and by this example reader should be able to The process of interacting the entire client and server-side has a whole understanding. This example is divided into two files, one is a static HTML file, provides a form, and sets the submission button, the server will direct it to another file, which is our servlet, read the form by it. Print to the client.

1. Static HTML text: Ourform.html

2. FormDemo.java

1. Static HTML text: Ourform.html

Our Form

Name:

Gender: Male Female

The show is shown in the ie as shown in the figure:

Readers who are unfamiliar with HTML can refer to the two properties of the FORM for HTML, especially the two properties of the Form and Action

2. FormDemo.java

//Formdemo.java import java.io. *; import javax.servlet. *; Import javax.servlet.http. *;

public class FormDemo extends HttpServlet {public void doGet (HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException // GET request processing method {response.setContentType ( "text / html"); // first set Header, provided here only ContentType A PrintWriter Out = response.getwriter (); // Get text output Writer

String name = request.getParameter ("name"); // Get form value Name string sex = request.getParameter ("sex"); // Get form value sex name = new string (name.getbytes (), "ISO- 8859-1 "); // Convert to the correct encoding

// Print the obtained form value Out.println (""); out.println (""); out.println (""); out.println (""); out.println (""); Out.println ("

Data you posted "); out.println (" "); out.println (" "); out.println (New String (" your name: ") .getbytes ()," ISO-8859-1 ")); Out.println (" Name "); out.println (" "); out.println (" "); Out.println (New String (" "your gender:"). Gettes (), "ISO-8859-1"); out.print (""); if (Sex.equals ("1")) Out.println (New String ("Men") .Getbytes ( ), "ISO-8859-1"); else out.println (New String (New String ("Female") .GetBytes (), "ISO-8859-1"); Out.println (""); Out.println (""); out.println (""); out.close (); // Close Writer}} This servlet is also relatively simple, first get it from the submitted form The two values ​​needed, then print this information to the client with HTML. It is worth noting that in this example, all the characters that appear in the Chinese, we have used the transformation of character encoding to print the Chinese correctly. In the first example we There is no Chinese, and we need to mention the Chinese problem of servlet. We know that all coding methods are the same on the same machine, and the general Chinese platform is GB2312, and 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 may be garbled problems. When the HTTP network is transmitted, the unified encoding method is ISO-8859-1, this time If there is still a problem in accordance with local coding, this is also an imperfect place when servlet is implemented. It does not automatically perform local encoding to ISO-8859-1, so it will appear directly. Coabular. In principle, any place where the print string appears, it is necessary to coding conversion, but the text characters are in different character sets. The same encoding should be used to print the Western characters. 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 String strings so that the NET_ENCODED string can be used to print to the client without being wrong. It is also important to note that in order to display Chinese normally in the client, charset = GB2312 must be set at the HTML header.

When we press the submission button, the results we get are as follows:

What kind of results will we change from get to POST from get to POST from GET? Since we didn't rewrive the dopost method, we got the following results in RESIN:

Interested readers can modify the FormDemo class to respond to the POST method.

Through several examples, the reader should have a probably understanding of how Servlet responds to HTTP requests, and obtains data from the submitted form, but to build a web application, there is not enough, below, we want The conversation and lifecycle of the explanation of the WEB application is both important for building web applications.

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, Also use Method GetSession (TRUE)

(2) 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.

Let's take a simple example of the use of session // sessionexample.java import java.io. *; import javax.utilt. *; Import javax.servlet.http. *; // Import necessary packages public class SessionExample extends HttpServlet {public void doGet (HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException // doGet method implemented {response.setContentType ( "text / html"); // set the HTTP header PrintWriter out = response.getWriter (); // Get the output Writer httpsession session = request.getSession (TRUE); // Get the session object

// Print HTML marker Out.println (""); out.println (""); out.println (""); out.println (""); out.println ("");

Date create = new date (session.getcreeationTime ()); // gets the time Date Accessed = New Date (session.getlastaccessedTime ()); // Get the time of the last access to the session object Out.println ("ID " session.getid () " "); // Get this session ID and print out.println (" Created: " CREATED "); // Print session creation time OUT.Println ("Last Accessed: " accessed " "); // Print last access time session.setttribute (" UID "," 12345678 "); // Add variables in session uid = 12345678 session.setttribute (" name "," Tom "); / / Add variables in session Name = Tom

ENUMERATION E = session.gettributenames (); // Get the enumeration object of the variable name in the session (E.haASMoreElements ()) {// Traversing each variable String Name = (String) E.NEXTELEMENT (); // First Get the name string value = session.getattribute (name) .tostring (); // By the name is obtained from the session out.println (Name "=" value "") "" ")"); // Print} Out.println ("" " ); // Print HTML mark Out.println ("");}}}

The result of the servlet run is:

With the session object, the web application can save the customer's status on the server side, which will gradually experience the importance readers to build web applications. Just mentioned above, Session is just a concept, there can be many implementation methods, here we have more introduced. Because servlet itself is a very practical content, a variety of techniques, implementation, and incompetent enumeration. And many related content is not just a servlet patent. This lecture can only be introduced here, so that the reader has a conceptual understanding of servlet. Interested readers can refer to related books.

10.2.4 SERVLET lifecycle

Similar to the client's applet, servlet (here the concept of servlet is back to the most original meaning) also follows the strict lifecycle. There are three types of events in life of each servlet instance, which corresponds to three ways to wake 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 cycles, but no need to call the init method again, servlet is generally only initialized (11) When Server does not need servlet, such as when Server wants to close, Server call servlet's Destroy

From this to the content of the servlet, the reader should be able to understand the concept of the Web application through comparison of Servlet and traditional static web pages, and the appearance of web applications makes the dull web page vivid and interactive. Java is not unique in web applications, but it is quite excellent. With the cooperation of Servlet and the JSP we want to explain, you can easily build a powerful web application.

Learning Servlet, in fact, the most important thing is not Java itself, everyone has seen a servlet and a general Java program. To learn the servlet, in addition to mastering the basic servlet API, the most critical is how to grasp the entire web application from the whole, how to use the servlet reasonably, so that servlet will play the role of the dragon point when building a web site, not complex redundancy Repeatability labor. There is no big difficulty in truly writing servlet. Therefore, the reader is learning, it is best to find some large-scale examples. By reading the code, analyzing the structure, better grasping the use of servlet, know when to implement the servlet, when should you implement other methods? More appropriate, don't have to study the syntax of the servlet or some other tips. For those readers who are not familiar with the web site, there may be difficult times when they study, then our suggestion is to learn the basic Web website. It can be said that servlet is just a tool, and the idea is that readers will slowly understand in practice. When you have mature thoughts, you will learn the servlet, you will have a little familiar. 10.3 JSP Introduction

10.3.1 JSP concept

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. At present, JSP, ASP is the most extensive server-side scripting language. If the reader has already understood what the ASP has been understood, then the JSP should be very easy to understand, from the concept, JSP and ASP are the same, but only The language used is different. 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 the state 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. Here is a schematic of a JSP run:

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 This package is used.

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.4 Comparison of JSP and ASP

JSP, ASP is the most widely used server-side scripting language, which is generally said that there are many similarities in technology. Both are the technical environment provided by the web application to implement dynamic interactive web pages. Both can provide program developers to provide applications to implement applications with logically separated from the own assembly design web page. Moreover, both can replace CGI, making the website construction and development simpler and fast.

But there is still a big difference, the most essential difference is that the two are different from different technical regulations, and their implementation is different. JSP technology is based on platforms and servers, input support from a wide range of toolkits and database products. In contrast, ASP technology relies primarily on Microsoft's technical support.

From the perspective of learning, both are more than different, readers with ASP experience can be compared to learning.

10.3.5 JSP and traditional CGI comparison with Servlet, the concept of CGI is very simple, but truly writing CGI programs is not the case, it requires real skill, it must have the ability to debug the program. Write CGI is a headache that makes the programmer, it should be like this, there will be a server-side scripting language like JSP, ASP. JSP hides most of the complexity in traditional CGI programming, making server-side programming greatly simplified. At the same time, since JSP is ultimately compiled into a servlet, we can easily know that JSP efficiency is higher than CGI through the comparison of servlet and CGI.

10.3.6 Establishing a JSP Operation Environment

Generally speaking, servers that support JSP always support servlet because JSP itself requires support for servlet. The front we introduce RESIN is actually a JSP engine, and support for servlet is just part of its function. So we don't have to look for any new environment to try our JSP.

The JSP configuration in Resin is more simple relative to servlet, because it is written for JSP, you only start HTTPD and SRUN, and the JSP file in the DOC directory can be identified. Let's take a simplest example: JSP file: add.jsp 2 2 = Save this file to your doc directory, type http: // localhost: 8080 / add.jsp, Type http: // localhost: 8080 / add.jsp, at this time, if you appear The page indicates that your JSP page has already started working:

As for this simple JSP meaning in later analysis.

10.3.7 Server parameter settings

We just tried a JSP file in the default publishing directory, which is already a corresponding configuration statement in the default configuration file in RESIN. If you need to configure other directories or virtual directories, you need to manually modify the configuration file, because each JSP Server configuration method is different, here we don't have too much introduction to Resin configuration, interested readers can refer to existing Configuration statements and resin help documents.

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 comment

2. JSP comment

3. Statement

4. Expression

5. Script section

1. HTML comment

This comment can be seen by viewing the source file by viewing the source file. JSP syntax:

Example 1 Displayed in the client page source program:

Example 2 -> Displayed in the client page source program:

Description You can use any valid JSP expressions in the comments. 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. This comment can be seen by viewing the source file by viewing the source file.

2. JSP comment

JSP comments As the documentation of the JSP page, the comment is not seen by viewing the source file by viewing the source file. That is, the comment is not sent to the client.

JSP syntax:

example

Note test

Description The JSP engine does not work for JSP comments. JSP comments are neither sent to the client, nor is it displayed in the client's JSP page. Can't see when viewing the source file. Therefore, if you want to write a document instructions in the JSP page source program, JSP comments are useful. Note: In JSP comments, you cannot use -%>, but if you must use it, you can avoid it by using-% />. 3. Statement

Declare variables or methods in the JSP page scripting language

JSP syntax:

example

Description In the JSP file, one or more variables and methods can be declared at a time, and they are separated from semicolons. 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 instruction or the include instruction contains some static files, the valid range of the declaration will expand, that is, the declaration is also valid in the static file. However, if the JSP source file contains a dynamic file with instructions, the statement in the primary JSP file will not work in this dynamic file.

4. Expression

In the JSP script language, you can use any valid expressions.

JSP grammar: Example 1:

Example 2: Random Display A Number: Describe the expression for evaluation, then its value is converted into a string, and inserts a place where the 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 segment tab, the expression requires a semicolon as an end.

5. Script section

In the JSP page scripting language, a valid code snippet is included.

JSP syntax:

example 1:

Describe the plurality of variables and methods described in the script segment. Can use any effective expressions. Can use any JSP implicit objects or any objects that use tag declarations. 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.

The above introduction is the basic syntax of JSP. There are several rules of the above rules, we can easily write a general JSP file. For example, the example of our previous test RESIN has only one sentence. It is the expression of the expression, 2 2 =, the front part is the HTML text that needs to be printed directly. The Java statement is the Java statement. To return the value of the expression and print it to the client. Translated into a corresponding servlet statement, probably: Out.println ("2 2 =" (2 2))); if this statement is changed to System.Out.Println ("2 2 =" (2 2)); run on the console, then the result of running is 2 2 = 4

10.3.8 JSP Directive (2)

Here is some of the functional statements in JSP:

1. Include instruction

2. Page instruction

3. element

4.

5.

6.

7.

8.

1. Include instruction

This instruction is used to contain a file with a text or code.

JSP syntax:

Example: The content of the include.jsp file is: Random.JSP number is: Random.jsp file is:

The number of random display in random.jsp is: 2148.093521070482

Description Include instructions Insert a file containing text and code in the JSP file. 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 labels 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 Directive

Define global properties of the entire JSP page. JSP Syntax: Example: Description: The scope of the Page instruction is the entire JSP file and the JSP file with the include instruction or any static files that come in, the entire JSP file and these static files are called a "translation unit". Note: Page instruction Not applicable to any dynamic contained 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 instruction in any position of the JSP file or the file being included, its scope is entire "panning unit". However, a good designer style is often placed on the top of the file.

Language = "Java" is used 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 import.session = "true | false" in a JSP file to determine JSP Whether the 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, the session object cannot be used. 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

Transfer your client's request to an HTML file, JSP file or script segment. JSP syntax:

Example: Description: The tag will be processed from a JSP file to another file processing.

Special Note: The JSP engine is no longer executed by the code below the main 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), and the output area already has content, the use element will cause illegal exceptions. Attributes

Page = "{relativeurl |}" This property is used to set the associated URL of the file to be transferred. This URL cannot contain 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.

Take the value of the bean property to display in the result page. JSP syntax:

Example: The program code for bean is: package accessDatabase; public class readdate {private string username = "changcheng"; public string void getusername () {return username;}}

The content of the JSP file is: The value obtained from the bean is named UserName is:

The result of the execution is: obtain the value of the attribute name User from the bean: changcheng

Description: Before use, you must create or call a bean instance before use. The label is a getxxx () method for obtaining a Javabeans property value, equivalent to a certain attribute in the bean.

Property: Name = "beanInstanceName" in the name of the bean instance declared in the label. Property = "PropertyName" bean name.

Description: In the above example, username must be the attribute in the bean (the bean) in the bean () method, otherwise it will be wrong when it is compiled.

5.

In the JSP file, there is a static or dynamic file. JSP syntax? Lt; jsp: include Page = "{relativeURL |}" flush = "true" />

example:

Property: Tags Allows you to include a 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. The label 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 |}" 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 plug-in to the client to execute Applet or beanjsp syntax: type = "bean | applet" code = "classfilename" codebase = "classfiledirectoryName" [name = "instanceename"] [Archive = "uritoarchive, ..."] [ align = "bottom | top | middle | left | right"] [height = "displayPixels"] [width = "displayPixels"] [hspace = "leftRightPixels"] [vspace = "topBottomPixels"] [jreversion = "JREVersionNumber | 1.1" ] [NSPLUGINURL = "URLTOPLUGIN"] [iePluginURL = "URLTOPLUGIN"]> [[] ] [Text Message for User] Example:

Unable to load applet

Elements are delivered 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 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 The position of the image displayed in the BEAN is relative to such rows in the JSP result page, the row is the row included in the JSP file. 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.1nspluginURL = "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 ​​passed to Applets or Beans. To deliver multiple parameters and values, you can use multiple tags in elements. Applets get parameters through java.applet.applet.getParameter method.

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

7.

Set one or more attribute values ​​for the bean.

JSP syntax: {property = "*" | Property = "protyname" [param = "parametername"] | Property = "PropertyName" value = "{string |}"} />

Example: Property: Tags are used to set the attribute values ​​in the JavaBean component. Before you use the element, you must use the label to declare this bean. The value of the Name must be consistent with the value of the ID in .

The value of the general setting attribute has three methods: (i) using methods, you can use all values ​​in the user request (these values ​​are typically the value of the elements in the client form, and as parameters are stored in the Request object) and beans. Assignment of the property matches. 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, assign values ​​to assign values ​​or unpacked attributes with a specific value in the request object and the property in the bean.

(iii) Use the method, the value of the value of the string or the expression of the expression is directly set to the attribute of bean

Attributes and usage: name = "BeanInstanceName" instance name of the bean created or called in the label. Name's value must be consistent with the value of the iD.

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 that specifies the name and the range of use.

JSP syntax: id = "beanting" scope = "Page | Request | Session | Application" {class = "package.class" | type = "package.class" | class = "package.class" type = "package.class" "Beanname =" {package.class |} "type =" package.class "} {/> |> other tags} example:

Property: The label 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 label.

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.

JSP's basic thinking and servlet is exactly the same. The grammar listed above is just a tool to achieve these ideas, and many of them are related to some of the advanced technologies in JSP, such as bean, plugin, etc., readers later In practice, you can experience it. Here we also got a small example of translation from JSP to servlet, readers can reach the relationship between JSP and Servlet from the Central.

10.3.9 Hidden objects in JSP (1)

Since JSP is an embedded language, you cannot express some must pass some of the necessary parameters, such as the Request object, Response object, etc., so a few implicit objects are provided in the JSP specification 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 hidden objects include Application, Session, Request, Response, Out, Page, Exception, PageContext

1. Session object

2. APPLICATION object

3. REQUEST object

4. Respose object

5. Out object

6. Page object

7. Exception object

8. PageContext object

1. Session object

The front in the servlet section has been mentioned that when the customer first access the web server publishing directory (a web server has a web file under one or more "released directory"), the web server automatically creates a session object and It assigns unique ID numbers, customers can save some information they need to the session object for use. The session object refers to an object obtained by a GetSession method. In JSP, it is an implicit object, and the reader of the SESSION object can see Servlet API2. APPLICATION object

When the web server starts, the web server will automatically create 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. REQUEST object

The REQUEST object is mainly 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 concrete method of using the Javax.Servlet.httpservletRequest to see the servlet API.

4. Respose object

The Respose 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. It is 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

The 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. See the Java 2 API for specific usage methods.

7. Exception object

The Exception object is automatically generated when the JSP page has an exception or error occurs during the execution.

Once the current page is used, you can use the Exception object to find the page error message. The type of Exception object is: java.lang.exception class.

The common method of Exception objects is:

String getMessage () Returns the error message of the page, if not, return NULL

Void PrintStackTrace () Prints and displays the current Exception object and its execution trajectory in the form of a standard error output stream.

See the Java 2 API for specific usage methods.

8. PageContext object

The PageContext object is equivalent to the container of the current page, you can access all objects of the current page. The base class of the PageContext object is: javax.servlet.jsp.pageContext class. PageContext object common method: httpsession getSession () gets the session object of the current page. ServletRequest getRequest () gets the Request object of the current page. ServletResponse getResponse () gets the Response object of the current page. ServletContext GetServletContext () gets the Application object of the current page. ServletConfig GetServletConfig () gets the CONFIG object of the current page. Object getPage () gets the PAGE object of the current page. JSpWriter getOut () gets the OUT object of the current page. Exception getException () gets the exception object of the current page. Void SetAttribute (String VariabelName, Object ObjectName) Saves Object ObjectName to pageContext. Object GetAttribute (String Variablename)

Get the data saved in the PageContext object. Returns null. Void Removettribute (String Variablename) if the parameter variablename does not exist in the current session.

Delete the object that specifies the name Variablename in PageContext. If the object name does not exist, no operation is performed.

See the Servlet API for specific methods.

10.3.9 Hidden objects in JSP (2)

Let's take a simple example to illustrate the basic preparation methods of JSP, and the specific application skills need to be reader to practice. This example is the example of obtaining data from the form when explaining servlet, and prints to the client client. The static HTML file used in the original example, just change the action to our new In response to file jsptest.jsp, the reader mainly views the difference between JSP files and the original Java file.

1. Static HTML file OurForm..html

2. JSP file: jsptest.jsp

1. Static HTML file Ourform.html

Our Form

Name:

Gender: Male Female

2. JSP file: jsptest.jspdata you posted

Your name:

Your gender:

The execution result of this example is the same as before. On the basis of the previous servlet analysis, the reader understands that this example should have no problem, here is not more analyzed for grammar. Let's take a look at the features of this example.

First, the most obvious point is that the file has become shorter after using JSP, the format is clearer, which is also a most important reason to use JSP, using servlets to print a lot of HTML statement is very bad, while JSP's main body HTML, embedded Java statement is only responsible for the dynamic effect, so it is more convenient than servlet. Below we will analyze how to make servlets and JSPs to cooperate with each other, take a better application, and achieve better application results.

The other is that when JSP is used, it is not necessary to configure each file separately, as long as it is an extension JSP, the JSP engine will automatically recognize. The servlet is required to be configured to use, which is also safe to consider, directly access. Theclass file is not allowed, because it is not possible to be a legal servlet. JSP is a compiled text, even if it is compiled into a servlet, it must also comply with the servlet specification, although it may not meet the HTML syntax, it is safe.

There is also a Chinese issue here to simplify, and local Chinese strings do not require encoding conversions to be displayed in the client. One of the key points here is to set the page attribute at the head, where charset = GB2312 tells the JSP engine local code is GB2312, and then the JSP engine will automatically convert, do not need to be handmade. However, it is not to say that it is eternal, and the Chinese problem still exists during the JSP page. Readers will be able to have the problem of transferring any Chinese issues, so readers should be It is basically understanding Chinese issues, which is one of them.

At this time, if we change the static page GET to POST? We will find that it is not like httpservlets, this JSP can still work normally because JSP's implementation is servlet at the lowest layer, but it is different from httpservlet, so it does not exist the classification problem of the client request, it There is only one _jspservice (httpservletRequest request, the httpservletResponse response method is implemented by the JSP engine, so writing JSP does not have to care about so many abrasions as servlets.

Here is the temporary java file generated by Resin. It is the example of the above example to convert it into a servlet. Interested readers can read it. If you really read it, you will benefit.

// RESIN (TM) generated jsp package _jsp; import java.io. *; import javax.servlet. *; Import javax.servlet.jsp. *; Import javax.servlet.jsp.tagext. *; Import javax.servlet. Http. *;

public class _JSPtest__jsp extends com.caucho.jsp.JavaPage {public void _jspService (javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws IOException, javax.servlet.ServletException {javax.servlet.jsp.PageContext pageContext = com.caucho.jsp.QJspFactory.create () getPageContext (this, request, response, null, true, 8192, true);. javax.servlet.jsp.JspWriter out = (javax.servlet.jsp.JspWriter) pageContext .getOut (); com.caucho.jsp.ByteWriteStream _jsp_raw_out; _jsp_raw_out = (com.caucho.jsp.ByteWriteStream) out; javax.servlet.ServletConfig config = getServletConfig (); javax.servlet.Servlet page = this; javax.servlet .http.HttpSession session = pageContext.getSession (); javax.servlet.ServletContext application = pageContext.getServletContext (); try {_jsp_raw_out.write (_jsp_string0, 0, _jsp_string0.length); String name = request.getParameter ( "name" String sex = request.getParamet ER ("SEX"); _jsp_raw_out.write (_jsp_string1, 0, _jsp_string1.length); out.print ((name)); _jsp_raw_out.write (_jsp_string2, 0, _jsp_string2.length); if (Sex.Equals ("1 ")) Out.print (" male "); else out.print (" female "); _ jsp_raw_out.write (_jsp_string3, 0, _jsp_string3.length);} catch (exception e) {pageContext.HandlePageException (e);} Finally {jspfactory.getDefaultFactory (). ReleasePageContext (PageContext);}}

Private java.util.arraylist_caucho_depends; private java.util.arrayList_caucho_cache; private com.caucho.java.Linemap_caucho_line_map

public boolean _caucho_isModified () {if (! com.caucho.util.CauchoSystem.getVersionId () = -1983231406) return true; for (int i = 0; i <_caucho_depends.size (); i ) {com.caucho.jsp .Depend = (com.caucho.jsp.depend) _Caucho_depends.get (i); if (depend.ismodified ()) return true;} returnaf_caucho_lastmodified () {return 0;}

Public com.caucho.java.linemap _caucho_getlinemap () {return _Caucho_Line_map;

Public void _caucho_init (httpservletRequest Req, httpservletResponse res) {res. setcontenttype ("text / html; charset = GB2312");}

public void init (ServletConfig config, com.caucho.java.LineMap lineMap, com.caucho.vfs.Path pwd) throws ServletException {super.init (config); _caucho_line_map = new com.caucho.java.LineMap ( "_ JSPtest__jsp.java "," /Jsptest.jsp "; _caucho_line_map.add (1, 1); _Caucho_Line_Map.Add (1, 28); _Caucho_Line_Map.Add (9, 29); _Caucho_Line_Map.Add (16, 33); _Caucho_Line_Map.Add ( 20, 35); _Caucho_depends = new java.util.ArrayList (); _Caucho_depends.add (new com.caucho.jsp.depend (pwd.lookup ("/ d: / d: / d: / D: / D: / D: / D: / D: / D: / D: / D) ), 996991110000L));

private static byte [] _jsp_string0; private static byte [] _jsp_string1; private static byte [] _jsp_string2; private static byte [] _jsp_string3; static {try {_jsp_string0 = "/ r / n / r / n / r / n / r / N / R / N / R / N / R / N

Data you posted / r / n ".GETBYTES (" GB2312 "); _jsp_string1 =" / r / n / r / n ".GetBytes (" GB2312 "); _jsp_string2 = "/ r / n / r / n / r / n your gender: / r / n" .GetBytes ("GB2312"); _JSP_STRING3 = "/ R / N / R / N / R / N / R / N / R / N ".GetBytes (" GB2312 ");} catch (unsupportEncodingexcection e) {E.PrintStackTrace ();}}} This section has been explained, and readers should have a conceptual understanding of JSP. It should be able to write simple JSP files. If you are not very clear about some concepts, you don't have to worry, you will have a deeper experience. Below we will discuss the relationship between JSP and Servlet, hoping to help Readers better understand servlet and jsp.

10.4 JSP and Servlet combination

As we have already introduced two different web development tools of servlet and JSP, they are from Java, so in nature is the same, but the form is different, but for the development program, the differences in form are often very important. Because it often has a great impact on development efficiency. So it is precisely because of the form of forms, making their application fields greatly.

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. Below is a schematic of the mode 2:

Which model used in the construction of the Web is very important, only a large number of experiences can make the correct and efficient choice. In short, the website is not only technically problem, and the overall plan is very important. Readers should pay more attention to the essence of ideas while learning JSP and Servlet, and technology is time, but thought is always valuable.

[本 讲 小]

This lecture mainly explains the basic concepts of servlet and JSP, basic syntax. The purpose of this lecture is not to explain the details of servlet, JSP, but hopes to give readers a conceptual understanding. Laying a foundation for the reader after learning Java-based website development.

This brief introduces the basic concept of servlet and how to write simple servlets, and how to configure RESIN to build a simple debug environment. Heavy emphasized the class level of the servlet, and the simmonization of the servlet, httpservlet, JSP.

Then, wearing a servlet, we introduced the writing of JSP. Since JSP is implemented with servlet in the underlying, it is nothing difference with the servlet, so this part mainly focuses on the syntax of JSP and the implicit variables in JSP. It mainly plays a reference role, and readers can query when they are used. Finally, through an example, it is very important to compare the Similarities and differences. This is a very important part of the reader, should understand.

At the end of this lecture, we list two JSP working patterns, analyzed the occasions applicable, readers can make a little browsing, and there is a great help to future practices.

This lecture process analyzes the Chinese issues of servlet and JSP, and solutions. It is also useful when developing a Chinese website.

Servlet and JSP are technically strong technologies, and there is a lot of content here. There is no way to cover it. The reader can refer to books, truly understand and master the essence of these two technologies from practice.

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

New Post(0)