java interview questions and answers 08

Posted by elfeste on Tue, 08 Feb 2022 10:47:12 +0100


java core technology volume
java core technology Volume II

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

A: 301302 is the code of HTTP status, which means that a URL has been transferred.


  • 301 redirect: 301 represents permanently moved.
  • 302 redirect: 302 represents temporary moved.

80. What is the difference between forward and redirect?

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

In the direct Forward mode, the client and browser only send a request once. The Servlet, HTML, JSP or other information resources are responded to by the second information resource. In the request object request, the saved object is shared for each information resource.

**Indirect forwarding method (Redirect) * * actually two HTTP requests. When the server responds to the first request, it asks the browser to send a request to another URL, so as to achieve the purpose of forwarding.

Take a popular example:

Direct forwarding is equivalent to: "A borrows money from B, B says no, B borrows money from C, and if it can't be borrowed, it will pass the message to A";

Indirect forwarding is equivalent to: "A asks B to borrow money, B says no, let A ask C to borrow".
81. Briefly describe the difference between tcp and udp?

  • TCP is connection oriented (for example, dial up 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. In other words, the data transmitted through TCP connection is error free, not lost, not repeated, and arrives in sequence; 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 in case of packet loss can also control the sequence of packets that are out of order.
  • UDP has better real-time performance and higher work efficiency than TCP. It is suitable for communication or broadcast communication with high-speed transmission and real-time performance.
  • 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 communication.
  • TCP requires more system resources and UDP requires less system resources.

82. Why should TCP shake hands three times, but not twice? Why?

In order to realize reliable data transmission, both sides of TCP protocol communication must maintain a serial number to identify which packets have been received by the other party. The process of three handshakes is a necessary step for both parties to inform each other of the starting value of the serial number and confirm that the other party has received the starting value of the serial number.

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

83. How does tcp sticky packet come into being?

①. Sticky packet generated by sender

The client and server using TCP protocol to transmit data often maintain a long connection state (one connection sends one data, and there is no sticky packet). Both sides can transmit data all the time when the connection is not open; However, when the data packets sent are too small, the TCP protocol will enable the Nagle algorithm by default and send these smaller data packets together (buffer data sending is a process of heap pressure); This merging process is carried out in the sending buffer, that is, the data is sent out, and it is already in the state of sticky packet.

②. Sticky package generated by receiver

When the receiver uses TCP protocol to receive data, the process is as follows: the data is transmitted to the receiver from the bottom of the network model to the transmission layer. The TCP protocol processing of the transmission layer is to place it in the reception buffer, and then the application layer actively obtains it (C language uses recv, read and other functions); At this point, there will be a problem, that is, the data read function we called in the program can not get the data out of the buffer in time, and the next data will arrive and there will be a partial buffer at the end. When we read the data, it will be a sticky package. (data speed > data speed of application layer)

84. What are the seven layer models of OSI?

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

  2. Presentation layer: presentation, security and compression of data.

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

  4. Transport layer: define the protocol port number of data transmission, as well as flow control and error verification.

  5. Network layer: carry out logical address addressing to realize the path selection between different networks.

  6. Data link layer: establish logical connection, address addressing of hardware, error checking and other functions.

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

85. What are the differences between get and post requests?

  • GET is harmless when the browser goes back, and POST will submit the request again.
  • The URL address generated by GET can be bookmarked, but POST cannot.
  • GET requests will be actively cache d by the browser, but POST will not, unless manually set.
  • GET requests can only be url encoded, while POST supports multiple encoding methods.
  • The GET request parameters will be completely retained in the browser history, while the parameters in POST will not be retained.
  • The parameters transmitted by GET request in URL are limited in length, while POST does not.
  • For the data type of parameters, GET only accepts ASCII characters, while POST has no restrictions.
  • GET is less secure than POST because parameters are directly exposed to the URL and cannot be used to pass sensitive information.
  • The GET parameter is passed through the URL, and the POST is placed in the Request body.

86. How to achieve cross domain?

Method 1: picture ping or script tag cross domain

Image ping is often used to track the number of page clicks or dynamic advertising exposure.
The script tag can get data from other sources, which is also the basis of JSONP dependency.

Mode 2: JSONP cross domain

JSONP (JSON with Padding) is a "usage mode" of data format JSON, which allows web pages to request data from other domains. According to XmlHttpRequest, the object is affected by the homology policy and uses


  • Only Get requests can be used
  • It is not possible to register event listening functions such as success and error, and it is not easy to determine whether the JSONP request fails
  • JSONP loads code from other domains for execution. It is vulnerable to the attack of Cross Site Request Forgery, and its security cannot be guaranteed

Mode 3: CORS

Cross origin resource sharing (CORS) is a specification of browser technology, which provides a method for Web services to send sandbox scripts from different domains, so as to avoid the homology strategy of the browser and ensure safe cross domain data transmission. Modern browsers use CORS in API containers such as XMLHttpRequest to reduce the risk source of HTTP requests. Different from JSONP, CORS also supports other HTTP requests in addition to the GET request method. The server generally needs to add one or more of the following response headers:

Access-Control-Allow-Origin: *Access-Control-Allow-Methods: POST, GET, OPTIONSAccess-Control-Allow-Headers: X-PINGOTHER, Content-TypeAccess-Control-Max-Age: 86400

The cross domain request will not carry Cookie information by default. If it needs to be carried, please configure the following parameters:

"Access-Control-Allow-Credentials": true// Ajax setting "withCredentials": true

Mode 4: window name+iframe works by loading cross domain HTML files in iframe (general dynamic creation 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 capability of iframe tag;
  • window. The ability of the 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 property returns the window object of the element. You can use this window object to access the iframe document and its internal DOM.

<!--  The following is represented by port 10000: domainA 10001 express: domainB-->
<!-- localhost:10000 --><script>  var iframe = document.createElement('iframe'); = 'none'; // hide
  var state = 0; // Prevent pages from being refreshed indefinitely iframe Onload = function() {if (state = = = 1) {console.log (json.parse (iframe. Contentwindow. Name)); / / clear the iframe. Contentwindow. Document. Write (''); iframe. Contentwindow. Close(); document. Body. Removechild (iframe);} Else if (state = = = 0) {state = 1; / / after loading, point to the current domain to prevent errors (proxy.html is a blank page) / / 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> = JSON.stringify({a: 1, b: 2});</script></html>

Mode 5: window postMessage()

A new feature of HTML5 can be used to send messages to all other window objects. It is important to note that we must ensure that all scripts are executed before sending MessageEvent. If the function is invoked in the process of execution, it will cause the latter function to run out of time.

The following code implements cross domain storage localStorage

<!--  The following is represented by port 10000: domainA 10001 express: 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(;          if (data) {              if (callbacks[data[1]]) {                  callbacks[data[1]](data[2] === 'null' ? null : data[3]);              }              delete callbacks[data[1]];          }      }  }, false);
  var domain = '*';  // Add function lssetitem (key, value) {var obj = {setitem: key, value: value}; frames['myPostMessage']. postMessage(JSON.stringify(obj), domain);  }  //  Get 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);  }  //  Delete 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(;      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>

