Java Web development BASICS (2)-servlet Introduction

Source: Internet
Author: User

Servlet is a Java program that uses Java Servlet applications to design interfaces and related classes and methods.

Servlet expands server capabilities by creating a framework and uses the request-response mode to provide web services. When the client sends a request to the server, the server sends the request information to the servlet. The servlet generates the response content and sends it to the server. Then, the server returns the response to the client.

1. servlet functions:
1. Create and return a complete HTML page containing dynamic content based on the nature of the customer request.

2. Create an HTML page (HTML segment) that can be embedded in an existing HTML page ). Communicates with other server resources (such as files, databases, applets, and Java applications.

3. Accept input from multiple clients and broadcast the results to multiple clients. For example, servlet can be a game server with multiple participants.

4. Use MIME type to filter data for special processing, such as image conversion and server (including SSI ).

Ii. servlet container:
Handles customer requests, sends requests to servlet, and returns results to the customer. The actual implementation of containers of different programs may change, but the interfaces between containers and servlets are defined by Servlet APIs, this interface defines the servlet container's method to be called on the servlet and the object class passed to the servlet.

3. servlet lifecycle:

1. Create an instance of servlet in the servlet container
2. The Container calls the init () method of the instance.
3. If the container has a request for this servlet, call the service () method of this instance.
4. The Container calls its destroy () method before destroying the instance.
Once a servlet is requested, there is no way to prevent the container from executing a complete lifecycle.

Iv. servlet API


1. servlet interface:

Public interface Servlet
Its lifecycle is defined by the javax. servlet. servlet interface. When writing a servlet, you must directly or indirectly implement this interface. Generally, it tends to be indirect: Derived from javax. servlet. genericservlet or javax. servlet. http. httpservlet.

When implementing the servlet interface, you must implement the following five methods:
Init ():
Public void Init (servletconfig config) throws servletexception

Once the servlet is instantiated, the container calls this method. The container traditionally provides this method to a servletconfig object, so that the servlet instance can save the configuration data related to the container for future use. If this method does not end normally, a servletexception will be thrown. Once this exception is thrown, the servlet will no longer execute it, and subsequent calls to it will cause the container to reload it and run this method again. The interface specifies that this method can be called only once for any servlet instance. Before any request is sent to the servlet, this method can be completed without throwing an exception.

Service ():
Public void Service (servletrequest req, servletresponse res) throws servletexception, ioexception

This method can be called to process user requests only after successful initialization. The previous parameter provides methods and fields for accessing the initial request data, and the other provides the servlet method for constructing the response.

Destroy ():
Public void destroy ()

The container can terminate the servlet service at any time. The container must give the Service () thread enough time to end the execution before calling this method. Therefore, the interface specifies that destroy () is not executed when the service () is being executed.

Getservletconfig ():
Public servletconfig getservletconfig ()

During servlet initialization, the container passes in a servletconfig object and stores it in the servlet instance. This object allows access to two items: the initialization parameter and the servletcontext object, the former is usually specified by the container in the file, which allows you to transmit scheduling information to the sevrlet at runtime, and the latter provides container information for the servlet. This method allows the servlet to obtain the object and configuration information at any time.

Getservletinfo ():
Public String getservletinfo ()

This method returns a String object containing Servlet Information, such as developer, creation date, and description information. This method can also be used for containers.

2. httpservlet class
This class extends the genericservlet class and provides more http-related implementations for servlet interfaces.

Service ():
Protected void Service (httpservletrequest req, httpservletresponse res) throws servletexception, ioexception

Public void Service (httpservletrequest req, httpservletresponse res) throws servletexception, ioexception

This method is used as the HTTP request distributor and cannot be overloaded at any time. When a request arrives, the Service () method determines the request type (get, post, Head, options, delete, put, trace ), and distribute the request to the corresponding processing methods (doget (), dopost (), dohead (), dooptions (), dodelete (), doput (), dotrace ()) each do method has the same form as the first service. To respond to specific types of HTTP requests, we must reload the corresponding do method. If the servlet receives an HTTP request without reloading the corresponding do method, it returns a standard HTTP Error indicating that this method is unavailable to this resource.

Getlatmodified ():

Protected long getlastmodified (httpservletrequest req)
This method returns the latest servlet modification time dependent on January 1, 1970 00:00:00 GMT time in milliseconds. By default, a negative number is returned, indicating that the time is unknown. When processing a GET request, you can call this method to know the latest modification time of the servlet, and the server can decide whether to remove the result from the cache.

3. httpservletrequest Interface
Public interface httpservletrequest extends servletrequest

All objects that implement this interface (for example, HTTP request objects passed from the servlet container) can allow the servlet to access the data of all requests through its own method. The following are some basic methods for getting form data.

Getparameter ()
Public String getparameter (string key)
This method tries to locate the corresponding parameter based on the keyword in the query string and return its value. If multiple values exist, the first value in the list is returned.

Getparametervalues ():
Public String [] getparametervalues (string key)
If a parameter can return multiple values, such as a set of check boxes, you can use this method to obtain all values of the corresponding parameter.

Getparameternames ():
Public enumeration getparameternames ()
This method returns an enumeration object that contains a list of all parameter names of the corresponding request.

4. httpservletresponse Interface
Public interface httpservletresponse extends servletresponse
The servlet container provides an object that implements this interface and passes it to the servlet through the Service () method. Through this object and its method, servlet can modify the response header and return results.

Setcontenttype ():
Public void setcontenttype (string type)
Before sending a response to the caller, you must use this method to set the MIME type of the HTTP response. It can be any valid MIME type. When HTML is returned to the browser, it is of the "text/html" type.

Getwriter ():
Public printwriter getwriter () throws ioexception
This method returns the printwriter object and the servlet result as text to the caller. The printwriter object automatically converts the Unicode characters in Java to the correct encoding for the client to read.

Getoutputstream ():
Public servletoutputstream getoutputstream () throws ioexception
This method returns the servletoutputstream object, which is a subclass of Java. Io. outputstream. This object sends binary data to the customer.

Setheader ():
Public void setheader (string name, string value)
This method is used to set the HTTP Response Header sent back to the customer. There are some quick methods to change some common response headers, but sometimes you need to call this method directly.

Servlet performance and efficiency
A servlet is initialized only once and executed multiple times. Therefore, extremely small inefficiency will also have a great impact as time increases. In code, you need to consider the use of string objects. If you need to use many strings to generate HTML responses, you should not generate a String object for each string, because this will generate a large number of string and stringbuffer objects, this causes a large amount of Object Construction consumption and garbage collection burden. The solution is to write all the objects to be written directly to printwriter in one row, or create a stringbuffer object and Use APPEND () method to add text.

Timely delivery
Sometimes, the program takes a long time to execute. In this case, some information should be returned to the client, instead of displaying the white screen for a long time, which can be returned to some extent after execution, you can use the flush () method of printwriter to forcibly send the existing content back to the browser.

For more information about servlet running examples, see

Http://blog.csdn.net/wasingmon/archive/2006/01/10/575703.aspx

End!

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.