Servlet is a general expansion of servers that support Java. Its most common use is to extend the web server, providing very safe, portable, easy-to-use CGI alternatives. It is a dynamically loaded module that serves as a request from a web server. It is fully running on the Java virtual machine. Because it runs on the server, it does not rely on the browser compatibility.
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 the Servlet API. This interface defines the method of the servlet container to be called on the servlet and passed to the SERVLET class.
SERVLET lifecycle:
1, a instance of the servlet container creates a servlet
2, the container calls the init () method of this instance
3. If the container has a request to the servlet, the service () method of this instance is called.
4, the container is destroying the destroy () method before the present example
5, 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. Returns NULL if you do not specify a parameter in the request information.
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. Returns NULL if you do not specify a parameter in the request information.
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
Needed
Http://java.sun.com/products/servlet/; get a copy of JSDK and move 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 ("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. Servlet session
Since the protocol HTTP used by the web server is a stateless protocol, it is necessary to use other additional means to maintain a series of requests for a series of requests. In the previous, the general method is to use:
l Hidden Table field: In the browser, this type of field is invisible, however, it is transmitted in the request, and the server-side program can read its value. Its advantage is that it is easy, and most browser supports; the disadvantage is that the field must be established in a specific order, the client can get its value by viewing the source code, click the "Back" button in the browser to lose to the current The additional fields in the page also limits the generation of the user's dynamic generation document.
l cookie: It is some key data dishes, which is created by the server and stored by the client's browser. The browser maintains its own cookie table, which makes it as a session tracking solution. The benefit of using cookies is that it is more intuitive than storing data in the URL or form. Its disadvantage is that it can be used to track users longer than a short session, and can even be used to track each request sent by a user to the site, so some people are worried about their privacy issues and close cookie, some old The browser does not support cookies. Servlet API provides a cookie class to support cookies, add and read cookies with httpservletresponse.addcookie () and httpservletresponse.getCookies () methods.
l URL rewrite: Modify the requested URL to contain the session ID. The disadvantage of this method is that for a large amount of data, the URL will become very long and the control; in some environments, the string length of the URL has a certain limit; the data confidential issue, you may not want the side of the side or You can use the same computer to see your session data. Servlet provides an HTTPSERVLETREQUEST class to get parameters.
The Servlet API has its own built-in session tracking, which can be used with HTTPSession objects. Its setAttribute () method binds a pair of name / value data, save it to the current session, if the name already exists in the session, the syntax is: public void setttribute (String Name, Object Value). The GetAttribute () method reads the object stored in the session, the syntax is: Public Object GetAttribute (String Name). GetAttributeNames () method Returns all the names stored in the session, the syntax is: public string [] GetAttributeNames (). The last method is the removettribute () method, which deletes the specified information from the session, and the syntax is: Public Void Removeattribute (String Name). The HttpSession object can be obtained using the HTTPServletRequest object Request's GetSession (TRUE) method. The parameter is true means that if there is no such object, one is created.