The latest collection of JAVA interview questions (7)

The internet

79. What do the http response codes 301 and 302 represent? What's the difference?

Answer: 301 and 302 are the encoding of HTTP status, which means that a certain URL has been transferred.

the difference:

  • 301 redirect: 301 stands for Permanently Moved.

  • 302 redirect: 302 stands for Temporarily Moved.

80. The difference between forward and redirect?

Forward and Redirect represent two request forwarding methods: direct forwarding and indirect forwarding.

Direct forwarding mode (Forward), the client and browser only send a request once, Servlet, HTML, JSP or other information resources, the second information resource responds to the request, in the request object request, the saved object is for each information Resources are shared.

The indirect forwarding method (Redirect) is actually two HTTP requests. When the server responds to the first request, the browser sends a request to another URL to achieve the purpose of forwarding.

Give a popular example:

Direct forwarding is equivalent to: "A asks B to borrow money, B says no, B goes to C to borrow, and if it fails to borrow, it will pass the message to A";

Indirect forwarding is equivalent to: "A asks B to borrow money, B says no, let A go to C to borrow."

81. Briefly describe the difference between tcp and udp?

  • TCP is connection-oriented (such as dialing to establish a connection before making a call); UDP is connectionless, that is, there is no need to establish a connection before sending data.

  • TCP provides reliable services. That is to say, the data transmitted through the TCP connection has no errors, no loss, no duplication, and arrives in order; UDP does its best to deliver, that is, reliable delivery is not guaranteed.

  • Tcp realizes reliable transmission through checksum, retransmission control, serial number identification, sliding window, and confirmation response. For example, the retransmission control when the packet is lost, the sequence control of the out-of-order sub-packets can also be performed.

  • UDP has better real-time performance, higher work efficiency than TCP, and is suitable for high-speed transmission and real-time communication or broadcast communication.

  • Each TCP connection can only be point-to-point; UDP supports one-to-one, one-to-many, many-to-one and many-to-many interactive communications.

  • TCP requires more system resources, while UDP requires less system resources.

82. Why does tcp need to shake hands three times? why?

In order to achieve reliable data transmission, both parties in the TCP protocol must maintain a sequence number to identify which of the sent data packets have been received by the other party. The process of the three-way handshake is a necessary step for the communicating parties to inform each other of the initial value of the serial number and confirm that the other party has received the initial value of the serial number.

If there are only two handshakes, at most only the initial sequence number of the initiator of the connection can be confirmed, and the sequence number selected by the other party cannot be confirmed.

83. Tell me about how tcp sticky packets are generated?

①. The sender generates a sticky package

The client and server that use the TCP protocol to transmit data often maintain a long connection state (there is no sticky packet when the data is sent once a connection), and the two parties can always transmit data when the connection is not disconnected; but when the data packet is sent Too small, then the TCP protocol will enable the Nagle algorithm by default to combine and send these smaller data packets (buffer data transmission is a process of heap compression); this combination process is carried out in the sending buffer, and That is to say, when the data is sent out, it is already in a sticky state.
Insert picture description here
②. The receiver generates a sticky package

When the receiver uses the TCP protocol to receive data, the process is like this: the data is passed to the transport layer from below the network model to the receiver. The TCP protocol processing of the transport layer places it in the receiving buffer, and then the application layer actively obtains it. (C language uses recv, read and other functions); at this time there will be a problem, that is, the read data function we call in the program can not take out the data in the buffer in time, and the next data comes and has a part The end of the put buffer is a sticky packet when we read the data. (The speed of putting data> the speed of taking data at the application layer)

Insert picture description here
84. What are the seven-layer models of OSI?

  • Application layer: an interface between network services and end users.

  • Presentation layer: data presentation, security, and compression.

  • Session layer: establish, manage, and terminate sessions.

  • Transport layer: Define the protocol port number for data transmission, as well as flow control and error checking.

  • Network layer: Perform logical address addressing to realize path selection between different networks.

  • Data link layer: functions such as establishing logical connections, addressing hardware addresses, and error checking.

  • Physical layer: establish, maintain, and disconnect physical connections.

