Java EE Foundation (02): detailed explanation of servlet core API usage

1、 Introduction to core API

1. Servlet execution process

Servlet is one of the three major components of Java Web (servlet, filter and listener). It belongs to dynamic resources. The role of servlet is to process requests. The server will hand over the received requests to the servlet for processing. In the servlet, you usually need to: receive request data; process requests; and complete responses.

2. Introduction to core API

2、 ServletConfig interface

1. Interface introduction

When the container initializes the servlet, it creates a ServletConfig object for the servlet, passes the object through the init () method and saves it in this servlet object. Core role: 1 Obtain initialization information; 2. Get the ServletContext object.

2. Code case

<servlet>
    <init-param>
        <param-name>my-name</param-name>
        <param-value>cicada</param-value>
    </init-param>
    <servlet-name>servletOneImpl</servlet-name>
    <servlet-class>com.node02.servlet.impl.ServletOneImpl</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>servletOneImpl</servlet-name>
    <url-pattern>/servletOneImpl</url-pattern>
</servlet-mapping>
public class ServletOneImpl implements Servlet {

    @Override
    public void init(ServletConfig servletConfig) throws ServletException {
        String servletName = servletConfig.getServletName() ;
        System.out.println("servletName="+servletName);
        String myName = servletConfig.getInitParameter("my-name") ;
        System.out.println("myName="+myName);
        Enumeration paramNames = servletConfig.getInitParameterNames() ;
        while (paramNames.hasMoreElements()){
            String paramKey = String.valueOf(paramNames.nextElement()) ;
            String paramValue = servletConfig.getInitParameter(paramKey) ;
            System.out.println("paramKey="+paramKey+";paramValue="+paramValue);
        }
        ServletContext servletContext = servletConfig.getServletContext() ;
        servletContext.setAttribute("cicada","smile");
    }
}

3、 ServletContext interface

1. Interface introduction

A project has only one ServletContext object, which can be obtained from multiple servlets. It can be used to transfer data to multiple servlets. The object is created when Tomcat is started and will be destroyed when Tomcat is closed! The function is to share data among dynamic resources of the whole web application.

1、ServletConfig#getServletContext();
2、GenericServlet#getServletContext();
3、HttpSession#getServletContext()
4、ServletContextEvent#getServletContext()

2. Four domain objects

ServletContext is one of the four domain objects of Java Web:

1、PageContext;
2、ServletRequest;
3、HttpSession;
4、ServletContext;

All domain objects have the function of accessing data, because there is a map inside the domain object to store data.

3. Code case

<context-param>
    <param-name>my-blog</param-name>
    <param-value>2019-11-19</param-value>
</context-param>
<servlet>
    <servlet-name>servletTwoImpl</servlet-name>
    <servlet-class>com.node02.servlet.impl.ServletTwoImpl</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>servletTwoImpl</servlet-name>
    <url-pattern>/servletTwoImpl</url-pattern>
</servlet-mapping>
public class ServletTwoImpl extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request,HttpServletResponse response)
            throws ServletException,IOException {
        response.setContentType("text/html;charset=utf-8");
        // 1、参数传递
        ServletContext servletContext = this.getServletContext() ;
        String value = String.valueOf(servletContext.getAttribute("cicada")) ;
        System.out.println("value="+value);
        // 2、获取初始化参数
        String myBlog = servletContext.getInitParameter("my-blog") ;
        System.out.println("myBlog="+myBlog);
        // 3、获取应用信息
        String servletContextName = servletContext.getServletContextName() ;
        System.out.println("servletContextName="+servletContextName);
        // 4、获取路径
        String pathOne = servletContext.getRealPath("/") ;
        String pathTwo = servletContext.getRealPath("/WEB-INF/") ;
        System.out.println("pathOne="+pathOne+";pathTwo="+pathTwo);
        response.getWriter().print("执行:doGet; value:"+value);
    }
}

4、 ServletRequest interface

1. Interface introduction

The HttpServletRequest interface inherits the ServletRequest interface and is used to encapsulate the request information. This object creates and passes in the service () method of the servlet every time the user requests the servlet. In this method, the passed in ServletRequest will be forcibly transformed into an HttpServletRequest object to process the HTTP request information. Core role: 1 Obtain request message information; 2. Obtain network connection information; 3. Get the request domain attribute information.

2. Code case

<servlet>
    <servlet-name>servletThreeImpl</servlet-name>
    <servlet-class>com.node02.servlet.impl.ServletThreeImpl</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>servletThreeImpl</servlet-name>
    <url-pattern>/servletThreeImpl</url-pattern>
</servlet-mapping>
public class ServletThreeImpl extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request,IOException {
        // http://localhost:6003/servletThreeImpl?myName=cicada
        String method = request.getmethod();
        System.out.println("method="+method); // GET
        String requestURL = request.getRequestURL().toString();
        // http://localhost:6003/servletThreeImpl
        System.out.println("requestURL="+requestURL);
        String requestURI = request.getRequestURI();
        System.out.println("requestURI="+requestURI); // /servletThreeImpl
        String queryString = request.getQueryString() ;
        System.out.println("queryString="+queryString); // myName=cicada
        String myName = request.getParameter("myName");
        System.out.println("myName="+myName); // cicada
    }
}

5、 Servletresponse interface

1. Interface introduction

Httpservletresponse inherits from servletresponse and encapsulates the HTTP response information. For each request from the client, the server will create a response object and pass it to the servlet Service() method. Core role: 1 Set response header information; 2. Send status code; 3. Set response text; 4. Redirection;

2. Code case

<servlet>
    <servlet-name>servletFourImpl</servlet-name>
    <servlet-class>com.node02.servlet.impl.ServletFourImpl</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>servletFourImpl</servlet-name>
    <url-pattern>/servletFourImpl</url-pattern>
</servlet-mapping>
public class ServletFourImpl extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request,IOException {
        response.setContentType("text/html;charset=utf-8") ;
        response.setCharacterEncoding("UTF-8");
        response.setStatus(200) ;
        response.getWriter().print("Hello,知了");
    }
}

3. Forwarding and redirection

Control of page Jump at the server;

request.getRequestDispatcher("/转发地址").forward(request,response);

The server responds to the jump information, and the browser performs page Jump;

response.sendRedirect("重定向地址");

6、 Source code address

GitHub·地址
https://github.com/cicadasmile/java-base-parent
GitEE·地址
https://gitee.com/cicadasmile/java-base-parent
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>