Java servlet programming and application (1)

xiaoxiao2021-03-06  91

I. Overview

Servlet is a Java application independent of platform and protocol, which can generate a dynamic web page.

Servlet is a Java application located within the server side within the web server. Unlike the traditional Java application that is launched from the command line, the servlet is loaded by the web server, which must contain Java virtual machines that support servlet.

Comparison of Java Servlet and Applet:

Similar place:

* They are not independent applications, there is no main () method.

* They are not called by the user or programmer, but is called another application (container).

* They have a survival cycle, including init () and destroy () methods.

the difference:

* Applets have a good graphical interface (AWT), run with the browser, run on the client.

* Servlet does not have a graphical interface and run on the server.

Comparison of Java Servlet and CGI (Common Gateway Interface:

Compared to traditional CGIs and many other similar CGI technologies, Java servlets have higher efficiency, easier to use, more powerful, better portability, saving investment. In the future technology development, servlets may completely replace CGI.

* Efficient in traditional CGIs, each request is to start a new process. If the CGI program itself is shorter, the overhead required to start the process is likely to exceed the actual execution time. In the servlet, each request is processed by a lightweight Java thread (not the heavyweight operating system process).

In the traditional CGI, if there is a request to the same CGI program, the code of the CGI program is repeated in memory in memory; for servlet, the request is N thread, only one servlet Class code. Servlet has more options than CGI in terms of performance optimization.

* Convenient servlets provide a large number of utility routines, such as automatically resolve and decode HTML form data, read, and set HTTP headers, process cookies, track session status, etc.

* Powerful

In servlet, many tasks that use traditional CGI programs are easy to complete. For example, servlets can interact directly with the web server, while ordinary CGI programs cannot. Servlets are also capable of sharing data between individual programs, making it easy to implement the functions such as database connection pools.

* Good portability

Servlet is written in Java, servlet API has a perfect standard. Therefore, servlet written for IPlanet Enterprise Server does not require any substantial changes to Apache, Microsoft IIS or WebStar. Almost all mainstream servers support the servlet directly or through the plugin.

* Save investment Not only there are many cheap or even free web servers available for personal or small-scale websites, and for existing servers, if it does not support servlet, add this part of the function is often free (or only need Extreme investment).

Comparison of Java Servlet and JSP (JavaServer Pages):

JavaServer Pages (JSP) is a technique that implements normal static HTML and dynamic HTML mixed encoding, and JSP does not increase any functionality that is inherently unable to use servlet. However, writing static HTML in JSP is more convenient, do not have to use the PrintLn statement to output each line HTML code. More importantly, with the separation of content and appearance, the task of different nature in page production can be conveniently separated: For example, the page designer is HTML design, and the space for the servlet programmer is inserted into the dynamic content. Java Servlet API 2.2 Introduction

The class and interface of Java Servlet API 2.2 make up two Java packets, namely: javax.servlet and javax.servlet.http (also include javax.servlet.jsp package, not within this article discussions).

The Javax.Servlet package provides the Servlet interface necessary to control the Servlet lifecycle, which must be implemented when writing servlets.

The Javax.Servlet.htttp package provides an abstract class and a general tool class that derived from the servlet interface to process the HTTP request. All servlet objects are implemented as a servlet interface. In most cases, the servlet interface is indirectly implemented as a javax.servlet.GenericServlet that has implemented servlet interfaces.

Javax.Servlet package defined classes and interfaces:

Interface requestDispatcher

/ / Define an object to be requested from the customer and send the request to any specified resource on the server, such as a servlet, jsp or html file.

Interface servlet

// Define how all servlets must implement.

Interface servletconfig

/ / Define the Servlet Config object, transfer information to servlet when the servlet engine is initialized in servlet.

Interface servletContext

// Define a range of methods to communicate with the servlets.

Interface servletRequest

/ / Define an object to pass the customer request information to the servlet.

Interface servletResponse

// Define an object, by servlet to send a response to the customer.

Interface SingLethreadModel

// Used to ensure that servlet at any time, only processes only a request.

Class genericServlet

// Inherited the servlet interface, define a universal, a servlet that is not related to the protocol.

Class ServletInputStream

// Define an input stream for binary data to read the customer request from the servlet.

Class ServletOutputStream

// Define an output stream for transmitting binary data to customers by servlet.

Class ServleTexception

// Define an exception that can be thrown when the servlet encounters problems.

Class UnavailableException

// Define an exception that is used by servlet to indicate it forever or not available.

Javax.servlet.http package definition classes and interfaces:

Interface httpservletRequest

// Inherited the servletRequest interface to provide information for the HTTPSERVLET.

Interface httpservletresponse

// Inherited the servletResponse interface and supports the HTTPSERVLET output response information. Interface httpsession

/ / Provide support for the session state of the HTTP user.

Interface httpsessionBindingListener

// Make a notification when an object is added to a session or from a session.

Interface httpsessionContext

// is defined by servlet 2.1, which is not supported in the new version.

Class cookie

// Use a cookie technology in servlet

Class httpservlet

// Define an abstract class that inherits the GenericServlet abstract class, which should be inherited by httpservlet.

Class httpsessionBindingEvent

// Define an object that receives a handle of such object when an object that implements the HTTPSessionBindingListener interface is added to a session or from //.

Class httputils

// Provide a series of methods for easy to write HTTPSERVLETs.

The following mainly introduces the HTTP Servlet application programming interface provided by javax.servlet.http.

HTTP Servlet uses an HTML form to send and receive data. To create an HTTP Servlet, extend the HTTPServlet class, which is a subclass of the genericServlet for the HTML table with a dedicated method. The HTML form is defined by

and tag. The form is typically included in the input field (such as a text input field, checkbox, radio button, and selection list) and buttons for submitting data. When submitting information, they also specify which servlets (or other programs) should be executed. The HTTPSERVLET class contains init (), destroy (), service (), etc. Wherein init () and destroy () methods are inherited.

(1) init () method

In the life period of the servlet, only the init () method is performed. It is performed when the server is loaded with a servlet. You can configure a server to load servlet when you start the server or client to access the servlet. No matter how many client access servlets, INIT () will not be repeated.

The default init () method is usually in line with the requirements, but can also be customized to override it, typically manage server-side resources. For example, a custom init () can be written only for one GIF image, improve the performance of servlet to return to GIF images and the performance of multiple client requests. Another example is to initialize the database connection. The default init () method sets the initial parameters of the servlet, and uses its servletconfig object parameters to start the configuration, so all servlets that override the init () method should call super.init () to ensure that these tasks are still executed. Before calling the service () method, you should ensure that the init () method has been completed.

(2) Service () method

The service () method is the core of the servlet. Whenever a customer requests an HTTPSERVLET object, the service () method of the object is called, and it is passed to this method a "servletRequest) object and a" SERVLETRESPONSE) object as a parameter. The service () method already exists in the HTTPServlet. The default service function is to call the corresponding DO functionality corresponding to the HTTP request. For example, if the HTTP request method is GET, DOGET () is called by default. The servlet should overwrite the DO function for the HTTP method supported by servlet. Because the httpservlet.service () method checks if the request method is called, it is not necessary to override the service () method. Just override the corresponding DO method. When a client issues an HTTP POST request via an HTML form, the dopost () method is called. Parameters associated with the POST request are sent from the browser to the server as a separate HTTP request. DOPOST () method should be used when you need to modify the data of the server. When a customer issues an HTTP GET request or directly requests a URL via an HTML form, the doget () method is called. The parameters associated with the GET request are added to the URL and send it with this request. You should use the doget () method when the server is not modified. The response of the servlet can be the following types:

An output stream, the browser explained according to its content type (such as Text / HTML).

An HTTP error response, redirect to another URL, Servlet, JSP.

(3) DESTROY () method

The Destroy () method is only performed once, that is, the server is stopped and the servlet is unloaded. Typically, servlet is turned off as part of the server process. The default destroy () method is usually in line with requirements, but it can also overwrite it, typically manage server-end resources. For example, if the servlet accumulates statistics at runtime, a DESTROY () method can be written, which is used to save the statistics in the file when the servlet is not loaded. Another example is to turn off the database connection.

When the server unresses the servlet, the destroy () method will be called after all service () method calls or after the specified time interval. A servlet may generate other threads when running the service () method, so confirm that when the destroy () method is called, these threads have terminated or completed.

(4) GetServletConfig () method

GetServletConfig () method returns a servletconfig object that is used to return to initialization parameters and servletContext. The servletContext interface provides environmental information about servlet.

(5) GetServletInfo () method

GetServletInfo () method is an optional method that provides information about servlet, such as author, version, copyright. When the server calls the sevlet service (), doget (), and dopost (), "request" and "response" are required as parameters. The "Request" object provides information about the request, and the "Response" object provides a communication path to the browser to the browser in response. The related class in the Javax.Servlet package is ServletResponse and ServletRequest, and the related class in the Javax.Servlet.http package is httpservletRequest and HttpservletResponse. Servlet communicates with the server through these objects and eventually communicates with the client. The servlet can know the client environment, the information of the server environment, and all information provided by the client. The servlet can call the "Response" object to send a response, which is ready to send back the client.

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

New Post(0)