Servlet basic knowledge and application


1. Overview of Servlet

  • Servlet is a small java program running on the web server, used to process the request sent from the web client, and respond to the request;
  • Use Servlet :
    Write a java class to implement the Servlet interface;
    configure Servlet;

2. Getting started with Servlet

1. Create packages and classes

Insert picture description here

2. Let this class implement the Servlet interface

The service method is mainly rewritten here;

package ServletDemo1;
import javax.servlet.*;
import java.io.IOException;

/**
 * Servlet 的入门程序
 */
public class HelloServlet implements Servlet {
    
    
    @Override
    public void init(ServletConfig servletConfig) throws ServletException {
    
    

    }

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

    /*
        这里主要用这个方法
        用来处理客户请求,并对请求作出响应;
     */
    @Override
    public void service(ServletRequest req, ServletResponse resp) throws ServletException, IOException {
    
    
        //向页面输出内容
        resp.getWriter().println("hello Servlet!!!");
    }

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

    @Override
    public void destroy() {
    
    

    }
}

3. Configure this class in web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">

    <!-- 配置Servlet -->
    <servlet>
        <!-- 配置 Servlet 的名称 -->
        <servlet-name>HelloServlet</servlet-name>
        <!-- 配置 Servlet 的全路径 -->
        <servlet-class>ServletDemo1.HelloServlet</servlet-class>
    </servlet>

    <!-- 配置Servlet 的一个映射-->
    <servlet-mapping>
        <!-- 配置 Servlet 的名称 -->
        <servlet-name>HelloServlet</servlet-name>
        <!-- 配置访问路径 -->
        <url-pattern>/hello</url-pattern>
    </servlet-mapping>
</web-app>

4. Access Servlet

Insert picture description here

Three, Servlet execution process

Insert picture description here

Fourth, the realization relationship of Servlet

1. Basic realization relationship

Servlet interface
|
GenericServlet class: general Servlet, a servlet independent of the protocol;
|
HttpServlet class: HTTP-specific Servlet;

2. Overview of relationship realization

  • Usually writing a servlet will make this servlet inherit HttpServlet and rewrite the service method;
  • In the service method, different doXXX methods will be executed according to different request methods;
    (get request executes doGet method, post request executes doPost method)
  • So often after inheriting HttpServlet, there is no need to rewrite the service method , just rewrite doGet and doPost ;
  • Usually the code to be processed by the request is the same, so you need to make doGet and doPost call each other , which can simplify programming;
package ServletDemo2;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class HelloServlet2 extends HttpServlet {
    
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
        //如果是GET请求,就会执行doGet中的代码
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
        //如果是POST请求,就会执行doPost中的代码
        resp.getWriter().println("HelloServlet22222222");
    }
}

Insert picture description here

3. Create Servlet in IDEA

(You can create Servlet directly without configuring information in web.xml)
Insert picture description here

Five, Servlet life cycle

1. Overview of Servlet Life Cycle

  • Life cycle : the process of an object from creation to destruction;
  • The Servlet will be instantiated when it is accessed for the first time. As long as the Servlet is instantiated, the init method will be executed (the init method will only be executed once);
  • For any request sent from the client, the service method will be executed (different doXxx methods are called within the service according to different request methods);
  • When the Servlet is removed from the server or the server is shut down, the Servlet object will be destroyed, the destroy method inside will be executed, and then the garbage collection will recycle it;

6. Servlet loading at startup

1. Reasons for loading at startup

  • Assuming some time-consuming operations are done in the init method , when the first user accesses this object for the first time, the waiting time is long;
  • So you need to change the Servlet to load at startup ;
  • That lets you create objects Servlet server at startup , before such time-consuming operation will cost at server startup, users do not need to spend extra time;

2. Load when the configuration is complete

Configure in web.xml
Insert picture description here

Seven, Servlet access path configuration

1. Servlet in <url-pattern>the arrangement

  • Exact path match
    to /start;
  • Directory matches
    to /begin to /*end;
  • Extension matches
    can not begin with /, is *beginning

Insert picture description here

2. Priority of access

Full path matching> directory matching> extension matching

Eight, ServletConfig object

1 Overview

  • ServletConfig is used to obtain related configuration objects of Servlet;

Nine, ServletContext object-get web project information

1. Overview of ServletContext Object

  • ServletContext: Servlet context object ; ServletContext object knows the content before and after the servlet;
  • There is only one ServletContext object per web project;
  • Create a separate ServletContext object for each web project when the server starts;

2. The role of the ServletContext object:

Get web project information

  • Get the MIME type of the file;
  • Get the project name of the web request;
  • Get the initialization parameters of the web project;

Ten, ServletContext object-read the file under the web project

1. The second role of the ServletContext object:

Read files under web project

  • Previously, files can be read using IO streams, but now to get files under web projects, errors will occur when using traditional IO streams;
  • Read file code under web project

11. ServletContext object-access data as a domain object

1. Domain Objects

  • Domain object : refers to the data stored in the domain object, this data will have a certain scope;
  • Domain : refers to a certain scope of action;

2. Three functions of the ServletContext object:

Access data as domain objects

  • Method of storing data;
  • Method of obtaining data;
  • Method of removing data;

3. ServletContext as the scope of the domain object

Scope: the entire web server;

12. Response object

1. Overview of Response Object

  • B/S structured software can access the server through a browser;

Insert picture description here

2. Response object API

(1) About the method of response line

  • setStatus(int sc)
    Set the response status code;

(2) About the method of response header

  • setHeader(String name, String value)
    The method at the beginning of set: a key corresponds to a value situation;
  • addHeader(String name, String value)
    The method at the beginning of Add: one key corresponds to multiple values;

(3) About the method of the responder

  • getOutputStream()
  • getWriter()

3. Chinese garbled processing of Response object response

(1) Use byte stream to process Chinese
Insert picture description here
(2) Use character stream to process Chinese
Insert picture description here

13. Request object

1. Overview and API of Request Object

(1) Obtain client information

  • getMethod()
    How to get the request;
  • getQueryString()
    Submit the parameter string after obtaining the request path;
  • getRequestURI(), getRequestURL()
    Get the URI and URL of the request path;
  • getRemoteAddr()
    Obtain the IP address of the client;

(2) Method of obtaining request header

  • getHeader(String name)
    Obtain a request header with a key corresponding to a value;
  • getHeaders(String name)
    Obtain a request header with a key corresponding to multiple values;

(3) Method of obtaining request parameters

  • getParameter(String name)
    Used to get the submitted parameters (a name corresponds to a value);
  • getParameterValues(String name)
    Used to get the submitted parameters (a name corresponds to multiple values);
  • getParameterMap(String name)
    Used to get the submitted parameters (encapsulate the submitted parameter names and corresponding values ​​into a map);

(4) Request is a method of accessing data as a domain object

  • setAttribute(String name, Object o)
    Store data in the request field;
  • getAttribute(String name)
    Get data from the request field;
  • removeAttribute(String name)
    Remove data from the request field;

2. The Request object receives form request parameters

Insert picture description here
Insert picture description here

3. Chinese garbled processing of the request object receiving form request parameters

(1) Handling Chinese garbled characters by get
Insert picture description here

(2) Handling Chinese garbled characters in post
Insert picture description here

Guess you like

Origin blog.csdn.net/pary__for/article/details/111377721