About Java servlet Programming Application Basics Analysis

Source: Internet
Author: User
Tags abstract command line html form http post http request implement version microsoft iis
Servlet| programming I. Overview

A servlet is a platform-and protocol-independent, server-side Java application that generates dynamic Web pages.

A servlet is a server-side Java application located inside a Web server, unlike a traditional Java application that starts from the command line, which is loaded by a Web server that must contain a Java virtual machine that supports the servlet.

Java Servlet comparison with applets:

Similarities and differences:

* They are not standalone applications and do not have the main () method.

* They are not invoked by a user or programmer, but by another application (container).

* They all have a life cycle that contains the init () and Destroy () methods.

The difference:

* Applet has a good graphical interface (AWT), with the browser, running on the client.

* The Servlet does not have a graphical interface to run on the server side.

Comparison of Java Servlet and CGI (Common Gateway Interface):

Compared to traditional CGI and many other CGI-like technologies, the Java servlet is more efficient, easier to use, more powerful, more portable, and less expensive to invest. In the course of future technology development, the servlet may completely replace the CGI.

* Efficient

In traditional CGI, each request starts a new process, and if the CGI program itself is executing for a short time, the overhead of starting the process is likely to exceed the actual execution time. In the servlet, each request is handled by a lightweight Java thread (rather than a heavyweight operating system process).

In traditional CGI, if there are n concurrent requests for the same CGI program, the CGI program's code is repeatedly loaded n times in memory, and for the servlet, the request is n threads, and only one servlet class code is required. In terms of performance tuning, the servlet also has more options than CGI.

* Convenient

The servlet provides a number of utility routines, such as automatically parsing and decoding HTML form data, reading and setting HTTP headers, processing cookies, tracking session state, and so on.

* Strong function

In the servlet, many tasks that are difficult to accomplish with traditional CGI programs can be done easily. For example, a servlet can interact directly with a Web server, whereas a normal CGI program cannot. The servlet can also share data between programs, making it easy to implement features such as database connection pooling.

* Good portability

The servlet is written in Java and the Servlet API has perfect standards. Therefore, the servlet written for iplanet Enterprise server can be ported to Apache, Microsoft IIS, or WebSTAR without any substantial changes. Almost all mainstream servers support the servlet directly or through Plug-ins.

* Save on Investment

Not only are there a lot of inexpensive and even free web servers for personal or small-scale web sites, and for existing servers, if it doesn't support a servlet, adding that part is often free (or requires very little investment).

Comparison of Java Servlet and JSP (JavaServer Pages):

JavaServer Pages (JSP) is a common static HTML and Dynamic HTML hybrid coding technology, JSP does not add any nature can not be implemented in the Servlet function. However, it is more convenient to write static HTML in the JSP without having to use the PRINTLN statement to output each line of HTML code. More importantly, with the separation of content and appearance, the tasks of different natures in page making can be easily separated: for example, HTML design by the page designer, while leaving room for the servlet programmer to insert dynamic content.

Java Servlet API 2.2 Introduction

The Java Servlet API 2.2 classes and interfaces comprise two Java packages, namely: Javax.servlet and Javax.servlet.http (also including javax.servlet.jsp packages, not covered in this article).

The Javax.servlet package provides the servlet interface necessary to control the servlet lifecycle, which you must implement when writing a servlet.

The Javax.servlet.http package provides abstract classes and generic tool classes that derive from the servlet interface specifically for processing HTTP requests. All Servlet objects implement the Servlet interface, most often as javax.servlet.GenericServlet and javax.servlet.http.HttpServlet that have implemented the Servlet interface Subclasses of these two abstract classes to implement the Servlet interface indirectly.

classes and interfaces defined by the Javax.servlet package:

Interface RequestDispatcher

Defines an object that accepts requests from a customer and sends the request to any specified resource on the server, such as a servlet, JSP, or HTML file.

Interface Servlet

Defines the methods that all Servlet must implement.

Interface ServletConfig

Defines a servlet config object that is used by the servlet engine to pass information to the servlet when the servlet is initialized.

Interface ServletContext

A series of methods are defined so that the servlet communicates with the environment in which it is running.

Interface ServletRequest

Defines the object used to pass customer request information to the servlet.

Interface Servletresponse

Defines an object that is used by the servlet to send a response to the customer.

Interface Singlethreadmodel

Used to ensure that the servlet processes only one request at any one time.

Class Genericservlet

Inherits the Servlet interface and defines a generic, protocol-independent servlet.

Class ServletInputStream

Defines an input stream for binary data from which the servlet reads customer requests.

Class Servletoutputstream

Defines an output stream that is used by the servlet to send binary data to the customer.

Class Servletexception

Defines an exception that can be thrown when a servlet encounters a problem.

Class Unavailableexception

Defines an exception that is used by the servlet to indicate that it is permanently or temporarily unavailable.

classes and interfaces defined by the Javax.servlet.http package:

Interface HttpServletRequest

Inherits the ServletRequest interface and provides request information for HttpServlet.

Interface HttpServletResponse

Inherits the Servletresponse interface and provides support for HttpServlet output response information.

Interface HttpSession

Provides support for maintaining the session state of an HTTP user.

Interface Httpsessionbindinglistener

Enables an object to be notified when it joins or deletes from a session.

Interface Httpsessioncontext

Defined by Servlet 2.1, the object is not supported in the new version.

Class Cookie

Using cookie technology with the servlet

Class HttpServlet

Defines an abstract class that inherits Genericservlet abstract classes and should be httpservlet inherited.

Class Httpsessionbindingevent

Defines an object that receives a handle to an object that implements the Httpsessionbindinglistener interface when it is joined or deleted from the meeting//session

Class Httputils

Provides a range of ways to easily write HttpServlet.

The following describes the HTTP servlet application programming interfaces provided by Javax.servlet.http.

The HTTP Servlet uses an HTML table to send and receive data. To create an HTTP Servlet, extend the HttpServlet class, a subclass of the genericservlet of an HTML table in a specialized way. HTML forms are defined by and tags. A form typically contains input fields, such as text input fields, check boxes, radio buttons, and select lists, and buttons for submitting data. When submitting information, they also specify which servlet (or other program) the server should perform. The HttpServlet class contains methods such as Init (), Destroy (), service (), and so on. where the Init () and Destroy () methods are inherited.

(1) Init () method

In the lifetime of the Servlet, only one init () method is executed. It is executed when the server is mounted in the Servlet. You can configure the server to enter the servlet into the servlet for the first time on the boot server or client. Regardless of how many clients access the Servlet, init () is not repeated.

The default init () method is usually compliant, but it can also be overridden with a custom init () method, typically managing server-side resources. For example, you might write a custom init () to only mount a GIF image at a time, and improve the performance of the Servlet returning a GIF image and a request that contains multiple clients. Another example is the initialization of a database connection. The default init () method sets the servlet initialization parameters and starts the configuration with its ServletConfig object arguments, so all Servlet overrides of the Init () method should call Super.init () to ensure that these tasks are still performed. Before calling the service () method, make sure that the init () method is complete.

(2) Service () method

The Ervice () method is the core of the Servlet. Whenever a client requests a HttpServlet object, the service () method of the object is invoked and passed to the method a request (ServletRequest) object and a response (Servletresponse) object as an argument. The service () method already exists in HttpServlet. The default service function is to invoke the DO function corresponding to the method of the HTTP request. For example, if the HTTP request method is get, the doget () is invoked by default. The servlet should overwrite do functionality for the HTTP methods supported by the servlet. Because the Httpservlet.service () method checks whether the request method calls the appropriate processing method, you do not have to overwrite the service () method. Just overwrite the appropriate do method.

The DoPost () method is invoked when a customer issues an HTTP POST request through an HTML form. The parameters associated with the POST request are sent from the browser to the server as a separate HTTP request. You should use the Dopost () method when you need to modify server-side data.

The Doget () method is invoked when a customer issues an HTTP GET request through an HTML form or requests a URL directly. The parameters associated with the GET request are added to the URL and sent along with the request. The Doget () method should be used when server-side data is not modified.

The servlet response can be of the following types:

An output stream that the browser interprets based on its content type (such as text/html).

An HTTP error response, redirected to another URL, servlet, JSP.

(3) Destroy () method

The Destroy () method executes only once, that is, when the server is stopped and the servlet is uninstalled. Typically, the Servlet is closed as part of the server process. The default Destroy () method is usually compliant, but it can also be overridden, typically managing server-side resources. For example, if the servlet accumulates statistics at run time, you can write a destroy () method that is used to save statistics in a file when the servlet is not mounted. Another example is to close the database connection.

When the server uninstalls the Servlet, the Destroy () method is invoked after all service () method calls have been completed, or after a specified interval. A servlet may produce additional threads when it runs the service () method, so make sure that when the destroy () method is invoked, the threads are terminated or completed.

(4) Getservletconfig () method

The Getservletconfig () method returns a ServletConfig object that is used to return initialization parameters and ServletContext. The ServletContext interface provides environmental information about the servlet.

(5) Getservletinfo () method

The Getservletinfo () method is an optional method that provides information about the servlet, such as author, version, and copyright.

The request and response objects are required as parameters when the server invokes the Sevlet service (), Doget (), and Dopost () three methods. The Request object provides information about the request, and the response object provides a means of communication that returns the response information to the browser.

The related classes in the Javax.servlet package are servletresponse and ServletRequest, while the related classes in the Javax.servlet.http package are httpservletrequest and HttpServletResponse.

The Servlet communicates with the server through these objects and eventually communicates with the client. The Servlet can learn about the client environment, the server environment, and all the information provided by the client by invoking the method of the Request object. The Servlet can call the response object's method to send a response that is ready to be sent back to the client.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.