Servlet, GenericServlet, HttpServlet overview and implementation

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/ym15229994318ym/article/details/100883149

What is Servlet

We used to come into contact with pure static html, this time For comparison servlet is a dynamic resource, he can write java code to process the request, the server will request to the Servlet to deal with, Servlet general to do is: receiving a request , process the request completion response.

What are Servlet implementation

Three ways:

  • Direct implementation of the Servlet interface, Servlet interface javax.servlet.Servlet
  • GenericServlet inherited class, GenericServlet class javax.servlet.GenericServlet
  • Inherit HttpServlet, HTTPServlet in javax.servlet.http.HttpServlet
    Web project we write generally follow the http protocol, so we often use in the development of a third way, more convenient.

Servlet life cycle

The so-called life cycle from birth to death is like human beings, let's take a look at the method of the Servlet API
servlet method

  • ServletConfig getServletConfig (), String getServletInfo () is a non-Servlet life cycle approach, used to get information and configuration information Servlet Servlet (version, author, etc.), I will not say any more, here is mainly to learn more about the life cycle approach .
  • void init (ServletConfig), void service (ServletRequest, ServletResponse), void destroy () method is a Servlet life cycle of three.
  • Birth: server creates when Servlet Servlet is first accessed, or are created in the server is started, then it means Servlet born. Servlet will be invoked after birth (creation) init () method, this method will only be called once. This method is called and only once, and calling at birth (creation), so generally we will acquaintance of work to be done on this method.
  • Work: When our server receives the request, Servlet will be to call the service () method, so we put the code to process the request on this method, but also received a call once, so this method is called multiple times of.
  • Death: when the server is shut down, the server to close Servlet, at this time our Servlet means death, so we want to release the Servlet resources on this method.

As can be seen above the three life-cycle approach is not our own manual calls, but calls itself through the server, which is very important.

Let's start on the code, create a Servlet.

The first way: direct implementation of the Servlet interface

Implement interfaces, interface methods need to be rewritten

public class MyServlet implements Servlet {
	public void init(ServletConfig config) throws ServletException {
		System.out.println("Servlet出生!");
	}
	// 这里我们先返回一个null
	public ServletConfig getServletConfig() {return null;}
	public void destroy() {
		System.out.println("Servlet死亡!");
	}
	// 这里我们先返回一个null
	public String getServletInfo() {return null;}

	public void service(ServletRequest req, ServletResponse res)
			throws ServletException, IOException {
		System.out.println("servlet工作!");
	}
}

When we start the server, and the first visit MyServlet, init () is invoked, and then call the service () method, will not call the init () method to access again, but calls the service () method until the when the server is shut down, it will call destroy () method.

Note that when the xml file does not automatically generate the corresponding Servlet our tool, we should configure itself, or access to the server is invalid.

<servlet>
		<servlet-name>hello</servlet-name>
		<servlet-class>cn.bjwlxy.servlet.MyServlet</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>hello</servlet-name>
		<url-pattern>/MyServlet</url-pattern>
	</servlet-mapping>  
</servlet>

servlet-name: This is the label we give our xml in the Servlet from the name, you can custom but must and servlet-name name tag, like so linked up.
servlet-class: This label is our Servlet class path
url-pattern: This label is going to knock us when accessing the server's address in the address bar.

The second way: inheritance of GenericServlet

GenericServlet is a class that implements the Servlet interface, we can write your own Servlet through inheritance GenericServlet.
Let's take a look at GenericServlet Source:

