So detailed Servlet tutorial, don't you come to have a look?

1. Servlet program

1.1 what is Servlet

  1. Servlet is one of the Java EE specifications (interfaces)
  2. Servlet is one of the three components of Java Web. The three components are: servlet program, Filter filter, Listener listener
  3. Servlet is a Java applet running on the server, which is used to receive the data sent by the client and respond to the client at the same time

1.2 how to create and implement Servlet interface manually

  1. First, write a class to implement the Servlet interface
  2. Override the service method to process client requests while responding to data
package com.cunyu.servlet;

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

/**
 * Created with IntelliJ IDEA.
 * Version : 1.0
 * Author  : Village Yuyao
 * Email   : cunyu1024@foxmail.com
 * Website : https://cunyu1943.github.io
 * Official account: Village rain
 * Date    : 2020/6/4 3:08 PM
 * Project : JavaLearning
 * Package : com.cunyu.servlet
 * Class   : HelloServlet
 * Desc    : Hello Launch page
 */
public class HelloServlet extends HttpServlet {
    /**
     * service Methods dedicated to handling requests and responses
     *
     * @param req  request
     * @param resp response
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("Hello Servlet´╝îMy first Servlet App!");
    }
}
  1. After completing the above steps, go to web.xml The access address of the Servlet interface configured in
<?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">
    
    <!--  to Tomcat to configure Servlet program -->
    <servlet>
        <!--    Servlet Program alias (class name recommended)    -->
        <servlet-name>HelloServlet</servlet-name>
        <!--    Servlet Full class name of the program    -->
        <servlet-class>com.cunyu.servlet.HelloServlet</servlet-class>
    </servlet>

    <!--  to Servlet Program configuration access address  -->
    <servlet-mapping>
        <!--    Tell the server which address is currently configured Servlet Program use    -->
        <servlet-name>HelloServlet</servlet-name>
        <!--    Configure the access address, which means the address is http://ip:port / Project path / hello -- >
        <url-pattern>/hello</url-pattern>
    </servlet-mapping>
</web-app>
  1. Start Tomcat to access in browser http://localhost:8080/servletTest/hello, and then the service() method will be executed in the background

1.3 Servlet life cycle

  1. Execute the Servlet constructor method, only when the Servlet program is created on the first access, it will call
  2. Execute init initialization method, only when the Servlet program is created on the first access, it will call
  3. Execute the service() method, which is called every time
  4. Execute destroy() destroy method, called when the Web project stops

1.4 how to create Servlet program quickly through IDEA

Select the src directory or the package to generate the Servlet, right-click, new - > create new Servlet, fill in the Servlet program name, the package and the full class name of the Servlet, and uncheck Java EE 6 at the same time. If checked, the annotation configuration will be generated, which will be contacted in the subsequent learning process.

After clicking generate, the Servlet program will be generated and web.xml Configuration in.

1.5 inheritance system of the entire Servlet class

2. ServletConfig class

As can be seen from the class name, ServletConfig is a configuration information class. Both the Servlet program and the ServletConfig object are created by Tomcat, and we just need to use them. In addition, the Servlet program is created at the first access by default, and the ServletConfig object is created for each Servlet program.

2.1 three functions of ServletConfig class

  1. Gets the alias of the servlet program, that is web.xml Servlet name configured in
  2. Get initialization parameters, that is web.xml Init param configured in
  3. Get ServletContext object

Join us web.xml The configuration is as follows, and then the initialization method can be used to obtain the above three values:

<?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">

    <!--  to Tomcat to configure Servlet program -->
    <servlet>
        <!--    Servlet Program alias (class name recommended)    -->
        <servlet-name>HelloServlet</servlet-name>
        <!--    Servlet Full class name of the program    -->
        <servlet-class>com.cunyu.servlet.HelloServlet</servlet-class>

        <init-param>
            <param-name>userName</param-name>
            <param-value>root</param-value>
        </init-param>
    </servlet>


    <!--  to Servlet Program configuration access address  -->
    <servlet-mapping>
        <!--    Tell the server which address is currently configured Servlet Program use    -->
        <servlet-name>HelloServlet</servlet-name>
        <!--    Configure the access address, which means the address is http://ip:port / Project path / hello -- >
        <url-pattern>/hello</url-pattern>
    </servlet-mapping>


</web-app>
package com.cunyu.servlet;

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

/**
 * Created with IntelliJ IDEA.
 * Version : 1.0
 * Author  : Village Yuyao
 * Email   : cunyu1024@foxmail.com
 * Website : https://cunyu1943.github.io
 * Official account: Village rain
 * Date    : 2020/6/4 3:08 PM
 * Project : JavaLearning
 * Package : com.cunyu.servlet
 * Class   : HelloServlet
 * Desc    : Hello Launch page
 */
public class HelloServlet extends HttpServlet {
    /**
     * service Methods dedicated to handling requests and responses
     *
     * @param req  request
     * @param resp response
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("Hello Servlet´╝îMy first Servlet App!");
    }

    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        System.out.println("Initialization method");
//        Get Servlet program alias Servlet name
        System.out.println("Alias:" + config.getServletName());
//        Get initialization parameter init param
        System.out.println("Initialization parameters:" + config.getInitParameter("userName"));
//        Get ServletContext object
        System.out.println(config.getServletContext());
    }
}

3. ServletContext class

3.1 what is ServletContext

  1. ServletContext is an interface that represents a Servlet context object
  2. The ServletContext object is a domain object
  3. Each Web project only corresponds to one ServletContext object instance
  4. Each ServletContext is created when the Web project deployment starts and then destroyed when the Web project stops

3.2 the role of ServletContext

  1. obtain web.xml Context param in configuration
  2. Get the current Web project path, such as / ServletTest
  3. Obtain the absolute path in the server after project deployment, including various static resources and other paths
  4. ServletContext accesses data through key value pairs (maps)

The following is an example of the above four functions. First, in web.xml Add the following configuration, and then obtain various parameters through the program:

<!--context-param Is a context parameter of Web engineering-->
    <context-param>
        <param-name>wechat</param-name>
        <param-value>cunyu1943</param-value>
    </context-param>

    <servlet>
        <servlet-name>ServletContextServlet</servlet-name>
        <servlet-class>com.cunyu.servlet.ServletContextServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>ServletContextServlet</servlet-name>
        <url-pattern>/servletContext</url-pattern>
    </servlet-mapping>
package com.cunyu.servlet;

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

/**
 * Created with IntelliJ IDEA.
 * Version : 1.0
 * Author  : Village Yuyao
 * Email   : cunyu1024@foxmail.com
 * Website : https://cunyu1943.github.io
 * Official account: Village rain
 * Date    : 2020/6/5 8:36 am
 * Project : JavaLearning
 * Package : ${PACKAGE_NAME}
 * Class   : ${CLASS_NAME}
 * Desc    : ServletContext function
 */
public class ServletContextServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//        1. Get the context parameter context param
        ServletContext servletContext = getServletContext();
        String url = servletContext.getInitParameter("url");
        System.out.println("URL The values for are:" + url);

//        2. obtain the project path
        System.out.println("Project path:" + servletContext.getContextPath());

//        3. Obtain the absolute path on the server after project deployment
//        Where / is resolved as: http://ip:port / project name /, mapped to the web directory of the IDEA code
        System.out.println("Absolute path of project deployment:" + servletContext.getRealPath("/"));

//        4. Access data through key value pairs. Note: ServletContext belongs to Web project, so as long as the project is started and created, the Servlet program can access it until the Web project is shut down
        System.out.println("ServletContext object:" + servletContext);
//        Save data
        servletContext.setAttribute("password", "1234567");
//        Access to data
        System.out.println("password The values for are:" + servletContext.getAttribute("password"));
    }
}

