Servlet and related classes and interfaces

Source: Internet
Author: User

Servlet and related classes and interfaces

The previous article introduced Web in the web project. the configuration information of the xml file. This article mainly introduces the very important configuration-Servlet configuration, focuses on several Servlet-related interfaces and classes, includes Servlet interface, ServletConfig interface, ServletContext interface, GenericServlet class, And HttpServlet class.

1. Servlet Introduction

What is Servlet:

Baidu interpreted it as "a small service program or a service connector. It is a server program written in Java. Its main function is to interactively browse and modify data to generate dynamic Web content ". Servlet is an interface in the Java language. Any class that directly or indirectly implements the Servlet interface can be called a Servlet class.

Relationship between Servlet and Tomcat:

Tomcat is a Web application server and a Servlet container. As a Servlet container, Tomcat can create Servlet-class instances at startup, call the init () method to initialize the Servlet, process customer requests, and send requests to the Servlet, and send the Servlet response back to the customer. Servlet is a component running on a server that supports the Java language. In the web. xml file, configure servlet class information through the <Servlet> label, see the http://www.cnblogs.com/Y-oung/p/8401549.html for detailed configuration.

2. Servlet Interface

First look at the source code:

package javax.servlet;import java.io.IOException;public abstract interface Servlet {    public abstract void init(ServletConfig paramServletConfig)            throws ServletException;    public abstract ServletConfig getServletConfig();    public abstract void service(ServletRequest paramServletRequest,            ServletResponse paramServletResponse) throws ServletException,            IOException;    public abstract String getServletInfo();    public abstract void destroy();}

Init (): initialization method. After Tomcat instantiates the Servlet, the Servlet container will call the init () method to initialize the object, let the Servlet object complete initialization before processing the customer request, for example, establishing a database connection and obtaining configuration information. The init () method is called only once throughout the Servlet lifecycle. The init () method has a parameter of Type ServletConfig. The Servlet container uses this parameter to transmit configuration information to the Servlet. Servlet uses the ServletConfig object to obtain the initialization parameters provided in name-value pairs from the web. xml file. In addition, you can use the ServletConfig object to obtain the ServletContext object describing the Servlet runtime environment. With this object, the Servlet can communicate with its Servlet container.

The configuration information in the red circle can be parsed in the init () method of the MainServlet class.

GetServletConfig (): This method returns the ServletConfig object passed to the Servlet object when the container calls the init () method. The ServletConfig object contains the Servlet initialization parameters (such as the configuration information in the red circle ). The following describes the ServletConfig interface.

