Although the servlet has been used a lot, it has always been limited to its use operations.
A relatively comprehensive understanding of it has recently been utopian.
Here is a blog post organized by the blogger. A brief introduction of the servlet
The servlet (Server Applet), the full name of the Java servlet, does not have a Chinese translation. is a server-side program written in Java. Its main function is to interactively browse and modify data to generate dynamic Web content. A narrow servlet refers to an interface implemented by the Java language, which refers to any class that implements the Servlet interface, and generally the servlet is interpreted as the latter.
The servlet runs on Java-enabled application servers. In principle, a servlet can respond to any type of request, but in most cases the servlet is used only to extend the Web server based on the HTTP protocol. Second, the working principle of the Servlet
Initialization of Web applications (creating a Servlet object)
Typically in a Java Web project, we use a servlet, which is configured in Web.xml. The initialization of the application is mainly to parse the Web.xml file.
The initialization of Web applications is implemented in the Contextconfig Configurestart method, and the initialization of the application is mainly parsing the Web.xml file, which describes the key information of a Web application and is also a portal to Web applications. The individual configuration items in the Web.xml file will be parsed into the corresponding properties to be saved in the Webxml object. The properties in the Webxml object are also set to the context container, which includes creating Servlet objects, filter, listener, and so on, so the context container is the servlet container that actually runs the servlet. A Web application corresponds to a context container, and the configuration properties of the container are specified by the applied Web.xml.
How the servlet works
A request that a user initiates from a browser to a server typically contains the following information: Http://hostname:port/contextpath/servletpath,hostname and Port are used to establish a TCP connection to the server. The following URL is used to select which child container to service the user's request in the server. In Tomcat, URLs and servlet containers complete the mapping through class Org.apache.tomcat.util.http.mapper, mapper sets the host and context containers to the request based on the requested hostname and ContextPath In the Mappingdata property.
The servlet can help us with all of our work, but today's web apps rarely implement all of the pages of interaction directly with a servlet, but with a more efficient MVC framework. The rationale for these MVC frameworks is to map all requests to a servlet and then implement the service method, which is the portal to the MVC framework.
When the servlet is removed from the servlet container, it also indicates that the servlet's lifecycle is over, and the servlet's Destroy method is invoked to do some cleanup work
Servlet life cycle
The Servlet lifecycle can be defined as the entire process from creation through destruction. The following procedures are followed by the Servlet:
The Servlet is initialized by invoking the Init () method.
the Servlet invokes the service () method to handle the client's request. The
Servlet terminates (ends) by calling the Destroy () method.
Finally, the Servlet is garbage collected by the JVM's garbage collector.
The init () method
Init method is designed to be invoked only once. It is invoked the first time the Servlet is created, and is no longer invoked on each subsequent user request. Therefore, it is used for one-time initialization, just like an Applet's Init method. The
servlet is created when the user first invokes the URL that corresponds to the servlet, but you can also specify that the servlet be loaded the first time the server starts.
when a user invokes a servlet, a servlet instance is created, and each user request generates a new thread, which is transferred to the Doget or DoPost method when appropriate. The init () method simply creates or loads some data that will be used for the entire lifecycle of the Servlet.
The service () Method
Service () method is the primary way to perform actual tasks. The Servlet container (that is, the WEB server) invokes the service () method to process requests from the client (browser) and writes the formatted response back to the client.
each time the server receives a Servlet request, the server generates a new thread and invokes the service. The service () method checks the HTTP request type (GET, POST, put, DELETE, and so on) and invokes Doget, DoPost, Doput,dodelete, and so on when appropriate.
The Doget () method get
request comes from a normal request for a URL, or from an HTML form that does not specify method, which is handled by the Doget () methods.
The DoPost () method
POST request comes from an HTML form that specifically specifies the method as post, which is handled by the DoPost () methods.
The Destroy () method
Destroy () method is invoked only once and is invoked at the end of the Servlet lifecycle. The Destroy () method lets your Servlet close the database connection, stop the background thread, write the Cookie list or hit counter to disk, and perform other similar cleanup activities.
iii. Examples of servlet usage
Instance usage Prerequisites: JDK and Tomcat are already configured
Here we are ready to:
(1) Servlet:HelloWorld.java
Import the required Java library import
java.io.*;
Import javax.servlet.*;
Import javax.servlet.http.*;
Extended HttpServlet class public class
HelloWorld extends HttpServlet {
private String message;
public void Init () throws Servletexception
{
//execute the required initialization message
= ' Hello world ';
}
public void doget (HttpServletRequest request,
httpservletresponse response)
throws Servletexception, IOException
{
//Set response content type
response.setcontenttype ("text/html");
The actual logic is here
printwriter out = Response.getwriter ();
Out.println ("
(2) Servlet-api.jar
The need to rely on Servlet-api.jar packages does not require too much explanation, which contains the servlet-related interface classes.
The blogger has provided the appropriate jar packs for the Ape friends to download:
http://download.csdn.net/detail/u013142781/9446459
The following actions are also required:
(1) Put Helloworld.java and Servlet-api.jar under D:\servlettest. (Ape Friends if placed in other directories, the following settings should be modified accordingly)
(2) environment variable classpath add Servlet-api.jar store path, Bo is the main D:\servlettest\servlet-api.jar
(3) Open cmd, enter to D:\servlettest (CD D:\servlettest), then execute command javac Helloworld.java, compile Servlet.
(4) After the success of the compiler found D:\servlettest a helloworld.class file.
(5) Put the Helloworld.class file under the webapps\root\web-inf\classes of Tocmat (if there is no classes, create a new one put in)
(6) Add the following configuration to the Tocmat webapps\root\web-inf\web.xml file:
<servlet>
<servlet-name>HelloWorld</servlet-name>
<servlet-class>helloworld </servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloWorld< /servlet-name>
<url-pattern>/HelloWorld</url-pattern>
</servlet-mapping>
After the Web.xml configuration of the blogger is this:
<?xml version= "1.0" encoding= "iso-8859-1"?> <!--licensed to the Apache Software Foundation (ASF) under one or M Ore contributor license agreements.
The NOTICE file distributed with this work for additional information regarding copyright. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); You are not to use this file except in compliance with the License. Obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 unless required by applicable Agreed to writing, software distributed under the License was distributed on ' as is ' basis, without Warra
Nties or CONDITIONS of any KIND, either express OR implied.
The License for the specific language governing permissions and limitations under the License. --> <web-app xmlns= "Http://java.sun.com/xml/ns/javaee" xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" "Xsi:schemalocation=" http://java.sun.com/xml/Ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd "version=" 3.0 "metadata-complete=" tr UE "> <display-name>welcome to tomcat</display-name> <description> Welcome to Tomcat </ description> <servlet> <servlet-name>HelloWorld</servlet-name> <servlet-class>hellow orld</servlet-class> </servlet> <servlet-mapping> <servlet-name>helloworld</servlet-na
me> <url-pattern>/HelloWorld</url-pattern> </servlet-mapping> </web-app>
(7) Next double-click the startup.sh in Tomcat's Bin directory to start Tomcat.
(8) Access path: Http://localhost:8080/HelloWorld, the effect is as follows: