Introduction to Servlet

zhaozj2021-02-08  261

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 (" Hello World! </ TITLE>");</p> <p>Out.println ("</ HEAD>");</p> <p>Out.println ("<Body>");</p> <p>Out.println ("<H1> Hello World! </ H1>");</p> <p>Out.println ("</ Body>");</p> <p>Out.println ("</ html>");</p> <p>}</p> <p>}</p> <p>Servlet performance and efficiency</p> <p>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.</p> <p>Timely return</p> <p>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.</p></div><div class="text-center mt-3 text-grey"> 转载请注明原文地址:https://www.9cbs.com/read-1909.html</div><div class="plugin d-flex justify-content-center mt-3"></div><hr><div class="row"><div class="col-lg-12 text-muted mt-2"><i class="icon-tags mr-2"></i><span class="badge border border-secondary mr-2"><h2 class="h6 mb-0 small"><a class="text-secondary" href="tag-2.html">9cbs</a></h2></span></div></div></div></div><div class="card card-postlist border-white shadow"><div class="card-body"><div class="card-title"><div class="d-flex justify-content-between"><div><b>New Post</b>(<span class="posts">0</span>) </div><div></div></div></div><ul class="postlist list-unstyled"> </ul></div></div><div class="d-none threadlist"><input type="checkbox" name="modtid" value="1909" checked /></div></div></div></div></div><footer class="text-muted small bg-dark py-4 mt-3" id="footer"><div class="container"><div class="row"><div class="col">CopyRight © 2020 All Rights Reserved </div><div class="col text-right">Processed: <b>0.045</b>, SQL: <b>9</b></div></div></div></footer><script src="./lang/en-us/lang.js?2.2.0"></script><script src="view/js/jquery.min.js?2.2.0"></script><script src="view/js/popper.min.js?2.2.0"></script><script src="view/js/bootstrap.min.js?2.2.0"></script><script src="view/js/xiuno.js?2.2.0"></script><script src="view/js/bootstrap-plugin.js?2.2.0"></script><script src="view/js/async.min.js?2.2.0"></script><script src="view/js/form.js?2.2.0"></script><script> var debug = DEBUG = 0; var url_rewrite_on = 1; var url_path = './'; var forumarr = {"1":"Tech"}; var fid = 1; var uid = 0; var gid = 0; xn.options.water_image_url = 'view/img/water-small.png'; </script><script src="view/js/wellcms.js?2.2.0"></script><a class="scroll-to-top rounded" href="javascript:void(0);"><i class="icon-angle-up"></i></a><a class="scroll-to-bottom rounded" href="javascript:void(0);" style="display: inline;"><i class="icon-angle-down"></i></a></body></html><script> var forum_url = 'list-1.html'; var safe_token = '4GqgLxV_2F9JKfzSWNIKDf8Ld26kOZ3b87Jd_2FRio95JL68wejgEy7_2FSmCP8T1qOPjvt6bcr9bJ_2B8vt6RIIQ_2B8BXQ_3D_3D'; var body = $('body'); body.on('submit', '#form', function() { var jthis = $(this); var jsubmit = jthis.find('#submit'); jthis.reset(); jsubmit.button('loading'); var postdata = jthis.serializeObject(); $.xpost(jthis.attr('action'), postdata, function(code, message) { if(code == 0) { location.reload(); } else { $.alert(message); jsubmit.button('reset'); } }); return false; }); function resize_image() { var jmessagelist = $('div.message'); var first_width = jmessagelist.width(); jmessagelist.each(function() { var jdiv = $(this); var maxwidth = jdiv.attr('isfirst') ? first_width : jdiv.width(); var jmessage_width = Math.min(jdiv.width(), maxwidth); jdiv.find('img, embed, iframe, video').each(function() { var jimg = $(this); var img_width = this.org_width; var img_height = this.org_height; if(!img_width) { var img_width = jimg.attr('width'); var img_height = jimg.attr('height'); this.org_width = img_width; this.org_height = img_height; } if(img_width > jmessage_width) { if(this.tagName == 'IMG') { jimg.width(jmessage_width); jimg.css('height', 'auto'); jimg.css('cursor', 'pointer'); jimg.on('click', function() { }); } else { jimg.width(jmessage_width); var height = (img_height / img_width) * jimg.width(); jimg.height(height); } } }); }); } function resize_table() { $('div.message').each(function() { var jdiv = $(this); jdiv.find('table').addClass('table').wrap('<div class="table-responsive"></div>'); }); } $(function() { resize_image(); resize_table(); $(window).on('resize', resize_image); }); var jmessage = $('#message'); jmessage.on('focus', function() {if(jmessage.t) { clearTimeout(jmessage.t); jmessage.t = null; } jmessage.css('height', '6rem'); }); jmessage.on('blur', function() {jmessage.t = setTimeout(function() { jmessage.css('height', '2.5rem');}, 1000); }); $('#nav li[data-active="fid-1"]').addClass('active'); </script>