Service (): This method is the core method used to process client requests (ensure that the init () method is completed correctly before the service () method is called by the container. The container constructs a request object (type: ServletRequest) that represents the client request information and a response object (type: ServletResponse) that is used to respond to the client as a parameter and passes it to service (). In the service () method, the Servlet object obtains the client-side information and request information through the ServletRequest object. After processing the request, it calls the method of the ServletResponse object to set the response information.

GetServletInfo (): This method returns a string containing Servlet Information (such as the author, version, and copyright information), and returns a plain text string instead of any type of tag.

Destroy (): This method is used to destroy Servlet objects. When the container detects that a Servlet object should be removed from the service, the container will call the destroy () method of the object so that the Servlet object can release the resources it uses, this method will only be executed once. When the memory needs to be released or the container is closed, the container will call the destroy () method of the Servlet object. Before the Servlet container calls the destroy () method, if there are other threads in the service () the execution container will wait for these threads to finish or wait for the timeout value set by the server to arrive. Once the destroy () method of the Servlet object is called, the container no longer sends the request to the object. If you need to change the Servlet to serve the client again, the container will generate a new Servlet object to process client requests. After the destroy () method is called, the container will release the Servlet object and the object will be recycled by the java garbage collector in the following time.

As you can see, the Servlet Interface contains only five methods: init (), getServletConfig (), service (), getServletInfo (), and destroy (). Among them, the init (), service (), and destroy () methods are related to the servlet lifecycle. Different methods are executed in different time periods of the lifecycle, the order is init ()-> service ()-> destroy (). The init () and destroy () methods are executed only once in the servlet lifecycle, while the service () method can be executed multiple times. Servlet interfaces are the lowest, most basic, and most important interfaces of Servlet classes.

3. ServletConfig Interface

First look at the source code:

package javax.servlet;import java.util.Enumeration;public abstract interface ServletConfig {    public abstract String getServletName();    public abstract ServletContext getServletContext();    public abstract String getInitParameter(String paramString);    public abstract Enumeration<String> getInitParameterNames();}

GetServletName (): Get the servlet name in the web. xml file (that is, the name of the <servlet-name> tag configuration ).

GetServletContext (): Get the ServletContext object. The following describes the ServletContext interface.

GetInitParameter (): Get the parameter value configured in the servlet tag of the web. xml file (note that it is the servlet tag, rather than the parameter value configured by other tags ).

GetInitParameterNames (): obtains the names of all initialization parameters in the Servlet, that is, the key value. You can use the key value to find the value of each initialization parameter (note that the returned value is of the enumeration type ).

 

 

 

 

 

 

 

 

As you can see, the methods in the ServletConfig interface mainly obtain servlet-related configuration information in the web. xml file.

4. ServletContext Interface

First look at the source code:

package javax.servlet;import java.io.InputStream;import java.net.MalformedURLException;import java.net.URL;import java.util.Enumeration;import java.util.EventListener;import java.util.Map;import java.util.Set;import javax.servlet.descriptor.JspConfigDescriptor;public abstract interface ServletContext {    public static final String TEMPDIR = "javax.servlet.context.tempdir";    public static final String ORDERED_LIBS = "javax.servlet.context.orderedLibs";    public abstract ServletContext getContext(String paramString);    public abstract String getContextPath();    public abstract int getMajorVersion();    public abstract int getMinorVersion();    public abstract int getEffectiveMajorVersion();    public abstract int getEffectiveMinorVersion();    public abstract String getMimeType(String paramString);    public abstract Set<String> getResourcePaths(String paramString);    public abstract URL getResource(String paramString)            throws MalformedURLException;    public abstract InputStream getResourceAsStream(String paramString);    public abstract RequestDispatcher getRequestDispatcher(String paramString);    public abstract RequestDispatcher getNamedDispatcher(String paramString);    public abstract Servlet getServlet(String paramString)            throws ServletException;    public abstract Enumeration<Servlet> getServlets();    public abstract Enumeration<String> getServletNames();    public abstract void log(String paramString);    public abstract void log(Exception paramException, String paramString);    public abstract void log(String paramString, Throwable paramThrowable);    public abstract String getRealPath(String paramString);    public abstract String getServerInfo();    public abstract String getInitParameter(String paramString);    public abstract Enumeration<String> getInitParameterNames();    public abstract boolean setInitParameter(String paramString1,            String paramString2);    public abstract Object getAttribute(String paramString);    public abstract Enumeration<String> getAttributeNames();    public abstract void setAttribute(String paramString, Object paramObject);    public abstract void removeAttribute(String paramString);    public abstract String getServletContextName();    public abstract ServletRegistration.Dynamic addServlet(String paramString1,            String paramString2);    public abstract ServletRegistration.Dynamic addServlet(String paramString,            Servlet paramServlet);    public abstract ServletRegistration.Dynamic addServlet(String paramString,            Class<? extends Servlet> paramClass);    public abstract <T extends Servlet> T createServlet(Class<T> paramClass)            throws ServletException;    public abstract ServletRegistration getServletRegistration(            String paramString);    public abstract Map<String, ? extends ServletRegistration> getServletRegistrations();    public abstract FilterRegistration.Dynamic addFilter(String paramString1,            String paramString2);    public abstract FilterRegistration.Dynamic addFilter(String paramString,            Filter paramFilter);    public abstract FilterRegistration.Dynamic addFilter(String paramString,            Class<? extends Filter> paramClass);    public abstract <T extends Filter> T createFilter(Class<T> paramClass)            throws ServletException;    public abstract FilterRegistration getFilterRegistration(String paramString);    public abstract Map<String, ? extends FilterRegistration> getFilterRegistrations();    public abstract SessionCookieConfig getSessionCookieConfig();    public abstract void setSessionTrackingModes(            Set<SessionTrackingMode> paramSet) throws IllegalStateException,            IllegalArgumentException;    public abstract Set<SessionTrackingMode> getDefaultSessionTrackingModes();    public abstract Set<SessionTrackingMode> getEffectiveSessionTrackingModes();    public abstract void addListener(String paramString);    public abstract <T extends EventListener> void addListener(T paramT);    public abstract void addListener(Class<? extends EventListener> paramClass);    public abstract <T extends EventListener> T createListener(            Class<T> paramClass) throws ServletException;    public abstract void declareRoles(String[] paramArrayOfString);    public abstract ClassLoader getClassLoader();    public abstract JspConfigDescriptor getJspConfigDescriptor();}

Tomcat creates a ServletContext instance for each web project. It is created at Tomcat startup and destroyed when the server is disabled. Data is shared in a web project and web project resources are managed, configure public information for the entire web. Each web project has a ServletContext instance, and each Servlet can access it. As you can see, there are many methods in the ServletContext interface. The following describes the methods based on the functions.

How to obtain shared data in the memory of a Web application:

SetAttribute (String paramString, Object paramObject): binds a Java Object to an attribute name and stores it in ServletContext. The paramString parameter specifies the attribute name. The paramObject parameter identifies the shared data.
GetAttribute (String name): returns an Object of the Object type based on the attribute name specified by the parameter. It indicates the attribute value that matches the attribute name in ServletContext.
GetAttributeNames (): returns an Enumeration object that contains all attribute names stored in the ServletContext.
RemoveAttribute (String name): deletes a matched attribute from ServletContext Based on the attribute name specified by the parameter.

Access the resources of the current Web application:
GetContextPath (): return the URL entry of the current Web application.
GetInitParameter (String name): return the initialization parameter value within the Web application range based on the given parameter name. In the web. xml file, the <context-param> element defined under <web-app> and element indicates the initialization parameters within the application scope.
GetInitParameterNames (): returns an Enumeration object that contains all initialization parameters within the scope of the Web application.
GetServletContextName (): returns the name of the Web application, that is, the value of the <display-name> element in the web. xml file.
GetRequestDispatcher (String path): returns a RequestDispatcher object used to forward requests to other Web components.

Access other Web applications in the Servlet container:
GetContext (String uripath): The ServletContext object of other Web applications in the current Servlet container is returned Based on the URI specified by the parameter.
Access Servlet container information:
GetMajorVersion (): returns the major version number of the Java Servlet API supported by the Servlet container.
GetMinorVersion (); returns the minor version number of the Java Servlet API supported by the Servlet container.
GetServletInfo (): returns the Servlet container name and version.

Access the file system resources on the server:
GetRealPath (String path): return a real path in the file system based on the virtual path specified by the parameter.
GetResource (String path): returns a URL mapped to the path specified by the parameter.
GetResourceAsStream (String path): returns an input stream used to read the file specified by the parameter.
GetMimeType (String file): returns the MIME type of the file specified by the parameter.

Output log:
Log (String msg) writes logs to the Servlet log file.
Log (String message, java. lang. Throwable throwable): write error logs and stack information of exceptions to Servlet logs.

To be continued ......

 

Related Article

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.