4. HTTP protocol

4.1 what is HTTP protocol

An agreement is a rule that everyone must abide by after two or more parties have reached a certain agreement through negotiation. It is called an agreement.

The HTTP protocol refers to the rules that need to be followed when sending data when the client and server communicate with each other. The data in HTTP protocol is also called message.

4.2 HTTP protocol format of request

The behavior of the client sending data to the server is called request, while the behavior of the server returning data to the client is called response.

GET request

The request line consists of the request line + request header. The request line includes the request method, the requested resource path and the requested protocol version number. The request header consists of key value pairs. Different key value pairs have different meanings. See the following example for details. Where GET requests are most commonly used:

  1. form label method=get
  2. a label
  3. link tag introduced to css
  4. Script tag introduction js
  5. img tag introduction picture
  6. iframe introduces HTML page
  7. Enter the address in the address bar of browser and press enter

POST request

The biggest difference between POST request and GET is the request header (i.e. the data sent to the server). POST consists of request line + request header + request body. The meaning of request line and request header is the same as that of GET request, while the request header is unique to POST. The specific meaning is as follows, the most commonly used place:

  1. form label method=post

4.3 HTTP protocol format of response

The response is mainly composed of response line + response header + response body. The response line includes the response protocol and version number, response status code and response status descriptor. The response header is also composed of different key value pairs, and the response body is the data returned to the client. See the following example for details:

4.4 common response codes

Response code explain
200 Request succeeded
302 request redirections
404 The request server has received, but the required data does not exist (wrong request address)
500 The server has received the request, but the server has an internal error (code error)

4.5 MIME type description

The full name of mime is the multi purpose Internet mail extension, which is the data type in HTTP protocol. The format is large type / small type and corresponds to a file extension. The most common MIME types are as follows:

file type File extension MIME type
Hypertext markup language text .html,.htm text/html
Plain text .txt text/plain
Rich text .rtf application/rtg
GIF graphics .gif image/gif
JPEG graphics .jpeg,.jpg image/jpeg
au sound file .au audio/basic
MIDI music files .mid,.midi audio/midi,audio/x-midi
RealAudio music files .ra,.ram audio/x-pn-realaudio
MPEG files .mpg,.mpeg video/mpeg
AVI file .avi video/x-msvideo
GZIP file .gz application/x-gzip
TAR file .tar application/x-tar

5 HttpServletRequest class

5.1 function of HttpServletRequest class

Every time the Tomcat server receives a Request from the browser, the Tomcat server will parse and encapsulate the HTTP protocol information from the Request into the Request object, and then pass it to the service methods (doGet and doPost) for the browser to use. We can get all the requested information through the HttpServletRequest object.

5.2 common methods of HttpServletRequest class

method explain
getRequestURI() Get the requested resource path
getRequestURL() Get the uniform resource locator of the request (absolute path)
getRemoteHost() Get ip of client
getHeader() Get request header
getParameter() Get requested parameters
getParameterValues() Get requested parameters (multiple values)
getMethod() GET or POST to GET the request
setAttribute(key, value) Set domain data
getAttribute(key) Get domain data
getRequestDispatcher() Get request forwarding object

5.3 Chinese scrambling in post and GET requests

When the request is made by POST or GET, the Chinese character may be garbled. The corresponding solution is as follows:

  • POST mode: directly set the character set of the request body to UTF-8
  • GET mode: first encode with iso8859-1, then decode with UTF-8
package com.cunyu.servlet;

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

/**
 * Created with IntelliJ IDEA.
 * Version : 1.0
 * Author  : Village Yuyao
 * Email   : cunyu1024@foxmail.com
 * Website : https://cunyu1943.github.io
 * Official account: Village rain
 * Date    : 2020/6/6 9:18 PM
 * Project : JavaLearning
 * Package : ${PACKAGE_NAME}
 * Class   : ${CLASS_NAME}
 * Desc    : Chinese scrambling problem of getting request parameters
 */
public class ParameterServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        POST Chinese garbled, set the request body character set UTF-8, before calling parameters.
        req.setCharacterEncoding("UTF-8");
        System.out.println(req.getParameter("hobby"));

    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");

//        GET Chinese garbled
//        Code with iso8859-1 first
//        Then decode it with UTF-8
        username = new String(username.getBytes("ISO-8859-1"), "UTF-8");
        System.out.println("user name:" + username);
        System.out.println("password:" + password);
    }
}

5.4 request forwarding

definition

The forward of request is the operation that when the server receives the request from the client, it jumps from one resource to another.

characteristic

  • Address bar unchanged
  • Belongs to a request
  • Sharing parameters in the Request domain
  • It can be forwarded to the WEB-INF directory
  • Cannot access resources outside of project

5.5 function of base tag

It is used to set the path referenced when the page relative path works, and jump by referring to an address.

<base href="https:cunyu1943.github.io">

5.6 different meanings of / in the web

In the Web / is an absolute path. If it is parsed by the browser, the resulting address is: http:/ip:port /; if it is parsed by the server, the resulting address is: http://ip:port / Project path.

be careful: response.sendRedirect("/");, which means to send / send to the browser for resolution, and get http://ip:port/

6. HttpServletResponse class

6.1 role of httpservletresponse

As with the HttpServletRequest class, every time a request from a client comes in, the server creates a Response object and passes it to the Servlet program. HttpServletRequest represents the information from the request, and HttpServletResponse represents the information of all responses. When setting the information returned by the server to the client, it is done through the HttpServletResponse object.

6.2 two output streams

The output stream is divided into byte stream and character stream. The corresponding methods and functions are shown in the table below. When we use them, we can only use one of them at the same time.

Output stream type method function
Byte stream getOutputStream() Commonly used for downloading (passing binary data)
Character stream getWriter() Commonly used for returning strings

6.3 how to return data and Chinese code to the client

Generally, we need to return data to the client. If we want to return data such as strings, we can use the character stream method getWriter().

public class ResponseIOServlet extends HttpServlet{
    @Override
    protected void doGet(HttpServletRequest req, HttpSevletResponse resp) throws ServletException, IOException{
        // Return string data to client
        PrintWriter writer = resp.getWriter();
        writer.write("response's content!!!");
    }
}

However, when we send back Chinese, there may be a garbled code problem. To solve this problem, there are usually two solutions:

  1. Set the server character set to UTF-8, and set the browser to use UTF-8 character set through the response header
// Set server character set
resp.setCharacterEncoding("UTF-8");
// Set browser character set via response header
resp.setHeader("Content-Type", "text/html;charset=UTF-8");
  1. At the same time, both the server and the client are set up using the UTF-8 character set, but it must be called before obtaining the stream object.
// Set both server and client character sets
resp.setContentType("text/html;charset=UTF-8")

6.4 request redirection

definition

Request redirection refers to that the client sends a request to the server, and then the server sends back some addresses to the client, and the client accesses. It's called redirection because the previous address may have been discarded.

characteristic

  1. Address bar change
  2. Two requests
  3. Do not share data in Request domain
  4. Cannot redirect to the resource under the WEB-INF directory
  5. Access to resources outside the project

Two ways to achieve redirection

  1. Set the response status code 302 to indicate redirection, and then specify the new address by setting the response header
// Set response status code
resp.setStatus(302);
// Specify the new address by setting the response header
resp.setHeader("Location", "https://cunyu1943.github.io");
  1. Directly use sendRedirect() method to set the new address, which is more recommended
resp.sendRedirect("https://cunyu1943.github.io");

Resource download

It is recommended that you pay attention to the official account of the village, and the article will be released here.

Resource classification

Screenshot of some resources

Tags: Java xml github JavaEE

Posted on Sun, 07 Jun 2020 03:55:24 -0700 by gibbo101