85. What is the difference between get and post requests?

  • GET is harmless when the browser rolls back, while POST will submit the request again.

  • The URL address generated by GET can be Bookmarked, but not by POST.

  • GET requests will be actively cached by the browser, while POST will not, unless manually set.

  • GET requests can only be url-encoded, while POST supports multiple encoding methods.

  • GET request parameters will be completely retained in the browser history, while POST parameters will not be retained.

  • The parameters transmitted in the URL of a GET request are limited in length, but not for POST.

  • For the data type of the parameter, GET only accepts ASCII characters, while POST has no restrictions.

  • GET is less secure than POST, because parameters are directly exposed on the URL, so it cannot be used to transmit sensitive information.

  • GET parameters are passed through the URL, and POST is placed in the Request body.

86. How to achieve cross-domain?

Method 1: Image ping or script tag cross-domain

Picture pings are often used to track the number of user clicks on pages or dynamic ad exposures.
Script tags can get data from other sources, which is also the basis for JSONP's reliance.

Method 2: JSONP cross-domain

JSONP (JSON with Padding) is a "use mode" of the data format JSON, which allows web pages to request data from other domains. According to the XmlHttpRequest object is affected by the same-origin policy, and using this open policy of the <script> element, web pages can obtain JSON data dynamically generated from other sources, and this usage mode is the so-called JSONP. The data captured with JSONP is not JSON, but arbitrary JavaScript, run with a JavaScript interpreter instead of parsed with a JSON parser. All, through Chrome, all Get requests sent by JSONP are of js type, not XHR.

Insert picture description here
Disadvantages:

  • Can only use Get request

  • It is not possible to register event monitoring functions such as success and error, and it is not easy to determine whether the JSONP request failed

  • JSONP is executed by loading code from other domains. It is vulnerable to cross-site request forgery attacks, and its security cannot be guaranteed.

Method 3: CORS

Cross-Origin Resource Sharing (CORS) is a browser technology specification that provides a method for Web services to send sandbox scripts from different domains to avoid the browser’s same-origin policy and ensure safe cross-origin Domain data transmission. Modern browsers use CORS in API containers such as XMLHttpRequest to reduce the risk of HTTP requests. Unlike JSONP, CORS also supports other HTTP requirements in addition to the GET request method. The server generally needs to add one or more of the following response headers:

Insert picture description here
Cross-domain requests will not carry cookie information by default. If you need to carry it, please configure the following parameters:
Insert picture description here
Method 4: window.name+iframe

window.name works by loading a cross-domain HTML file in an iframe (generally dynamically created i). Then, the HTML file assigns the string content passed to the requester to window.name. The requester can then retrieve the window.name value as a response.

  • Cross-domain capabilities of iframe tags;

  • The ability of the window.name attribute value to still exist after the document is refreshed (and the maximum allowed is about 2M).

Each iframe has a window that wraps it, and this window is a child window of the top window. The contentWindow attribute returns the Window object of the <iframe> element. You can use this Window object to access the iframe document and its internal DOM.

<!-- 
 下述用端口 
 10000表示:domainA
 10001表示:domainB
-->

<!-- localhost:10000 -->
<script>
  var iframe = document.createElement('iframe');
  iframe.style.display = 'none'; // 隐藏

  var state = 0; // 防止页面无限刷新
  iframe.onload = function() {
    
    
      if(state === 1) {
    
    
          console.log(JSON.parse(iframe.contentWindow.name));
          // 清除创建的iframe
          iframe.contentWindow.document.write('');
          iframe.contentWindow.close();
          document.body.removeChild(iframe);
      } else if(state === 0) {
    
    
          state = 1;
          // 加载完成,指向当前域,防止错误(proxy.html为空白页面)
          // Blocked a frame with origin "http://localhost:10000" from accessing a cross-origin frame.
          iframe.contentWindow.location = 'http://localhost:10000/proxy.html';
      }
  };

  iframe.src = 'http://localhost:10001';
  document.body.appendChild(iframe);
</script>

<!-- localhost:10001 -->
<!DOCTYPE html>
...
<script>
  window.name = JSON.stringify({
    
    a: 1, b: 2});
</script>
</html>

Method five: window.postMessage()

HTML5 new features can be used to send messages to all other window objects. It should be noted that we must ensure that all scripts are executed before sending MessageEvent. If it is called during the execution of the function, it will cause the subsequent function to time out and fail to execute.