public abstract class GenericServlet implements Servlet, ServletConfig,
        java.io.Serializable {
    private static final long serialVersionUID = 1L;
    private transient ServletConfig config;
    public GenericServlet() {}
    @Override
    public void destroy() {}
    @Override
    public String getInitParameter(String name) {
        return getServletConfig().getInitParameter(name);
    }
    @Override
    public Enumeration<String> getInitParameterNames() {
        return getServletConfig().getInitParameterNames();
    }
    @Override
    public ServletConfig getServletConfig() {
        return config;
    }
    @Override
    public ServletContext getServletContext() {
        return getServletConfig().getServletContext();
    }
    @Override
    public String getServletInfo() {
        return "";
    }
    @Override
    public void init(ServletConfig config) throws ServletException {
        this.config = config;
        this.init();
    }
    public void init() throws ServletException {}
    public void log(String msg) {
        getServletContext().log(getServletName() + ": " + msg);
    }
    public void log(String message, Throwable t) {
        getServletContext().log(getServletName() + ": " + message, t);
    }
    @Override
    public abstract void service(ServletRequest req, ServletResponse res)
            throws ServletException, IOException;
    @Override
    public String getServletName() {
        return config.getServletName();
    }
}

  • GenericServlet source is found, there are two init method in the class, there is a parameter that takes no parameters, we understand that there is a life cycle approach parameters, so there is init parameter in config to get information, but our subclasses override config value will be sure to cover when init (the ServletConfig) is null, all methods rely config class would not be realized, so it provides a free parameter of the init method, and subclasses to override the parameters have the init method call, avoids this problem.
  • With the "servlet have life cycle", there will call the init method parameters, and in GenericServlet class have parameters init method calls the init method with no arguments.
    I could not help but admire the way their predecessors came up with.
public class MyServlet extends GenericServlet {
	@Override
	public void init() throws ServletException {
		System.out.println("Servlet出生!");
	}

	@Override
	public void service(ServletRequest arg0, ServletResponse arg1)
			throws ServletException, IOException {
		System.out.println("Servlet工作!");
	}

	@Override
	public void destroy() {
		System.out.println("Servlet死亡!");
	}
}

  • In this way, it has reduced the burden on developers, the process is still the same, when the server creates a Servlet, when there is a request to access this Servlet, then as the "servlet have life cycle" once the implementation of init, service, destroy method.

The third way: to inherit HttpServlet

  • HttpServlet class inherits GenericServlet class, he is a special support for http requests, because we developed web projects generally follow the http protocol, and will often HttpServlet deal.
  • Take a look at the source code is still the same HttpServlet
public abstract class HttpServlet extends GenericServlet {
    protected void service(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
        ……
}
    @Override
    public void service(ServletRequest req, ServletResponse res)
        throws ServletException, IOException {

        HttpServletRequest  request;
        HttpServletResponse response;

        try {
            request = (HttpServletRequest) req;
            response = (HttpServletResponse) res;
        } catch (ClassCastException e) {
            throw new ServletException("non-HTTP request or response");
        }
        service(request, response);
}
……
}

  • HttpServlet class provides the service (HttpServletRequest, HttpServletResponse) method, which is HttpServlet own way, is not inherited from Servlet come. In HttpServlet of-Service (ServletRequest, ServletResponse) process would turn into strong ServletResponse ServletRequest and HttpServletRequest and the HttpServletResponse, then calls the service (HttpServletRequest, HttpServletResponse) method, which can be described subclasses to override service (HttpServletRequest, HttpServletResponse) method may be, You do not have to go strong turn of the request and response objects.
    In fact, sub-categories do not take cover service (HttpServletRequest, HttpServletResponse) method, because we need to do another step HttpServlet streamline operations, the following will be introduced.
    Here and above reason as the first cover, and then provide a way, played a not covered, but did they need to do.
  • So init, destroy not covered, it will be the same as the inherited GenericServlet call, not repeat them here. After all, GenericServlet is "Servlet" Your grandfather created thing.
public class MyServlet extends HttpServlet{

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		System.out.println("doget请求");
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		System.out.println("dopost请求");
	}
	
}
  • In the HttpServlet service (HttpServletRequest, HttpServletResponse) method will be to judge the current request is a GET or POST, if a GET request, it will be to call this class doGet () method, if it is POST requests to call doPost () method, which we described in subclasses to override doGet () or doPost () method can be.

to sum up

Here, I think we should understand that this process up. HttpServlet inherited from GenericServlet, GenericServlet and implements the Servlet interface.
So they can be understood as a father-son relationship, Ye Sun relationship. No matter what way we achieve the Servlet, as long as the server receives the request, he would have to call the three life-cycle approach.
I hope this help you

Guess you like

Origin blog.csdn.net/ym15229994318ym/article/details/100883149