Java review-scattered knowledge points 1

1. Synchronous and asynchronous blocking and non-blocking

1.1.Synchronous and asynchronousSynchronous
and asynchronous actually refer to the use of CPU time slices, mainly depending on the request initiator, whether the acquisition of the message is actively initiated or passively notified.

  • If it is initiated actively, it has been waiting for the response result (synchronous blocking), or other things can be processed, but it is necessary to continuously poll to see whether the initiated request has a response result (synchronous non-blocking)
  • If it is notified by the server, that is, after the requester sends the request, it must either wait for the notification (asynchronous blocking) or do its own thing first (asynchronous non-blocking). When the processing is completed, the server will actively notify the requester , Its request has been completed, this is asynchronous, asynchronous notification is completed by state changes, message notifications, or callback functions. Most of the time, callback functions are used.

1.2 Blocking and non-blocking

Blocking and non-blocking usually refer to operations for IO. Simply put, after we call a function and wait for the function to return the result, is the current thread in a suspended state or running state, if it is suspended State means that the current thread cannot do anything, just waiting to get the result. This is synchronous blocking. If it is still running, it means that the current thread can continue to process other tasks, which is a non-blocking state.

2. The difference between process and thread

  • The process is an independent unit of the system for resource allocation and scheduling, and the process has an independent address space thread
  • It is an entity of a process and the basic unit of CPU scheduling and allocation. It is a basic unit that is smaller than a process and can run independently. A program has at least one process, and a process has at least one thread.
  • The thread execution overhead is small, but it is not conducive to the management and protection of resources, while the process is the opposite

3. Internal category

3.1. Why use internal classes?

  • The biggest advantage of using internal classes is that it can solve the problem of multiple inheritance very well. Using internal classes can also bring us the following features:
    1). Internal classes can use multiple instances, each instance has its own state Information, and is independent of information from other peripheral objects.
    2). In a single outer class, multiple inner classes can implement the same interface in different ways, or inherit the same class.
    3). The moment of creating the inner class object does not depend on the creation of the outer class object.
    4). The inner class does not have a confusing "is-a" relationship, it is an independent entity.

3.2, internal classification

3.2.1 Member Inner Class

public class Outer{
    
    
      private int age = 99;
      String name = "Coco";
      public class Inner{
    
    
          String name = "Jayden";
          public void show(){
    
    
              System.out.println(Outer.this.name);
              System.out.println(name);
              System.out.println(age);
          }
      }
      public Inner getInnerClass(){
    
    
          return new Inner();
      }
      public static void main(String[] args){
    
    
          Outer o = new Outer();
          Inner in = o.new Inner();
          in.show();
      }
  }

注意:
	01、Inner 类定义在 Outer 类的内部,相当于 Outer 类的一个成员变量的位置,Inner 类可以使用任意访问控制符,如 publicprotectedprivate02、Inner 类中定义的 show() 方法可以直接访问 Outer 类中的数据,而不受访问控制符的影响,如直接访问 Outer 类中的私有属性age
	03、外部类是不能直接使用内部类的成员和方法的,可先创建内部类的对象,然后通过内部类的对象来访问其成员变量和方法;
	04、如果外部类和内部类具有相同的成员变量或方法,内部类默认访问自己的成员变量或方法,如果要访问外部类的成员变量,可以使用 this 关键字,:Outer.this.name

3.2.2 Member Inner Class

/*
1.静态内部类不能直接访问外部类的非静态成员,但可以通过 new 外部类().成员 的方式访问,比如我们访问age,可以使用 new Outer1().age直接访问。
2.如果外部类的静态成员与内部类的成员名称相同,可通过“类名.静态成员”访问外部类的静态成员;如果外部类的静态成员与内部类的成员名称不相同,则可通过“成员名”直接调用外部类的静态成员
3.创建静态内部类的对象时,不需要外部类的对象,可以直接创建 内部类 对象名 = new 内部类();
*/
public class Outer1 {
    
    
    private int age = 99;
    static String name = "Coco";
    public static class Inner{
    
    
        String name = "Jayden";
        public void show(){
    
    
            System.out.println(Outer1.name);
            System.out.println(name);
            System.out.println(new Outer1().age);
        }
    }
    public static void main(String[] args){
    
    
        Inner i = new Inner();
        i.show();
    }
}

3.2.3 Method inner class: its scope is limited to the method, the inner class cannot be accessed outside the method
3.2.4 Anonymous inner class

/*
1、匿名内部类是直接使用 new 来生成一个对象的引用;
*/
public class OuterClass {
    
    
          public InnerClass getInnerClass(final int   num,String str2){
    
    
              return new InnerClass(){
    
    
                  int number = num + 3;
                  public int getNumber(){
    
    
                      return number;
                  }
              };        /* 注意:分号不能省 */
          }
          public static void main(String[] args) {
    
    
              OuterClass out = new OuterClass();
              InnerClass inner = out.getInnerClass(2, "chenssy");
              System.out.println(inner.getNumber());
          }
      }
      interface InnerClass {
    
    
          int getNumber();
      }

4. Spring Bean life cycle

The three stages of the life cycle

