Servlet&HTTP&Request Notes

Keywords: Java Network Protocol http

Servlet&HTTP&Request Notes

1. Architecture of Servlet

Servlet - Interface

GenericServlet - Abstract Class

HttpServlet - Abstract Class

  • GenericServlet: Default empty implementation of the rest of the Servlet interface, using only the service() method as an abstraction
    • When defining a Servlet class in the future, you can inherit the GenericServlet and implement the service() method. Other methods are optional.
@WebServlet("/demo2")
public class ServletDemo2 extends GenericServlet {
    @Override
    public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
        System.out.println("demo2......");
    }
}
  • HttpServlet: An encapsulation of the http protocol to simplify operations.
    • 1. Definition class inherits HttpServlet
    • 2. Override doGet/doPost method
@WebServlet("/demo3")
public class ServletDemo3 extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("doGet Method....");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("doPost Method....");
    }
}

2.Servlet-related configuration

1.urlpartten:Servlet access path

1. A Servlet can define multiple access paths

//Any of these three paths can be accessed by writing one in the browser
@WebServlet({"/d4","/demo4","demo444"})

2. Path Definition Rules:

1. /xxx: path matching

2. /xxx/xxx: multi-layer path, directory structure

3. *.do: Extension matching

/**
 * Servlet Path Configuration
 */

//@WebServlet ({'/d4', /demo4','demo444'})//Any of these three paths can be accessed by writing one in the browser
//@WebServlet("/user/demo4")
//@WebServlet ("/user/*")//user Write freely after
//@WebServlet("/*")
@WebServlet("*.do")
public class ServletDemo4 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("demo4....");
    }
}

3.HTTP

3.1 Concepts

Hyper Text Transfer Protocol Hypertext Transfer Protocol

Transport protocol: Defines the format in which data is sent when clients and servers communicate.

Features:

1. Advanced TCP/IP based protocols

2. Default port number: 80

3. Based on the request/response model: one request corresponds to one response

4. Stateless: Each request is independent of each other and cannot interact with data.

[External chain picture transfer failed, source station may have anti-theft chain mechanism, it is recommended to save pictures and upload them directly (img-xtBgu51q-163698350) (D:zhangpanJavaPDFself-study notes http transport protocol.png)]

3.2 Request message data format

1. Request line

Request mode request url request protocol/version

​ GET /login.html HTTP/1.1

Request method:

There are seven request modes in the HTTP protocol, two of which are commonly used.

​ GET:

1. Request parameters are in the request line, after the url.

2. Request url length is limited.

3. Not very safe

​ POST:

1. Request parameters are in the body of the request.

2. There is no limit to the length of the url requested.

3. Relative security.

2. Request Header

Request Header Name: Request Header Value.

Common request headers:

			1. User-Agent: The browser tells the server that I have access to the version information of the browser you are using.

You can get the header information on the server side to solve browser compatibility problems.

​ 2. Refer: http://localhost/login.html

Tell the server where I (the current request) came from?

Effect:

1. Anti-theft chains:

[External chain picture transfer failed, source station may have anti-theft chain mechanism, it is recommended to save pictures and upload them directly (img-uLEfD9pz-163698573) (D:zhangpanJavaPDFself-study notesanti-theft chain.png)]

2. Statistical work:

3. Request blank lines

An empty line is the request header used to separate the POST request from the body of the request.

4. Request Body (Body)

Encapsulates the request parameters of the POST request message.

String format:

POST /login.html   HTTP/1.1
Host: localhost
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64: x64; rv:60.0) Gecko/20100101 Firefox/60.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9;*/*;q=0.8
Accept-Language: zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5;en-US;q=0.3,en;q=0.2
Accept-Encoding: gizp, deflate
Referer: http://localhost/login.html
Connection: keep-alive
Upgrade-Insecure-Requests: 1

username=zhangsan

3.3 Response message data format

4.Request

1. Principles of request and response objects

1. The request and response objects are created by the server. Let's use them.

2.The request object is to get the request message, and the response object is to set the response message.

[External chain picture transfer failed, source station may have anti-theft chain mechanism, it is recommended to save pictures and upload them directly (img-GrLzip08-163698355) (D:zhangpanJavaPDFself-study notesrequest&response.png)]

2. request object

1. request object inheritance architecture

ServletRequest - Interface

| Inheritance

HttpServletRequest - Interface

| Implementation

**org.apache.catalina.connector.RequestFacade class(tomcat)** 
2.request function

Get request message data

1. Get request row data
  • GET /day1/demo1?name=zhangsan HTTP/1.1

  • Method:

    • Get Request Method: GET

      ​ String getMethod()

    • (Key) Get virtual directories: /day1

      ​ String getContextPath()

    • Get Servlet Path: /demo1

      ​ String getServletPath()

    • Get get mode request parameter: name=zhangsan

      ​ String getQueryString()

    • (Key) Get Request URI:/day1/demo1

      ​ String getRequestURI(): /day1/demo1

      ​ StringBuffer getRequestURL(): http://localhost/day1/demo1

 ​			URL: Uniform Resource Locator: http://The People's Republic of China in localhost/day1/demo1

 ​			URI: Uniform Resource Identifier:/day1/demo1  Republic

    * Get protocol and version: HTTP/1.1

      ​	String getProtocol()

    * Get Client's IP Address:

      ​	String getRemoteAddr()

2. Get request header data
Method:

(Key*) String getHeader(String name): Get the value of the request header by its name

Enumeration getHeaderNames(): Get all request header names

Case:

@WebServlet("/requestDemo2")
public class RequestDemo2 extends HttpServlet{
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {}
    /**
     * Demonstrate Getting Request Header Data
     */
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1. Get all request header names
        Enumeration<String> headerNames = req.getHeaderNames();
        //2. Traversal
        while (headerNames.hasMoreElements()) {
            String name = headerNames.nextElement();
            //Get the value of the request header by name
            String value = req.getHeader(name);
            System.out.println(name+"--------"+value);
        }
    }
}

