JavaEE Foundation (02):Servlet Core API Usage Detailed

Keywords: Java github Tomcat network

Source code for this article: GitHub. Click here || GitEE. Click here

1. Introduction to Core API s

1. Servlet Execution Process

Servlet is one of the three components of JavaWeb (Servlet, Filter, Listener), which is a dynamic resource.Servlets are used to process requests, and the server hands the received requests to the Servlet for processing. In Servlets, you usually need to: receive request data; process requests; and complete responses.

2. Introduction to Core API s

API Role description
ServletConfig Gets the servlet initialization parameters and the servletContext object.
ServletContext Share data between dynamic resources throughout the Web application.
ServletRequest Encapsulates Http request information and creates it when requested.
ServletResponse Encapsulates the Http response information and creates it when requested.

2. ServletConfig interface

1. Introduction to interfaces

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

2. Code Cases

  • configuration file
<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>
  • API Usage
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. Introduction to interfaces

A project has only one ServletContext object, which can be retrieved from multiple Servlets and used to pass data to multiple Servlets. The object is created when Tomcat starts and destroyed when Tomcat closes!The purpose is to share data between dynamic resources throughout the Web application.

  • Getting Method
1,ServletConfig#getServletContext();
2,GenericServlet#getServletContext();
3,HttpSession#getServletContext()
4,ServletContextEvent#getServletContext()

2. Four Domain Objects

ServletContext is one of the four domain objects for JavaWeb:

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

All domain objects have access to data because there is a Map inside the domain object to store data.

3. Code Cases

  • configuration file
<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>
  • API Usage
public class ServletTwoImpl extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        // 1. Parameter Transfer
        ServletContext servletContext = this.getServletContext() ;
        String value = String.valueOf(servletContext.getAttribute("cicada")) ;
        System.out.println("value="+value);
        // 2. Get initialization parameters
        String myBlog = servletContext.getInitParameter("my-blog") ;
        System.out.println("myBlog="+myBlog);
        // 3. Obtaining application information
        String servletContextName = servletContext.getServletContextName() ;
        System.out.println("servletContextName="+servletContextName);
        // 4. Get Path
        String pathOne = servletContext.getRealPath("/") ;
        String pathTwo = servletContext.getRealPath("/WEB-INF/") ;
        System.out.println("pathOne="+pathOne+";pathTwo="+pathTwo);
        response.getWriter().print("Execution: doGet; value: "+value);
    }
}

4. ServletRequest interface

1. Introduction to interfaces

The HttpServletRequest interface inherits the ServletRequest interface, which encapsulates request information by creating and passing in the service() method of the servlet each time the user requests the servlet, in which the incoming servletRequest is forced to be converted into an HttpservletRequest object to process HTTP request information.Core role: 1. Get request message information; 2. Get network connection information; 3. Get request domain attribute information.

2. Code Cases

  • configuration file
<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>
  • API Usage
public class ServletThreeImpl extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, 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. Introduction to interfaces

HttpServletResponse inherits from ServletResponse and encapsulates the Http response information.For each request from the client, the server creates a response object and passes it to the Servlet.service() method.Core role: 1. Set response header information; 2. Send status code; 3. Set response body; 4. Redirect;

2. Code Cases

  • configuration file
<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>
  • API Usage
public class ServletFourImpl extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8") ;
        response.setCharacterEncoding("UTF-8");
        response.setStatus(200) ;
        response.getWriter().print("Hello,Cicada");
    }
}

3. Forwarding and redirection

  • Forward

Control of page jumps on the server side;

request.getRequestDispatcher("/Forward Address").forward(request, response);
  • redirect

The server responds to the jump information and the browser page jumps.

response.sendRedirect("Redirect Address");
  • Forwarding and redirection comparison
Difference Forward redirect
Address bar Unchanged change
Jump Service-side Jump Browser-side Jump
Number of requests Once Twice
Data in Domain Will not be lost Lose

6. Source code address

GitHub·address
https://github.com/cicadasmile/java-base-parent
GitEE·address
https://gitee.com/cicadasmile/java-base-parent

Posted by Zemnon on Tue, 10 Dec 2019 17:01:02 -0800