JavaWeb Road 01 - Servlet

Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allowed. https://blog.csdn.net/qq_42267300/article/details/86773088

Java Servlet

What is a Java servlet

Java Servlet, or the service called servlet connector (referred to as the Servlet ), is a realization of the general class java servlet interface, that interactively browse and modify data, generate dynamic Web content.

Servlet is the main function

  • Accept the request
  • Processing the request
  • Generate dynamic web content.

Refers to a narrow Servlet interface to the Java language, broadly refers to any Servlet class implements the Servlet interface, under normal circumstances, people will understand Servlet for the latter. Servlet running on Java-enabled application servers. In principle, Servlet can respond to any type of request, but in most cases only used to extend the Servlet Web server based on HTTP protocol.


The earliest support JavaSoft Servlet standard is a Java Web Server, thereafter, began to support some other standard Java-based Web server Servlet.




Servlet working mode

  • The client sends a request to the server
  • And call server starts Servlet, Servlet generated in response to the content request based on the client server and pass it
  • The server will respond back to the client



Servlet的API

  • void the init (config the ServletConfig): initialization method
  • void service(ServletRequest request,ServletResponse response):服务方法
  • void the destroy (): Method of destruction
  • The ServletConfig getServletConfig (): Get the current configuration of servlet objects
  • String getServletInfo (): Gets the information about the current servlet



Servlet life cycle

Servlet interface void the init (the ServletConfig config), void Service (ServletRequest Request, the Response ServletResponse), void the destroy () method is actually three Servlet life cycle function, representing the "birth", "work", "death."

We use the following code to look Servlet life cycle:

public class Demo1Servlet implements Servlet {
 
    @Override
    public void init(ServletConfig servletConfig) throws ServletException {
        System.out.println("Servlet正在初始化");
    }
 
    @Override
    public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
        //专门向客服端提供响应的方法
        System.out.println("Servlet正在完成业务逻辑");
 
    }
 
    @Override
    public void destroy() {
        System.out.println("Servlet正在销毁");
    }

    @Override
    public ServletConfig getServletConfig() {
        return null;
    }
 
    @Override
    public String getServletInfo() {
        return null;
    }



We configured mapping between xml, open the server, the first visit to the Servlet, the console prints the following information:
Here Insert Picture Description

In the four times we refresh the browser, the console has become such information:
Here Insert Picture Description

When we shut down the server, console print out the following information:
Here Insert Picture Description

Servlet when he finally destroyed, this is the complete life cycle of a Servlet.

A statement Servlet life cycle is: by default the first request to the server creates servlet objects, and call the init method to achieve initialization, and tune called once service method, whenever a request to the server retrieves a thread, call the service method to complete the specific business logic (code written) when the servlet is removed or when the server is shut down properly, the server calls the destroy method to achieve the destruction operation.



GenericServlet abstract class

We speak in front of the Servlet interface, but then face some inconvenience every time we use: not only have a bunch of methods need to achieve, you need to manually maintain ServletConfig a reference to the object, then there is any way to solve these problems in addition to it?

This time we will introduce a new class, he is GenericServlet abstract class, in addition to his service did not materialize, other methods have achieved.

Let us look at an abstract class GenericServlet original code:

public abstract class GenericServlet implements Servlet, ServletConfig, Serializable {
    private static final String LSTRING_FILE = "javax.servlet.LocalStrings";
    private static ResourceBundle lStrings = ResourceBundle.getBundle("javax.servlet.LocalStrings");
    private transient ServletConfig config;
 
    public GenericServlet() {
    }
 
    public void destroy() {
    }
 
    public String getInitParameter(String name) {
        ServletConfig sc = this.getServletConfig();
        if (sc == null) {
            throw new IllegalStateException(lStrings.getString("err.servlet_config_not_initialized"));
        } else {
            return sc.getInitParameter(name);
        }
    }
 
    public Enumeration<String> getInitParameterNames() {
        ServletConfig sc = this.getServletConfig();
        if (sc == null) {
            throw new IllegalStateException(lStrings.getString("err.servlet_config_not_initialized"));
        } else {
            return sc.getInitParameterNames();
        }
    }
 
    public ServletConfig getServletConfig() {
        return this.config;
    }
 
    public ServletContext getServletContext() {
        ServletConfig sc = this.getServletConfig();
        if (sc == null) {
            throw new IllegalStateException(lStrings.getString("err.servlet_config_not_initialized"));
        } else {
            return sc.getServletContext();
        }
    }
 
