[JavaWeb] Detailed Http request of

HTTP Profile

concept

Hypertext transfer protocol defines client and server communications, transmit and receive data format.

Protocol Features

  • TCP / IP based high-level agreement
  • The default port number is 80
  • Based on a request / response model: Response time corresponding to the first request
  • Stateless, each independently of each other between the request, the data can not interact.

historic version

1.0: Each new connection request will be correspondingly

1.1: If both address the same connection can be reused

A data request message format

 1. Request line

         Request method request url request protocol / version

            GET                /login.html            HTTP/1.1

7 HTTP protocol has requested embodiment, there are two commonly used

  • GET:
  1. Request parameters in the request line, after url
  2. url requests limited length
  3. Not safe (visible)
  • POST:
  1. Request parameters in the request body
  2. url is not limited in the length of the request
  3. Relatively safe (in vivo request)

2. request header

Request header name: request header value

Common request header are:

  • User-Agent: browser tells the server, the browser own version information This ensures that the browser compatibility issues
  • Referer: HTTP: //localhost/login.html tell the server that I (the current request) came from. It can be used for anti-theft chain and statistics.

3. Request blank line

Blank line, for dividing the request header and request POST request body.

4. The request body

请求行    POST     /login.html     HTTP/1.1
请求头    Host: localhost
         User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:73.0) Gecko/20100101 Firefox/73.0
         Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;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
         Connection: keep-alive
         Referer: http://search.bilibili.com
         Cookie: JSESSIONID=07DFB352A5D840658715BA1B0F6EE029
         Upgrade-Insecure-Requests: 1
空行
请求体   username=lisi

Request Detailed

Principle 1. request and response objects of

       1. request and response objects are created by the server. We use them

       2. request is subject to the acquisition request message, response message in response to the object is set to

2.request object inherits architecture:

3. request function:

1. Data acquisition request message

例如: GET /day3/demo1?name=zhangsan HTTP/1.1

method:

1. Get the request method: GET

String getMethod()

2. (*) Gets the virtual directory: / day3

String getContextPath()

  3. Get Servlet Path: / demo1

String getServletPath()

4. get acquisition mode request parameters: name = zhangsan

String getQueryString()

5. (*) acquisition request URI: / day14 / demo1

String getRequestURI(): /day14/demo1

StringBuffer getRequestURL() :http://localhost/day14/demo1

6. Get the protocol and version: HTTP / 1.1

String getProtocol()

7. Obtain an IP address of the client:

String getRemoteAddr()

Example 1:

@WebServlet("/requestDemo1")  //资源路径
public class RequestDemo1 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1. 获取请求方式 :GET
        String method = request.getMethod();
        System.out.println(method);
        //2. (*)获取虚拟目录:/day3
        String contextpath = request.getContextPath();
        System.out.println(contextpath);
        //3. 获取Servlet路径: /demo1
        String servletpath = request.getServletPath();
        System.out.println(servletpath);
        //4. 获取get方式请求参数:name=zhangsan
        String querystring = request.getQueryString();
        System.out.println(querystring);
        //5. (*)获取请求URI:/day14/demo1
        String requseturi = request.getRequestURI();
        System.out.println(requseturi);
        StringBuffer requestURL = request.getRequestURL();
        System.out.println(requestURL);
        //6. 获取协议及版本:HTTP/1.1
        String protocol = request.getProtocol();
        System.out.println(protocol);
        //7. 获取客户机的IP地址:
        String remoteAddr = request.getRemoteAddr();
        System.out.println(remoteAddr);
    }
}

2. The data acquisition request header

1. (Common) String getHeader (String name): Gets the value of the request header request header by name

2.Enumeration <String> getHeaderNames (): Get all request header name

 

@WebServlet("/requestDemo2")
public class RequestDemo2 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //演示获取请求头数据
        //1.获取请求头名称
        Enumeration<String> headerNames = request.getHeaderNames();
        //2.遍历
        while (headerNames.hasMoreElements()){
            //请求头名称
            String element = headerNames.nextElement();
            //根据名称获取请求头的值
            String value = request.getHeader(element);
            System.out.println(element+" :  "+value);
        }
    }
}

3. The volume data acquisition request

Request body: POST request method will only request body, encapsulating the POST request request parameters in the request body.

Gets steps:

1. Obtain the stream object

BufferedReader getReader (): Get a character input stream, only operation of the character data

ServletInputStream getInputStream (): Get the input byte stream, you can operate all types of data

2. then pick up from the stream object

example:

@WebServlet("/requestDemo5")
public class RequestDemo5 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取请求消息体
        //1. 获取字符流
        BufferedReader br = request.getReader();
        //2.读取数据
        String line = null;
        while ((line = br.readLine())!= null){
            System.out.println(line);
        }
    }

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

    }
}

4. Other function (important):

1. General parameters acquisition request mode: Whether or post requests get embodiment can use the following methods to obtain the request parameters

       1. String the getParameter (String name): Get the name of the parameter according to the parameter values

       2. String [] the getParameterValues (String name): Gets an array of parameter values in accordance with the parameter name

       3. the Enumeration <String> the getParameterNames (): Get the name of the parameter for all requests

       4. the Map <String, String []> getParameterMap (): Get all map the set of parameters

example:

@WebServlet("/requestDemo6")
public class RequestDemo6 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    //post 获取请求参数
        String username = request.getParameter("username");
        System.out.println(username);
        System.out.println("----------");

        //根据参数名称获取参数值的数组
        String[] hobbies = request.getParameterValues("hobby");
        for(String hobby : hobbies){
            System.out.println(hobby);
        }
        System.out.println("----------");

        //获取所有请求的参数名称
        Enumeration<String> parameterNames = request.getParameterNames();
        while (parameterNames.hasMoreElements()){
            String name = parameterNames.nextElement();
            System.out.println(name);
            String value = request.getParameter(name);
            System.out.println(value);
        }
        System.out.println("----------");
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    //  get 获取请求参数
        this.doPost(request,response);
    }
}

Chinese garbage problem:

get in the way: tomcat 8 has been garbled way to get the problem solved

post way: It may be garbled. Solution: Before acquisition parameters, set the encoding of the request

request.setCharacterEncoding("utf-8");

2. The request is forwarded: a resource in a way to jump inside the server

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

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

@WebServlet("/requestDemo7")
public class RequestDemo7 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("demo7被调用了。。");
        
        //转发到demo8资源
        RequestDispatcher requestDispatcher = request.getRequestDispatcher("/requestDemo8").forward(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }
}
@WebServlet("/requestDemo8")
public class RequestDemo8 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("demo8被调用了。。。");
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }
}

Features (Interview): 1. the browser address bar does not change the path.

                         2. only be forwarded to the current server internal resources, not to other sites

                         3. there is only one request, a request to access multiple resources

3. Share data:

Domain objects: a scope of the object, the data can be shared in the range

request field: a request on behalf of a range, generally a plurality of resource requests forwarded shared data.

method:

         1. setAttribute (String name, Object obj); // store data

         2. Object getAttribute (String name); // get the value through the key

         3. void removeAttribute (String name); // remove key-value pairs by key

4. Get ServletContext

ServletContext getServletContext();

Published 169 original articles · won praise 101 · views 70000 +

Guess you like

Origin blog.csdn.net/zzu_seu/article/details/105018749