4.1 Creation phase
scope = "singleton" (default)

Spring工厂创建的同时,对象创建
ClassPathXmlApplicationContext s1 = new ClassPathXmlApplicationContext("application.xml");

注意:lazy-init="true" 这种情况下是在获取对象的时候才创建
<bean name="student" class="com.zq.student" scope="singleton" lazy-init="true"/>

scope = “prototype”

Spring工厂在获取对象的时候创建对象.

ClassPathXmlApplicationContext s1 = new ClassPathXmlApplicationContext("application.xml");
Object student = s1.getBean("student");

4.2 Initialization phase

4.3 Destruction phase

5. Array learning

1. It can be used to store multiple data. Each array element stores one data. Usually, the
array element can be accessed through the index of the array element, including assigning to the array element and taking out the value of the array element.

5.1. Java arrays require all array elements to have the same data type.

5.2 The characteristics of the array:

  • After the initialization of the array is completed, the space occupied by the array in the memory will be fixed, and any changes in the array elements (including emptying) will make the length of the array unchangeable.
  • Arrays can store basic data types or reference types. As long as all array elements have the same type.
  • The array is a reference type, that is, it can be stored by another array.

5.3. There are two ways to initialize the array:

  • Static initialization: During initialization, the programmer explicitly specifies the initial value of each array element, and the system determines the length of the array.
  • Dynamic initialization: The length of the array is specified by the programmer or the program during initialization, and the system assigns initial values ​​to the elements.

Static initialization

//定义一个int[]类型的数组,并静态初始化。
int[] arrayInt = new int[]{
    
    1,2,3,4,5};

//上面的代码等价于下面的代码
int[] arrayInt1;
arrayInt1 = new int[]{
    
    1,2,3,4,5};

//上面的代码等价于下面的代码
int[] arrayInt2 = {
    
    1,2,3,4,5};

Dynamic initialization

声明数组类型与静态初始化指定的数组元素相同
int[] arrayInt = new int[5];

5.4. Access array elements and array traversal

Array length attribute length
length is the length attribute of the array. Through this attribute, the length of the array can be obtained, and then the value of the array can be queried (printed) by this attribute and assigned to the array dynamically.

数组长度属性例子
//1.查询(打印)数组的值
public class J_ArrayDemo3 {
    
    
    public static void main(String[] args) {
    
    
        int[] arrayInt = new int[8];
        for (int i = 0; i < arrayInt.length; i++) {
    
    
            System.out.println(arrayInt[i]);
        }
    }
}