Note that Safari will report an error:

Blocked a frame with origin "http://localhost:10001" from accessing a frame with origin "http://localhost:10000". Protocols, domains, and ports must match.

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

Method 6: modify document Domain cross subdomain

Prerequisite: these two domain names must belong to the same basic domain name! Moreover, the protocols and ports used must be consistent, otherwise cannot be used Domain is cross domain, so it can only cross sub domains

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

There are now two domain names aaa and bbb Embed bbb pages under aaa because of its document The name is inconsistent, and the JS of bbb cannot be operated under aaa. Under aaa and bbb, you can use js to add document name = ‘’; Consistent settings to achieve mutual access.

Method 7: WebSocket

WebSocket protocol is a new protocol of HTML5. It realizes full duplex communication between browser and server, and allows cross domain communication. It is a great implementation of server push technology. For relevant articles, please check: WebSocket, WebSocket sockjs

Note: WebSocket objects do not support DOM Level 2 event listeners. You must use DOM level 0 syntax to define each event separately.

Method 8: Agency

Homology strategy 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: blog csdn. net/ligang2585116/article/details/73072868

87. What is the implementation principle of JSONP?

jsonp, namely json+padding, dynamically creates a script tag. The src attribute of the script tag can be used to obtain the js script under any domain. Through this feature (or vulnerability), the server does not return the goods in json format, but returns a section of js code calling a function, which is called in src, so as to realize cross domain.

Topics: Java Back-end