    public String getServletInfo() {
        return "";
    }
 
    public void init(ServletConfig config) throws ServletException {
        this.config = config;
        this.init();
    }
 
    public void init() throws ServletException {
    }
 
    public void log(String msg) {
        this.getServletContext().log(this.getServletName() + ": " + msg);
    }
 
    public void log(String message, Throwable t) {
        this.getServletContext().log(this.getServletName() + ": " + message, t);
    }
 
    public abstract void service(ServletRequest var1, ServletResponse var2) throws ServletException, IOException;
 
    public String getServletName() {
        ServletConfig sc = this.getServletConfig();
        if (sc == null) {
            throw new IllegalStateException(lStrings.getString("err.servlet_config_not_initialized"));
        } else {
            return sc.getServletName();
        }
    }
}

Because it is not our focus, so we are not too much to explain.



HttpServlet abstract class

One would think GenericServlet abstract class has been very easy, then why not?
Qiang Qiang Qiang, it is because our protagonist, HttpServlet abstract class is more powerful, it is in the end stronger in what way, I will list them below.
First we look at the statement of HttpServlet:

public abstract class HttpServlet extends GenericServlet implements Serializable 

Obviously, it inherits the GenericServlet abstract class and implement the Serializable interface. Naturally inherits the advantages GenericServlet have.



HttpServlet powerful than GenericServlet place mainly in the following two points:

  • Strong turn two parameters HttpServletRequest and HttpServletResponse, overloaded call -Service () method
  • Acquisition request mode, depending on the different ways invocation request doXxx () method

To understand the second, first let's look at how to implement HttpServlet Service () method:

public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
        HttpServletRequest request;
        HttpServletResponse response;
        try {
            request = (HttpServletRequest)req;
            response = (HttpServletResponse)res;
        } catch (ClassCastException var6) {
            throw new ServletException("non-HTTP request or response");
        }

        this.service(request, response);
    }

We can see, HttpServlet abstract class, upon receiving the ServletRequest and ServletResponse object with its strong into HttpServletRequest and HttpServletResponse type, has been able to enforce such a conversion, because when you call Service method of Servlet, Servlet container always pass into a HttpServletRequest object and HttpServletResponse objects, ready to use HTTP.
After the call parameters have yet to HttpServletRequest and HttpServletResponse type of Service () method, this method is how to achieve it?

protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getMethod();
        long lastModified;
        if (method.equals("GET")) {
            lastModified = this.getLastModified(req);
            if (lastModified == -1L) {
                this.doGet(req, resp);
            } else {
                long ifModifiedSince;
                try {
                    ifModifiedSince = req.getDateHeader("If-Modified-Since");
                } catch (IllegalArgumentException var9) {
                    ifModifiedSince = -1L;
                }

                if (ifModifiedSince < lastModified / 1000L * 1000L) {
                    this.maybeSetLastModified(resp, lastModified);
                    this.doGet(req, resp);
                } else {
                    resp.setStatus(304);
                }
            }
        } else if (method.equals("HEAD")) {
            lastModified = this.getLastModified(req);
            this.maybeSetLastModified(resp, lastModified);
            this.doHead(req, resp);
        } else if (method.equals("POST")) {
            this.doPost(req, resp);
        } else if (method.equals("PUT")) {
            this.doPut(req, resp);
        } else if (method.equals("DELETE")) {
            this.doDelete(req, resp);
        } else if (method.equals("OPTIONS")) {
            this.doOptions(req, resp);
        } else if (method.equals("TRACE")) {
            this.doTrace(req, resp);
        } else {
            String errMsg = lStrings.getString("http.method_not_implemented");
            Object[] errArgs = new Object[]{method};
            errMsg = MessageFormat.format(errMsg, errArgs);
            resp.sendError(501, errMsg);
        }

    }

It can be seen or not implement any service logic in the service method, but according to the method of HttpServletRequest parameters, call one of the following methods: doGet (), doPost (), doHead (), doPut (), doTrace (), doOptions () and doDelete (). These seven methods, each method represents a method Http. doGet () and doPost () is the most common. So, if we need to implement specific service logic, no longer need to override Service () method, just need to override the doGet () or doPost () just fine.

Guess you like

Origin blog.csdn.net/qq_42267300/article/details/86773088