Servlet, filter, and Listener overview

Source: Internet
Author: User


Servlet technology is a solution for dynamic Web pages, which is a Web server-side programming technology based on Java programming language.


Servlet technology is also the basis of JSP technology (another Dynamic web development technology).


A servlet program is one that implements a special interface? Java class, which is called and started by a Web server that supports Servlets (with servlet engines).


A servlet program is responsible for processing access requests for one or a set of URL addresses that it corresponds to, and receiving access request information from clients and generating response content.


Applets are Java applets for browser-side applications, and Servlets are Java applets for Web server-side applications.


The servlet program can accomplish most of the tasks that ordinary Java programs can accomplish:
Gets the data that the client submitted via the form form of HTML and the parameter information behind the URL
Create a response message content to the client
Accessing the server-side file system
Connect to databases and develop database-based applications
Calling other Java classes

The servlet API (servlet application Programming Interface) is a set of Java classes and interfaces dedicated to the development of servlet programs. The jar package for the early wrapper Servlet API is called JSDK (Java Servlet Development Kit, the Javaservlet Development Kit), The latest version of the Javaservlet Development Kit has been integrated into Java EE (the Java Enterprise Version) Development Toolkit.



A servlet program is a Java class that implements the Javax.servlet.Servlet interface, and the Servlet interface defines the protocol conventions for communication between the servlet engine and the servlet program. The Javax.servlet.GenericServlet class implements the
Servlet interface, which implements the basic features and functions of the servlet program. The Javax.servlet.http.HttpServlet class is a subclass of Genericservlet, and it makes some extensions to the HTTP features on the basis of the Genericservlet class.

Each time a client accesses a servlet program that supports HTTP, the servlet engine invokes the Servlet's service method for processing. The service method accepts two parameters, one for encapsulating an HTTP request message, the type is httpservletrequest, and the other is an object representing the HTTP response message, which is of type HttpServletResponse. Call the Getwriter method of the HttpServletResponse object to get a text output stream object, and the data written to the stream object will be sent to the client as the entity content portion of the HTTP response message.

The servlet program must start running through the servlet engine, and the storage directory has special requirements, which usually need to be stored in the <web application directory >\web-inf\classes\ directory.


The servlet program must register and map its access path in the Web application's website. xml file, or using annotation, before it can be loaded by the servlet engine and accessed by the outside world.


A <servlet> element is used to register a servlet, which contains two primary child elements:<servlet-name> and <servlet-class> Used to set the registration name of the servlet and the full class name of the servlet, respectively.


An <servlet-mapping> element is used to map an external access path to a registered servlet, which contains two child elements:<servlet-name> and <url-pattern> Used to specify the name of the servlet's registry and the external access path of the servlet, respectively.

Default Servlet If a servlet's mapping path is just a forward slash (/), the servlet becomes the default servlet for the current Web application.
The URL of a matching <servlet-mapping> element cannot be found in the Web. xml file, and their access requests are given to the default servlet processing, that is, the default servlet is used to handle access requests that are not processed by all other Servlets
installation directory in <tomcat >\conf\ Web. xml file, a servlet named Org.apache.catalina.servlets.DefaultServlet is registered, and the servlet is set to the default servlet.
When accessing a static HTML file and picture in a Tomcat server, you are actually accessing the default servlet.

The 1.Servlet engine checks to see if an instance object of the servlet has been loaded and created. If so, perform step 4th directly, otherwise, step 2nd.
2. Mount and create an instance object of the servlet.
3. Invoke the Init () method of the Servlet instance object.
4. Create a HttpServletRequest object that encapsulates the HTTP request message and a HttpServletResponse object that represents the HTTP response message, and then call the servlet's service () Method and passes the request and response objects in as parameters.
Before the 5.WEB application is stopped or restarted, the servlet engine uninstalls the servlet and calls the servlet's Destroy () method before uninstalling.

Load-on-startup
Nesting a <load-on-startup> child element in the <servlet> element allows the Web application to mount and create instance objects of the servlet at startup, and to invoke the Init () method of the Servlet instance object.
Example:
<servlet>
<servlet-name>invoker</servlet-name>
<servlet-class>
Org.apache.catalina.servlets.InvokerServlet
</servlet-class>
<load-on-startup>2</load-on-startup>

</servlet>


The Init method is called only once for the entire lifetime of the servlet, and each access request to a servlet causes the servlet engine to invoke the Servlet's service method. For each access request, the Servlet engine creates a new HttpServletRequest request object and a new HttpServletResponse response object. The two objects are then passed as arguments to the service () method of the servlet that it invokes.
Auto Reload
Tomcat also provides configuration options for whether to automatically reload the modified servlet. In the <tomcat installation home directory >/conf/server.xml file, you can set the Reloadable property of the <Context> element to true so that Tomcat will monitor the/web-inf of the WEB application Whether the classes in the/classes and/web-inf/lib directories have changed, and then automatically reloads those classes that have changed.
Example:
<context path= "It" docbase= "D:\myweb" debug= "0" reloadable= "true"/>