Result:
host--------localhost:8080
connection--------keep-alive
sec-ch-ua--------"Chromium";v="94", "Google Chrome";v="94", ";Not A Brand";v="99"
sec-ch-ua-mobile--------?0
sec-ch-ua-platform--------"Windows"
upgrade-insecure-requests--------1
user-agent--------Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36
accept--------text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
sec-fetch-site--------none
sec-fetch-mode--------navigate
sec-fetch-user--------?1
sec-fetch-dest--------document
accept-encoding--------gzip, deflate, br
accept-language--------zh-CN,zh;q=0.9
cookie--------Hm_lvt_b393d153aeb26b46e9431fabaf0f6190=1623855597; Idea-39e33e3a=e7cbcc99-d462-4b33-9be2-70bd469c77b3; Idea-de5955db=e7cbcc99-d462-4b33-9be2-70bd469c77b3; JSESSIONID=02D52A3C1562AD8DA84ED0CFCBAB6DD6
3. Get Requestor Data

Request body: Only POST request mode can have a request body, which encapsulates the request parameters of a POST request.

Steps:

1. Get Stream Object
BufferedReader getReader(); //Gets the character input stream and can only operate on character data.
ServletInputStream getInputStream(); //Getting a byte input stream operates on all types of data.
	* Explain after uploading knowledge points
  1. Retrieve data from the stream object
@WebServlet("/requestDemo5")
public class RequestDemo5 extends HttpServlet {
    //Get Request Message Body - Request Parameters
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1. Get the character stream
        BufferedReader br = request.getReader();
        //2. Read data
        String line = null;
        while ((line = br.readLine())!= null ){
            System.out.println(line);
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {}
}


 	<form action="/requestDemo5" method="post">
        <input type="text" placeholder="enter one user name" name="username"><br>
        <input type="text" placeholder="Please input a password" name="password"><br>
        <input type="submit" name="register"><br>
    </form>

Other Functions
  1. Common way to get request parameters

    1. String getParameter(String name): Get the parameter value username=zz&password=123 based on the parameter name
    2. String[] getParameterValues(String name): Array hobby=xx&hobby=game that gets the parameter value from the parameter name
    3. Enumeration getParameterNames(): Get the parameter names for all requests
    4. Map<String, String[]> getParameterMap(): Get a map collection of all parameters

    Chinese scrambling problem:

    get Method: tomcat8 The get Style scrambling problem solved.
    post Way: Will scramble!
    	Solution: Set before getting parameters request Coding for request.setCharacterEncoding("utf-8");
    
  2. Request forwarding: A resource jump within a server.

    1. Steps:

    1. Get the request forwarder object from the request object: RequestDispatcher getRequestDispatcher(String path)

    2. Use the RequestDispatcher object to forward: forward(ServletRequest request, ServletResponse response)

    System.out.println("demo8.....Visited");
    //Forward to demo9 resource
    request.getRequestDispatcher("/requestDemo9").forward(request,response);
    

    2. Features:

    1. Browser address bar path does not change

    2. Can only be forwarded to current server internal resources

    3. Forwarding is a request

  3. Shared data:

    Domain object: A scoped object that can share data within a scope.

    Request domain: Represents the scope of a single request and is generally used to share data among multiple resources for request forwarding.

    Method:

    1.setAttribute(String name,Object obj): Store data

    2.Object getAttribute(String name): Get value by key

    3.void removeAttribute(String name): Remove key-value pairs by key

  4. Get ServletContext:

    ServletContext getServletContext()

2. Features: **

1. Browser address bar path does not change

2. Can only be forwarded to current server internal resources

3. Forwarding is a request

  1. Shared data:

    Domain object: A scoped object that can share data within a scope.

    Request domain: Represents the scope of a single request and is generally used to share data among multiple resources for request forwarding.

    Method:

    1.setAttribute(String name,Object obj): Store data

    2.Object getAttribute(String name): Get value by key

    3.void removeAttribute(String name): Remove key-value pairs by key

  2. Get ServletContext:

    ServletContext getServletContext()

Posted by selliott on Thu, 11 Nov 2021 08:13:56 -0800