Traverse arrays-exclusive loops for arrays and collections foreach
foreach loop syntax
for (array type variable: array variable (collection variable)) { //automatically access (iterate) each element }

public class J_ArrayDemo5 {
    
    
	public static void main(String[] args) {
    
    
	    String[] books = {
    
    "疯狂Java","狂神说","小滴课堂","黑马","尚学堂"};
	    for (String a : books) {
    
    
	        System.out.println(a);
	    }
	}
}

5.4.1. Commonly used methods in arrays

sort

/*
数组的工具类java.util.Arrays
数组对象本身没有什么方法可以供我们调用,但API中提供了一个工具类Arrays供我们使用,从而可以对数据对象进行一些计本的操作
常用功能:
给数组赋值,通过fill方法
对数组排序,通过sort方法
比较数组,通过equal方法比较数组中元素的值是否相等
查找数组元素,通过binary Search方法能对排序好的数组进行二分查找法操作
*/
public class J_ArrayDemo22 {
    
    
    public static void main(String[] args) {
    
    
        /*
         * 对数组arrayType的元素进行排序
         * void sort(type[] arrayType);
         * 对数组arrayType所在范围内的元素进行排序
         * void sort(type[] arrayType,int fromIndex,int toIndex)
         */
        int[] arrayInt = {
    
    22,34,11,25,28,12};
        int[] arrayInt1 = {
    
    22,34,11,25,28,12};
        Arrays.sort(arrayInt);
        for (int a : arrayInt){
    
    
            System.out.print(a + ",");
        }
        System.out.println();
        Arrays.sort(arrayInt1,2,4);
        for (int a : arrayInt1){
    
    
            System.out.print(a + ",");
        }
    }
}

public class J_ArrayDemo23 {
    
    
    public static void main(String[] args) {
    
    
    /*
     * String toString(type[] arrayType)
     * 将数组转化为字符串。
     */
        int[] arrayInt1 = null;
        int[] arrayInt2 = new int[0];
        int[] arrayInt3 = {
    
    1};
        int[] arrayInt4 = {
    
    1,12,23,4,1,2,3,1};
        System.out.println(Arrays.toString(arrayInt1));
        System.out.println(Arrays.toString(arrayInt2));
        System.out.println(Arrays.toString(arrayInt3));
        System.out.println(Arrays.toString(arrayInt4));
    }
}

6, stack and heap

  • Stack: When a method is executed, it will open up a space of its own in the memory stack, the variables in this method will be placed in this space, and the variables in the method will be destroyed as the method ends.
  • Heap: When an object is created in the program, the object will be saved in the heap. The object will not be destroyed with the end of the method. Even after the method ends, the object can still be referenced by other reference variables. When any reference variable is referenced, it will be recycled by the system garbage collection mechanism when the system is idle.

7. The difference between filters and interceptors:

① The interceptor is based on the reflection mechanism of java, and the filter is based on the function callback.
② The interceptor does not depend on the servlet container, and the filter depends on the servlet container.
③Interceptors can only work on action requests, while filters can work on almost all requests.
④ The interceptor can access the objects in the action context and value stack, but the filter cannot.
⑤In the life cycle of the action, the interceptor can be called multiple times, while the filter can only be called once when the container is initialized.
⑥ The interceptor can obtain each bean in the IOC container, but the filter cannot. This is very important. Injecting a service into the interceptor can call business logic.

8. What are the similarities and differences between jsp and servlet, and what are the connections?

1. JSP becomes a servlet after being compiled (jsp is essentially a servlet, jvm can only recognize java classes, not jsp code, web container compiles jsp code into java classes that jvm can recognize)

2.jsp is better at displaying on the page, servlet is better at logical control

3. There are no built-in objects in setvlet. The built-in objects in jsp must be obtained through HttpServletRequest object, HttpServletResponse object and HttpServlet object

4. JSP is a simplification of servlet. Using jsp only needs to complete the content that the programmer needs to output to the client. How to embed the java script in jsp into a class is completed by the jsp container, and servlet is a complete java class , The service method of this class is used to generate a response to the client

9. What is a complete http request like?

1. Parse the URL

First, the browser will check whether the URL exists correctly, and if it is not valid, it will return a default search engine.
If it exists and is legal, then it can be parsed to get information such as protocol (http or https), domain name (baidu), resource (homepage), etc.

2.
DNS query The browser will first check whether the domain name information is in the cache.
Then check whether the domain name is in the local Hosts file.
If it is not there, the browser will send a query request to the DNS server to obtain the IP address of the target server

3. TCP transmission and transportation. At
this time, the browser obtains the IP (DNS return) and port of the target server (included in the URL, if not, use the default (HTTP default port 80)), and the browser will call the library function socket to generate a TCP Stream sockets, that is, complete TCP packets.
After the TCP packet is completed, it can be transmitted. The browser and the server complete the TCP three-way handshake, establish a connection, and then request server resources.

4. The server receives requests and responds to
HTTP with many request methods, such as: GET/POST/PUT/DELETE, etc. The URL input in our browser is the GET method.
The server receives the GET request, and the server obtains the corresponding content according to the request information. For example, what we input is: \Baidu, you will know\, then it means to visit Baidu's homepage file

5. The browser parses and renders The
browser gets the resource that it wants to access from the server. Most of the time, this resource is an HTML page, of course, it may also be a file of other types.
The browser first parses the HTML document and generates a parse tree (a tree with DOM elements as nodes).
Load external resources of the page, such as JS, CSS, and images.
Traverse the DOM tree, calculate the style of each node, and finally complete the rendering and become the page we see.

10. Two ways to implement page redirection: request forwarding and redirection

Request forwarding: The
client first sends a request to the server. The server finds a matching servlet and specifies it to execute. When the servlet is executed, it calls the getRequestDispacther() method to forward the request to the specified student_list.jsp, The entire process is completed on the server side, and is completed in the same request, so the servlet and jsp share the same request, everything put in the servlet can be taken out in the student_list, so the student_list can Get the result of getAttribute(), and return the result to the client after getAttribute() is executed. The whole process is a request and a response.

Redirection: The
client sends a request to the server. The server matches the servlet. After the servlet is processed, the sendRedirect() method is called, and this response is returned to the client immediately. The response line tells the client that you must send another request to access the student_list. jsp, immediately after the client receives this request, it immediately sends a new request to request student_list.jsp, where the two requests do not interfere with each other and are independent of each other. Anything in setAttribute() in the previous request is in the back Not available in the request. It can be seen that there are two requests and two responses in sendRedirect(). (The server sends a 302 status code and a location message header to the browser. After receiving the request, the browser will send a request again according to the redirect address)

Request forwarding: request.getRequestDispatcher("/test.jsp").forword(request,response);
Redirection: response.sendRedirect("/test.jsp");

the difference:

1. Number of requests: Redirection means that the browser sends a request to the server and sends a request to a new address again after receiving the response. Forwarding means that the server jumps to a new address in order to complete the response after receiving the request; redirect at least the request Twice, forward the request once;

2. The address bar is different: the redirect address bar will change, and the forwarding address bar will not change;

3. Whether to share data: Redirect twice to request not to share data, and forward once to request shared data (information sharing is used at the request level, and redirection is bound to go wrong);

4. Redirection restriction: Redirection can be redirected to any URL, and forwarding can only redirect the resources of this site;

5. Different behaviors occur: redirection is a client-side behavior, and forwarding is a server-side behavior;

11. Common http return status codes (200,301,302,400)

200-The request is successful
301-The resource (webpage, etc.) is permanently transferred to another URL
404-The requested resource (webpage, etc.) does not exist
500-Internal server error

Guess you like

Origin blog.csdn.net/Anna_Liqi/article/details/114433653