Although Servlet APIs are referenced in the servlet source program, the objects that are actually called by the servlet runtime are created by the implementation classes in the Servlet container, so the jar package for the Servlet API is added to the CLASSPATH environment variable. The servlet program can only be guaranteed to compile successfully, but cannot let the servlet program run away from the servlet container.



In some cases, the ServletConfig interface servlet may need to access the servlet container or access external resources with a servlet container, so the Serlvet engine needs to pass the object representing the Servlet container to the servlet. In addition, information such as the friendly name and initialization parameters set for a servlet in the Web. xml file also needs to be passed to the servlet. The servlet engine encapsulates the object that represents the Servlet container and the configuration parameter information for the servlet into an object called ServletConfig, and is passed to the servlet when the servlet instance object is initialized. The ServletConfig interface is used to define methods that the ServletConfig object needs to provide externally so that these methods can be called in the servlet program to obtain information.
The servlet engine invokes the init (Servletconfig?config) method of the instance object of the servlet to pass the ServletConfig object to the servlet. The Servlet.getservletconfig () method must return a reference to the ServletConfig object passed in by the Init (Servletconfig?config) method.



The ServletContext interface servlet engine creates a corresponding ServletContext object for each Web application, and ServletContext objects are included in the ServletConfig object. Call the Servletconfig.getservletcontext method to return a reference to the ServletContext object.
Because all servlets in a Web application share the same ServletContext object, the ServletContext object is called a Application object (Web Application object).
Function:
Get initialization parameters for a Web application
Application domain-wide properties
accessing resource files
Gets the local path mapped by the virtual path
Access between Web applications
Other methods of ServletContext

Filter Main uses:
Before the client requests a Web page (html/jsp/servlet), let the filter first appropriate "filter", or when the server-side response to the client's request, let the filter before the appropriate "filter";
When jumping from one page (forward) to another page;
When you include other content (include);
In the event of an error.
Use filter:
1. Create a class that implements the filter interface and implements the method in it:
The init () method is its initialization method, which is automatically called when the filter is loaded;
The DoFilter () method is the core method of the filter class, and we hope that the function that the filter completes should be put into this method;
The Destroy () method is the method that is called when the filter is destroyed;
2. Put the filtered task into the Dofilter () method, which has three parameters: ServletRequest, Servletresponse, and Filterchain, Where ServletRequest and Servletresponse are the request and response parameters passed to the method, and Filterchain is used to pass the request and response to the next filter or other resources such as Jsp/servlet;
3. Call Filterchain's Dofilter () method in Dofilter (), which has only two parameters: ServletRequest and servletresponse, usually as long as the filter's Dofilter () The first two of the method can be used as its parameters;
4. Register this filter in Web. xml or annotation, and the page it will filter on.

Listener when a servlet context is created ready to accept the first request, or if the servlet context is about to close, the ServletContext Listener will be notified.
Servletcontextlistener
Servletcontextlistener is used to monitor changes in servlet context,
It has two methods:
Servletcontextinitialized (ServletContext Event SCE): When servlet
Servletcontextdestroyed (ServletContext Event SCE): This method is called when the servlet context is destroyed (such as shutting down the application server or reloading the app).
Servletcontextattributelistener
ServletContext Attributelistener is notified when a property is added, deleted, or replaced in a servlet context.
Method:
void attributeadded (Servletcontextattributeevent scab): This method is called when a property is added to the ServletContext;
void attributeremoved (Servletcontextattributeevent scab): This method is called when a property is removed from the ServletContext;
void attributereplaced (Servletcontextattributeevent scab): This method is called when a property in the ServletContext is changed.
Httpsessionlistener
When a httpsession has just been created (created) or fails (invalidated), Httpsessionlistener will be notified.
Method:
void sessioncreated (httpsessionevent HSE): This method is called when a HttpSession object is created;
void sessiondestroyed (httpsessionevent HSE): This method is called when a httpsession times out or calls HttpSession's invalidate () method to destroy it.
Httpsessionattributelistener
HTTP Sessionattributelistener will be notified when a property is added, removed, or replaced in a httpsession.
Method:
void attributeadded (Httpsessionbindingevent e): This method is called when a property is added to the session;
void attributeremoved (Httpsessionbindingevent e): This method is called when a property is removed from the session;
void attributereplaced (Httpsessionbindingevent e): This method is called when the properties in the session are changed.









Servlet, filter, and Listener overview

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.