Servlet Programming: (3) Servlet's Little knowledge point

Source: Internet
Author: User

    1. How to develop a servlet

    2. The mapping path of the servlet

    3. servlet Default Path

    4. The life cycle of Sevlet

    5. Automatic loading of Servlets

    6. The Init method with parameters and the Init method without parameters

    7. Multithreading concurrency problems for servlets

    8. ServletConfig Object

    9. ServletContext Object

5. Automatic loading of servlet


By default, the Servlet object is created the first time the servlet is accessed. If more logical code is executed in the servlet's construction method or the Init method, it will cause the user to visit Sevrlet for the first time at a slower time.

Workaround: Change the time for the servlet to create the object, that is, before loading the Web App!!!

In the configuration information of the servlet, add a <load-on-startup>!!

<servlet> <servlet-name>LifeDemo</servlet-name> <servlet-class>com.rk.http.b_lifecycle. Lifedemo</servlet-class> <!--let servlet objects load automatically-<load-on-startup>1</load-on-startup><! --Note: The greater the integer value, the lower the creation priority!! -</servlet> <servlet-mapping> <servlet-name>LifeDemo</servlet-name> <url-patter N>/life</url-pattern> </servlet-mapping>




6. Init with parameter and init method without parameters



Custom servlet classes for program developers, Generally inherits from the Javax.servlet.HttpServlet abstract class, while the Javax.servlet.HttpServlet class inherits from the Javax.servlet.GenericServlet abstract class. the Javax.servlet.GenericServlet provides two init methods:

void init (servletconfig config)

void Init ()

The simple relationship between the two is as follows:

Init method with parameters//The method is the life cycle method of the servlet and must be called by the Tomcat Server//NOTE: If you are writing the initial code, you do not need to overwrite the Init method with parameters public void init (ServletConfig c    Onfig) throws Servletexception {this.config = Config;this.init ();    }///parameter-free Init method//The method is a way for the servlet to write initialization code.    is a method that sun designed to cover developers and then write the initial logic code for the servlet inside. public void Init () throws Servletexception {}


Part of the source code for the Javax.servlet.GenericServlet class is as follows:

Package javax.servlet;import java.io.ioexception;import java.util.enumeration;public class  GenericServlet implements Servlet, ServletConfig, java.io.Serializable{private  transient servletconfig config;/** * does nothing. all of the  Servlet initialization is done by one of the <code>init</code > methods. */public genericservlet ()  { }/** * called by the  servlet container to indicate that the servlet is being  Placed into service. */    public void init (ServletConfig  config)  throws servletexception {this.config = config;this.init ();     }        /**     * A  Convenience method wHich can be overridden so that there ' s no need      * to call <code>super.init (config) </code>.     *       * instead of overriding init (ServletConfig),  Simply override     * this method and it will be  called by <code>genericservlet.init (Servletconfig config) </code>.      * The <code>ServletConfig</code> object can still  be retrieved via getservletconfig.      */     public void init ()  throws ServletException {    }     /**     * returns this servlet ' S ServletConfig  object.      */    public servletconfig getservletconfig ()  {     return config;    }        public  string getservletname ()  {        return  Config.getservletname ();    }    public string  Getinitparameter (String name)  {return getservletconfig (). Getinitparameter (name);     public enumeration getinitparameternames ()  {     Return getservletconfig (). Getinitparameternames ();    }            /**     * returns a reference  to the ServletContext in which this servlet is running.      */    public&nbsP Servletcontext getservletcontext ()  {    return getservletconfig (). Getservletcontext ();     }}



7. Multi-threaded concurrency problem of servlet

The Servlet object is single- instance multithreaded on the Tomcat server.

Because servlets are multithreaded, thread-safety issues can arise when multiple servlet threads concurrently access the servlet's shared data, such as member variables.

Workaround:

1) Synchronize code blocks that are used to share data (using the Synchronized keyword for synchronization)

2) It is recommended that you try not to use member variables in the Servlet class.

A) If you do use members, you must synchronize;

b) Minimize the scope of the synchronization code block to avoid concurrency degradation due to synchronization. (where the member variable is used, where is the synchronization!!) )


Example: Record page access times

package com.rk.http.c_thread;import java.io.ioexception;import java.io.printwriter;import  javax.servlet.servletexception;import javax.servlet.http.httpservlet;import  javax.servlet.http.httpservletrequest;import javax.servlet.http.httpservletresponse;/** *  Multithreading concurrency issues for servlets  *  @author  RK * */public class ThreadDemo extends  httpservlet{private int count = 0; @Overrideprotected  void doget ( Httpservletrequest request, httpservletresponse response)  throws servletexception,  ioexception{response.setcharacterencoding ("UTF-8"); Response.setcontenttype ("Text/html;charset=utf-8"); Printwriter out = response.getwriter ();//out.write ("


Servlet Programming: (3) Servlet's Little knowledge point

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.