Servlet&HTTP&Reques&Response Quick Start

servlet related configuration

  1. URLPattern: servlet access path

    A servlet can define multiple access paths

    @WebServlet({"/d4","/dd4","/ddd4"})
    

    Path rules:

    • /xxx: path matching
    • /xxx/xx: multi-layer path, directory structure
    • *.do: extension match

HTTP

  1. concept

    Hyper Text Transfer Protocol hypertext transfer protocol. What is a protocol? It defines the format for transmitting information between two devices.

  2. features

    • The default port number is 80
    • Based on the request/response model: one request corresponds to one response
    • Stateless, each request is independent of each other, and data cannot be exchanged

3. version

  • 1.0: A new connection will be established for each request response
  • 1.1: multiplexing connection
  1. Request message data format

    • request line

      GET /login.html	HTTP/1.1
      

      There are 7 request methods in the HTTP protocol, and 2 are commonly used

      GET

      1. The request parameters are in the request line, after the url? connect
      2. The requested url length is limited
      3. not perfect

      POST

      1. The request parameters are in the request body
      2. There is no limit to the length of the requested url
      3. relatively safe
    • request header

      1. User-agent

        The browser tells the server the version information of my browser

      2. Refer

        where do i come from

        It can prevent chain hotlinking and carry out statistical work

    • request blank line

      Blank line, used to separate post request header and request body.

    • request body (text)

      The post request method requests the place where the data is stored

    • Example:

      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: gzip, deflate
      Referer: http://localhost/login.html
      Connection: keep-alive
      Upgrade-Insecure-Requests: 1
      
      username=zhangsan	
      
  2. Response message data format (omitted)

Request

Request function

Primary user gets request message data

  1. Get request line data GET /day14/demo1?name=zhangsan HTTP/1.1

    • getMethod get request method GET
    • getContextPath gets the virtual path /day14
    • getServletPath gets the servlet path/demo1
    • getQueryString gets the Get request parameter name=zhangsan
    • getRequestURI Get request URI/day14/demo1
    • getProtocol get protocol and version HTTP/1.1
    • getRemoteAddr gets the client IP address
  2. Get request header data

    • getHeader(String name)
    • getHeaderNames(): Get all request header names
  3. Get request body data

    getReader obtains after obtaining the stream object

Other functions

  1. General method for getting request parameters

    1. String getParameter(String name): Obtain the parameter value according to the parameter name username=zs&password=123
    2. String[] getParameterValues(String name): Obtain the array of parameter values ​​according to the parameter name hobby=xx&hobby=game
    3. Enumeration getParameterNames(): Get the parameter names of all requests
    4. Map<String,String[]> getParameterMap(): Get the map collection of all parameters

Chinese garbled problem

request.setCharacterEncoding("utf-8");

request forwarding

request.getRequestDispatcher.forward(ServletRequest request,ServletResponse response) 
  • features

    1. Retweet is just a request
    2. It can only be forwarded to the internal resources of the current server
    3. The browser address bar does not change
  • share data

    1. Domain objects: share data within a certain scope

    2. request domain: the scope of data sharing in a request

      setAttribute() 存储数据
      getAttribute()获取数据
      removeAttribute移除数据
      

ServletContext

(Learn in detail under Response)

ServletContext getServletContext()

case-login

Link: Case - Login

Response

HTTP protocol response

  1. Request message: the data sent by the client to the server

    • request line
    • request header
    • request blank line
    • request body
  2. Response message: the message sent by the server to the client

    • response line

      1. composition

        Protocol/Version Response Status Code Status Code Description

      2. response status code

        1xx: The server accepts the message from the client, but has not completed the acceptance. After waiting for a while, it sends 1xx multi-status codes

        2xx: Success, 200

        3xx: Redirection. 302 redirect. 304 access cache

        4xx: client error

        ​ 404 The request path does not have a corresponding resource

        ​ 405 The request method does not have a corresponding doxxx method

        5xx: server error 500 server internal exception

    • response header

      1. Content-Type: The server tells the client the data format and encoding format of the response body

      2. Content-disposition: In what format does the server-side Gaoshu client open the corresponding data

        –inlinedefault

        –attachment;filename=xxx Open as an attachment

                response.setHeader("content-disposition","attachment;filname=111");
        
    • response empty line

    • Response body: the transmitted data

    • Response Content Example

      HTTP/1.1 200 OK
      Content-Type: text/html;charset=UTF-8
      Content-Length: 101
      Date: Wed, 06 Jun 2018 07:08:42 GMT
      
      <html>
      <head>
      <title>$Title$</title>
      </head>
      <body>
      hello , response
      </body>
      </html>
      

Response object

  1. set response message

    • set response line

      Format: HTTP/1.1 200 OK

      Set status code: setStatus

    • set response header

      setHeader(String name, String value)

    • set response body

      1. Get the output stream getWriter or getOutputStream

      2. Use the output stream

  2. redirect

    //response.setStatus(302);//1. 设置状态码为302
    //      response.setHeader("location","/day/servletDemo3"); //2.设置响应头location
    
    //上面的写法的简介
    response.sendRedirect("/day/servletDemo3");
    

The difference between redirection and forwarding

  1. redirection feature
    • address bar changes
    • Redirects to other sites
    • The redirection is two requests, and the request domain class cannot be used to share data
  2. forwarding features
    • Forwarding address path unchanged
    • is a request
    • Forwarding can only access resources on the current server

access path

  1. relative path

    For example./index.html

    ./Current directory

    .../Back one directory

  2. absolute path

    For example http://localhost/day14/demo

    or /day14/demo

  3. path usage

    • client use

      A virtual directory needs to be added, and the virtual directory is dynamically obtained

      request.getContextPath()
      
    • server use

      No need to add a virtual directory, generally used when forwarding

The server outputs character data to the browser

  1. step

    Get character output stream -> output data

  2. Garbled problem

    set response header

    response.setContentType("text/html;charset=utf-8");
    
  3. Case - Captcha

    Link: verification code case

ServletContext object

concept

Represents the entire web application and can communicate with the program's container (server)

Obtain

  1. request get

    request.getServletContext();
    
  2. HttpServlet get

    this.getServletContext();
    

Function

  1. Get the MIME type

    MIME type: A file data type defined in the Internet communication process

    Format: major type/small type

    text/html image/jpeg

    method of obtaining

    getMimeType(String file)
    
  2. Domain Objects: Shared Data

    • setAttribute
    • getAttribute
    • removeAttribute

    The scope of the ServletContext object: the data requested by all users, personal understanding is that all servlets share data

  3. Get the real (server) path of the file

    String b = context.getRealPath("/b.txt");//web目录下资源访问
    System.out.println(b);
    String c = context.getRealPath("/WEB-INF/c.txt");//WEB-INF目录下的资源访问
    System.out.println(c);
    String a = context.getRealPath("/WEB-INF/classes/a.txt");//src目录下的资源访问
    System.out.println(a);
    

Case-File Download

  1. File Download Requirements

    • page display hyperlink
    • After clicking the hyperlink, the download prompt box will pop up
    • Complete image file download
  2. Link File Download-Case

Guess you like

Origin blog.csdn.net/qq_44850917/article/details/123015107