Introduction to Servlet
Servlet container:
Responsible for handling the customer request, transmitting the request to the servlet and returns the result to the customer. The actual implementation of the container of different programs may vary, but the interface between the container and the servlet is defined by servletAPI. This interface defines the method of the servlet container to be called on the servlet and passed to the SERVLET class.
SERVLET lifecycle:
l A instance of servlet container creates a servlet
l Container calls the init () method of this instance
l If the container has a request to the servlet, call the service () method of this instance () method
l The container calls its destroy () method before destruction of this example.
l Destroy and mark this example for garbage collection
Once a servlet is requested, there is no way to prevent the container from performing a complete lifecycle.
The container creates an instance of it when servlet is called, and keeps this instance in memory, allowing it to process all requests. The container can decide to remove this instance from memory at any time. In a typical model, the container creates a separate instance for each servlet, and the container does not create a new thread per recesered request, but uses a thread pool to dynamically assign the thread to arrival, but This is the same as the SERVLET's point of view, the effect and the effect of creating a new thread for each request.
Servlet API
Servlet interface:
Public interface servlet
Its life cycle is defined by the javax.servlet.servlet interface. This interface must be implemented directly or indirect when you write servlet. Generally tended to indirectly: derived from javax.servlet.GenericServlet or javax.servlet.http.httpservlet. Five methods must be implemented when implementing a servlet interface:
INIT ():
Public Void Init (ServletConfig Config) Throws ServleTexception
Once instantiated the servlet, the container calls this method. The container contains a servletconfig object to this method so that the instance of the servlet can save the configuration data related to the container for later use. If this method does not end properly, you will throw a servletException. Once the exception is thrown, the servlet is no longer executed, and the call to it will cause the container to reload and run this method again. The interface specifies any servlet instance, this method can only be called once, before any request is passed to the servlet, this method can run without throwing an abnormally.
Service ():
Public Void Service (ServletRequest Req, ServletResponse Res) THROWS ServleTexception, IOEXCEPTION
This method can only be called to process user requests only after successful initialization. The previous parameter provides methods and fields that access the initial request data, and the latter method provides a method of constructing a servlet constructor.
DESTROY ():
Public void destroy ()
The container can terminate the servlet service at any time. The container is called before this method must be completed to the service () thread sufficient time, so the interface specifies that the design when Service () is executing is not executed.
GetServletConfig ():
Public servletconfig getServletConfig ()
When servlet is initialized, the container passes a servletconfig object and saved in a servlet instance, which allows access to both content: Initializing parameters and servletContext objects, the former is typically specified by the container in the file, allowing the SEVRLET to send relevant scheduling at runtime Information, the latter provides information about the container for servlets. This method allows servlet to get this object and configuration information at any time. GetServletInfo ():
Public String GetServletInfo ()
This method returns a String object that contains information of servlet, such as developers, creation dates, description information, and more. This method can also be used in the container.
GenericServlet class
Public Abstract Class GenericServlet Implants Servlet, ServletConfig, Serializable
Such a basic implementation part of the servlet interface is provided, and its service () method is declared as Abstract, so it is necessary to be derived. Init (servletConfig conf) method stores the servletconfig object in a private transient instance variable, the getServletConfig () method returns a pointer to this object, if you overload this method, you will not use GetServletConfig to get a servletconfig object, if Really want to overload, remember to include the call to super.config. The version 2.1 API provides an overloaded INIT () method. Now there is a call to init () at the end of the init (servletConfig) method, although it is empty. The version of the version of the version of the API, this class implements the servletconfig interface, which makes the developer to directly call servletconfig in the case of servletconfig objects, these methods are: GetInitParameter (), GetInitParameterNames (), GetServletContext. Such a method of writing two write logs, which actually calls the corresponding method on servletContext. Log (String MSG) Method Write the servlet's name and MSG parameters to the log of the container, and the log (String MSG, Throwable Cause) includes an exception in addition to the servlet.
HTTPSERVLET class
This class extends the GenericServlet class and provides a more relevant implementation with HTTP interfaces for the servlet interface.
Service ():
Protected Void Service (httpservletRequest Req, httpservletResponse res) throws servletexception, ioException
Public Void Service (httpservletRequest Req, httpservletResponse res) throws servletexception, ioException
This method is a distributor of an HTTP request, which cannot be overloaded at any time. When the request arrives, the service () method determines the type of request (GET, POST, HEAD, OPTIONS, DELETE, PUT, TRACE), and distribute the request to the corresponding processing method (doget (), dopost (), dohead () DOOPTIONS (), Dodelete (), doput (), dotrace ()) Each DO method has the same form as the first service (). In response to a specific type of HTTP request, we must overrun the corresponding DO method. If the servlet receives an HTTP request and you do not overload the corresponding DO method, it returns a standard HTTP error that this method is not available to this resource. getlatModified ():
Protected long getlastmodified (httpservletRequest Req)
The method returns from the Time-dependent time-dependent time to modify the servlet from 0:0:05 0:00 January 1, 1970, 1970, and the default is to return a negative representation time unknown. When processing a GET request, call this method to know the recent modification time of the servlet, the server can decide whether the result is removed from the cache.
HTTPSERVLETREQUEST interface
Public Interface HttpservletRequest Extends ServletRequest
All objects that implement this interface (such as HTTP request objects passed from the servlet container) allow servlets to access all requests through their own methods. Below is some basic methods used to obtain form data.
GetParameter ()
Public String getParameter (String Key)
This method attempts to place the corresponding parameters according to the keyword in the query string and return its value. If there are multiple values, return the first value in the list.
getParameterValues ():
Public string [] getParameterValers (String Key)
If a parameter can return multiple values, such as checkbox, you can use this method to get all values of the corresponding parameters.
GetParameterNames ():
Public Enumeration getParameterNames ()
This method returns an ENUMERATION object that contains all the parameter names of the corresponding request.
HTTPSERVLETRESPONSE interface
Public Interface HttpservletResponse Extends ServletResponse
The servlet container provides an object that implements the interface and passes it to the servlet through the service () method. Through this object and its method, the servlet can modify the head and return the result.
setContentType ():
Public void setContentType (String Type)
This method must be used to set the MIME type of HTTP response before sending a response to the caller. Can be any effective MIME type, when returning to the browser is the "Text / HTML" type.
GetWriter ():
Public PrintWriter getWriter () THROWS IOEXCEPTION
This method returns the PrintWriter object and returns the result of the servlet as a text to the caller. The PrintWriter object automatically converts the Unicode coded characters within Java into correct encoding to enable the client to read.
getOutputStream ():
Public servletOutputStream GetputStream () THROWS IOException
This method returns a 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 to the customer. There are some shortcuts to change some common response heads, but sometimes they need to call this method directly.
Compilation conditions
Need a copy of JSDK from http://java.sun.com/products/servlet/ and moves servlet.jar to the / jre / lib / ext directory in the JDK installation directory. If it is JDK1.1, move it under / lib and add servlet.jar to the ClassPath.
Operating conditions
Servlet server-side programs such as Apache Jserv, Jrun Server, WebLogic, WebSphere, Tomcat, Resin are required.
Simple example
Import java.io. *;
Import javax.servlet. *;
Import javax.servlet.http. *;
Public class helloworld extends httpservlet {
Public void doget (httpservletRequest request, httpservletResponse response)
THROWS IOEXCEPTION, ServletException
{
Response.setContentType (Text / HTML ");
PrintWriter out = response.getwriter ();
Out.println ("");
Out.println ("
");Out.println ("
");Out.println ("
Out.println (" HEAD>");
Out.println ("
Out.println ("
Out.println (" Body>");
Out.println (" html>");
}
}
Servlet performance and efficiency
A servlet is only initialized once, so minimal inefficiency will also have a lot of impact over time. In the code, you need to consider the use of String objects. If you generate an HTML response requires a lot of strings, you should not generate a String object for each string because it produces a lot of String and StringBuffer objects, resulting in a lot of object constructs. Consumption and garbage collection burden, the solution is to write all the way to write all the needs to write directly, or create a StringBuffer object, and use the Append () method to add text.
Timely return
Sometimes, the program takes a long time to execute. In this case, it should be sent to the client some information, not a white screen for a long time, which can send some things to a certain extent, you can use PrintWriter's flush () Method Force existing content back to the browser.