The following code implements cross-domain storage localStorage

<!-- 
 下述用端口 
 10000表示:domainA
 10001表示:domainB
-->

<!-- localhost:10000 -->
<iframe src="http://localhost:10001/msg.html" name="myPostMessage" style="display:none;">
</iframe>

<script>
  function main() {
    
    
      LSsetItem('test', 'Test: ' + new Date());
      LSgetItem('test', function(value) {
    
    
          console.log('value: ' + value);
      });
      LSremoveItem('test');
  }

  var callbacks = {
    
    };
  window.addEventListener('message', function(event) {
    
    
      if (event.source === frames['myPostMessage']) {
    
    
          console.log(event)
          var data = /^#localStorage#(\d+)(null)?#([\S\s]*)/.exec(event.data);
          if (data) {
    
    
              if (callbacks[data[1]]) {
    
    
                  callbacks[data[1]](data[2] === 'null' ? null : data[3]);
              }
              delete callbacks[data[1]];
          }
      }
  }, false);

  var domain = '*';
  // 增加
  function LSsetItem(key, value) {
    
    
      var obj = {
    
    
          setItem: key,
          value: value
      };
      frames['myPostMessage'].postMessage(JSON.stringify(obj), domain);
  }
  // 获取
  function LSgetItem(key, callback) {
    
    
      var identifier = new Date().getTime();
      var obj = {
    
    
          identifier: identifier,
          getItem: key
      };
      callbacks[identifier] = callback;
      frames['myPostMessage'].postMessage(JSON.stringify(obj), domain);
  }
  // 删除
  function LSremoveItem(key) {
    
    
      var obj = {
    
    
          removeItem: key
      };
      frames['myPostMessage'].postMessage(JSON.stringify(obj), domain);
  }
</script>

<!-- localhost:10001 -->
<script>
  window.addEventListener('message', function(event) {
    
    
    console.log('Receiver debugging', event);
    if (event.origin == 'http://localhost:10000') {
    
    
      var data = JSON.parse(event.data);
      if ('setItem' in data) {
    
    
        localStorage.setItem(data.setItem, data.value);
      } else if ('getItem' in data) {
    
    
        var gotItem = localStorage.getItem(data.getItem);
        event.source.postMessage(
          '#localStorage#' + data.identifier +
          (gotItem === null ? 'null#' : '#' + gotItem),
          event.origin
        );
      } else if ('removeItem' in data) {
    
    
        localStorage.removeItem(data.removeItem);
      }
    }
  }, false);
</script>

Pay attention to Safari, it will report an error:

Insert picture description here
To avoid this error, you can check the development menu==>disable cross-domain restriction in the Safari browser. Or it can only be implemented by server-side dumping, because the Safari browser only supports CORS cross-domain requests by default.

Method 6: Modify document.domain across subdomains

Prerequisite: The two domain names must belong to the same basic domain name! And the protocols and ports used must be the same, otherwise document.domain cannot be used for cross-domain, so only cross-subdomains

Within the scope of the root domain, it is allowed to set the value of the domain attribute to its parent domain. For example, in the "aaa.xxx.com" domain, you can set the domain to "xxx.com" but not "xxx.org" or "com".

Insert picture description here
Method seven: WebSocket

WebSocket protocol is a new protocol for HTML5. It implements full-duplex communication between the browser and the server while allowing cross-domain communication. It is a great implementation of server push technology. For related articles, please check: WebSocket, WebSocket-SockJS

Note: The WebSocket object does not support DOM Level 2 event listeners, and each event must be defined separately using DOM Level 0 syntax.

Method eight: agency

The same-origin policy is a restriction on the browser side, which can be solved by the server side

DomainA client (browser) ==> DomainA server ==> DomainB server ==> DomainA client (browser)

Source of eight cross-domain methods: blog.csdn.net/ligang2585116/article/details/73072868

87. Tell me about the implementation principle of JSONP?

jsonp is json+padding, dynamically creating script tags, and using the src attribute of script tags to get js scripts in any domain, through this feature (or vulnerability), the server does not return json format, but returns a paragraph to call a certain The js code of the function is called in src, which realizes cross-domain.

Guess you like

Origin blog.csdn.net/weixin_42120561/article/details/114704350