Summary of java basic theory + java WEB + java open source framework knowledge points

1. Java Basics

1.What is the function of final keyword?
  • Classes modified by final cannot be inherited
  • Methods modified by final cannot be overridden
  • Variables modified by final cannot be changed. If a reference is modified, it means that the reference is immutable and the content pointed to by the reference is mutable.
  • For methods modified by final, the JVM will try to inline them to improve operating efficiency. Variables modified by final will be stored in the constant pool during the compilation phase.
2.What is the difference between abstract class and interface?
  • A class that declares the existence of a method without implementing it is called an abstract class. It is used to create a class that embodies some basic behavior and declares a method for the class, but the class cannot be implemented in the class. Case. Instances of abstract classes cannot be created. However, you can create a variable whose type is an abstract class and have it point to an instance of a concrete subclass. There cannot be abstract constructors or abstract static methods. Subclasses of the Abstract class provide implementations for all abstract methods in their parent class, otherwise they would also be abstract classes. Instead, implement the method in a subclass. Other classes that are aware of its behavior can implement these methods in their class.
  • An interface is a variant of an abstract class. In an interface, all methods are abstract. Multiple inheritance can be obtained by implementing such an interface. All methods in the interface are abstract, and none of them have a program body. Interfaces can only define static final member variables. Implementation of an interface is similar to subclassing, except that the implementing class cannot inherit behavior from the interface definition. When a class implements a particular interface, it defines (i.e. gives the program body to) all of the methods of this interface. It can then call the interface's methods on any object of the class that implements the interface. Since there are abstract classes, it allows using the interface name as the type of the reference variable. Normal dynamic linking will take effect. References can be converted to or from interface types, and the instanceof operator can be used to determine whether an object's class implements the interface.
3. Java collection classes: What are the characteristics and usage of list, set, queue, map, and stack?
  • Map
    • Map is a key-value pair, and the key Key is the only one that cannot be repeated. One key corresponds to a value, and the value can be repeated.

    • TreeMap can guarantee the order, HashMap does not guarantee the order, that is, it is unordered.

    • Key and Value can be extracted separately from Map. The KeySet() method can extract all keys into a Set, and the Values() method can extract all the values ​​in the map into a set.

  • Set
    • A set that does not contain repeated elements. The set contains at most one null element. Only Iterator can be used to implement single-item traversal. There is no synchronization method in Set.
  • List
    • An ordered repeatable collection can add and delete elements at any position. Iterator can be used to implement one-way traversal, and ListIterator can be used to implement two-way traversal.
  • Queue
    • Queue follows the first-in-first-out principle. Try to avoid the add() and remove() methods when using it. Instead, use offer() to add elements and poll() to remove elements. Its advantage is that it can be judged by the return value. Successfully, LinkedList implements the Queue interface, and Queue usually does not allow the insertion of null elements.
  • Stack
  • Stack follows the last-in-first-out principle. Stack inherits from Vector. It extends the Vector class through five operations to allow the vector to be treated as a stack. It provides the usual push and pop operations, as well as the peek() method and test for taking the stack vertex. empty method to check whether the stack is empty, etc.
  • usage
    • If operations such as stacks and queues are involved, it is recommended to use List.
    • For quick insertion and deletion of elements, it is recommended to use LinkedList. If you need fast random access to elements, it is recommended to use ArrayList.
4. Tell me about the storage performance and characteristics of ArrayList, Vector, and LinkedList?
  • ArrayList and Vector both use arrays to store data. The number of array elements is larger than the actual stored data so that elements can be added and inserted. They both allow elements to be indexed directly by serial number, but inserting elements involves memory operations such as moving array elements, so indexing data Fast but slow to insert data. Because Vector uses the synchronized method (thread safety), its performance is usually worse than ArrayList, while LinkedList uses a doubly linked list to implement storage. Indexing data by serial number requires forward or backward traversal, but only when inserting data. You only need to record the items before and after this item, so the insertion speed is faster.
5. Memory leaks and memory overflows?
  • Memory leak (memoryleak) means that the application cannot release the memory space it has applied for after applying for memory. The harm of a memory leak can be ignored, but if allowed to develop, it will eventually lead to a memory overflow (outofmemory). For example, after reading a file, the stream must be closed promptly and the database connection must be released.

  • Memory overflow (outofmemory) means that when an application applies for memory, there is not enough memory space for it to use. For example, in our project, we import large batches of data in batches.

7. What is the difference between int and Integer?
  • Integer is the packaging type of int. During unboxing and boxing, the two are automatically converted. Int is a basic type and can directly store values; and integer is an object; a reference points to this object. Since Integer is an object, in the JVM Objects require a certain data structure to describe, and compared to int, they occupy larger memory.
8. What are the differences between String, StringBuilder and StringBuffer?
String String constant immutable When using string concatenation, there are two different spaces.
StringBuffer string variable variable Thread safety String concatenation appends directly after the string
StringBuilder string variable variable Not thread safe String concatenation appends directly after the string
  • StringBuilder execution efficiency is higher than StringBuffer and higher than String.
  • String 是一个常量,是不可变的,所以对于每一次+=赋值都会创建一个新的对象,StringBuffer 和 StringBuilder 都是可变的,当进行字符串拼接时采用 append 方法,在原来的基础上进行追加,所以性能比 String 要高,又因为 StringBuffer是线程安全的而 StringBuilder 是线程非安全的,所以 StringBuilder 的效率高于 StringBuffer.
  • 对于大数据量的字符串的拼接,采用 StringBuffer,StringBuilder.
9. Hashtable 和 Hashmap 的区别?
  • HashTable 线程安全,HashMap 非线程安全2、Hashtable 不允许 null 值(key 和 value 都不可以),HashMap 允许 null 值(key 和 value 都可以)。
    两者的遍历方式大同小异,Hashtable 仅仅比 HashMap 多一个 elements 方法。
10. 说几个常见的编译时异常?
  • SQLException 提供有关数据库访问错误或其他错误的信息的异常。
    IOexception 表示发生了某种 I / O 异常的信号。此类是由失败或中断的 I / O 操作产生的
    一般异常类 FileNotFoundException 当试图打开指定路径名表示的文件失败时,抛出此异常。
    ClassNotFoundException 找不到具有指定名称的类的定义。
    EOFException 当输入过程中意外到达文件或流的末尾时,抛出此异常。
11. 方法重载的规则?
  • 方法名一致,参数列表中参数的顺序,类型,个数不同。重载与方法的返回值无关,存在于父类和子类,同类中。可以抛出不同的异常,可以有不同修饰符。
12. 方法重写的规则?
  • The parameter list, method name, and return value type must be completely consistent, and the constructor cannot be overridden;
  • Methods declared final cannot be overridden;
  • Methods declared as static do not have overriding (only overriding and polymorphic unions make sense);
  • Access permissions cannot be lower than those of the parent class;
  • The overridden method cannot throw wider exceptions
  • Subclasses cannot override private methods of parent class
13. What is the difference between throw and throws?
  • throw:
    The throw statement is used in the method body to indicate that an exception is thrown, which is handled by the statements in the method body. Throw is an action that specifically throws an exception, so it throws an exception instance. When executing throw, some kind of exception must be thrown.
  • throws:
    The throws statement is used after the method declaration to indicate that if an exception is thrown, the caller of the method will handle the exception. throws mainly declares that this method will throw a certain type of exception, so that its users know what needs to be caught.
  • The type of exception. throws indicates the possibility of an exception, but does not necessarily mean that this exception will occur.
14. What is the difference between abstract class and interface?
  • All methods in an interface are implicitly abstract. An abstract class can contain both abstract and non-abstract methods.
  • A class can implement many interfaces, but it can only inherit one abstract class
  • If a class wants to implement an interface, it must implement all methods declared by the interface. However, a class does not need to implement all the methods declared by an abstract class. Of course, in this case, the class must also be declared abstract.
  • An abstract class can implement an interface without providing implementations of the interface methods.
  • Variables declared in Java interfaces are final by default. Abstract classes can contain non-final variables.
  • Member functions in Java interfaces are public by default. Member functions of abstract classes can be private, protected or public.
  • Interfaces are absolutely abstract and cannot be instantiated (Java 8 already supports implementing default methods in interfaces). An abstract class cannot be instantiated, but it can be called if it contains a main method.
15. Java’s basic types and byte sizes? bit.
byte short int long float double char boolean
8 bits 16 bit 32 bit 64 bit 32 bit 64 bit 16 bit Use an eighth of a byte
16. What four access modifications correspond to access levels?

public, protected, no access modifier, private

17. What is the difference between String and StringBuffer?
  • The main difference between String and StringBuffer is performance: String is an immutable object. Every operation on the String type is equivalent to generating a new String object and then pointing to the new String object. So try not to perform a large number of splicing operations on String. Otherwise, many temporary objects will be generated, causing the GC to start working, affecting system performance.
    StringBuffer operates on the object itself, rather than generating new objects, so in the case of a large number of splicing, we recommend using StringBuffer (thread-safe).
18. What is the underlying implementation of HashSet?
  • The implementation of HashSet depends on HashMap, and the values ​​of HashSet are stored in HashMap. A HashMap object is initialized in the construction method of HashSet, and HashSet does not allow duplicate values.
    Therefore, the value of HashSet is stored in HashMap as the key of HashMap, and returns false when the stored value already exists.
19. What is the meaning of abstract class?
  • The meaning of abstract classes can be summarized in three sentences: 1. Provide a common type for other subclasses 2. Encapsulate content repeatedly defined in subclasses
  • Define abstract methods. Although subclasses have different implementations, they are consistent in definition.
20. Why do you have to override the hashCode method when overriding equals?
  • The function of hashCode() is to obtain the hash code, also known as hash code; it actually returns an int integer. The purpose of this hash code is to determine the index position of the object in the hash table. If two objects are equal, the hashcode must also be the same. If the two objects are equal, calling the equals method on the two objects will return true. If the two objects have the same hashcode value, they are not necessarily equal. Therefore, the equals method has been overridden, the hashCode method must also be overridden. The default behavior of hashCode() is to produce unique values ​​for objects on the heap. If hashCode() is not overridden, two objects of this class will not be equal anyway (even if the two objects point to the same data).
21. What is the difference between HashSet and TreeSet?
  • HashSet is implemented by a hash table, therefore, its elements are unordered.
    The time complexity of add(), remove(), and contains() methods is O(1). TreeSet is implemented by a tree structure, and the elements in it are ordered. Therefore, the time complexity of the add(), remove(), and contains() methods is O(logn).
23. How are arrays allocated in memory?
  • When an object is created using the new keyword, memory space is allocated on the heap and then a reference to the object is returned. This is the same for arrays, because arrays are also objects, simple arrays of value types, and each array member is a reference (pointer) to a space on the stack.
24. How to create an immutable object in Java?
  • The state of the object cannot be modified after the constructor, any modification should be achieved by creating a new object.

  • All object properties should be set to final

  • Object creation must be correct, for example: the application of the object cannot be leaked in the constructor

  • The object should be set to final. Make sure that the inherited Class does not modify the immutability feature.

25. Is the ++ operator thread-safe in Java?
  • Not a thread-safe operation. It involves multiple instructions, such as reading a variable value, incrementing it, and then storing it back into memory. This process may involve multiple threads intersecting.
27. What is the difference between == and equals() in Java?
  • == can compare both basic data types and reference data types.
  • ==When comparing basic data types, the values ​​are compared. When comparing reference data types, the addresses of objects are compared.
  • equals can only compare reference data types. It compares whether the content in the object is the same. It also compares the address of the object without rewriting.
28. What is the difference between final, finalize and finally?
  • final is used to declare properties, methods and classes, which respectively means that properties are immutable, methods cannot be overridden, and classes cannot be inherited. finally is part of the exception handling statement structure, indicating that it is always executed. finalize is a method of the Object class. This method of the recycled object will be called when the garbage collector is executed.
    This method can be overridden to provide other resource recycling during garbage collection, such as closing files, etc.
29. Where does polymorphism appear in Java?
  • Polymorphism must have dynamic binding, otherwise it is not polymorphism, and method overloading is not polymorphism (because method overloading is determined at compile time, and there is no later dynamic binding at runtime)
  • When these three conditions are met: 1. Child-parent class relationship 2. There is overriding 3. There must be a parent class reference pointing to the child class object
30. What are the characteristics of static types?
  • Static attributes: loaded as the class is loaded, the attribute no longer belongs to a certain object, but to the entire class
  • Static method: Called directly with the class name, non-static member variables cannot be accessed in a static method
  • Static can only access static
31.How many ways does Java create objects?
  • new creates a new object
  • through reflection mechanism
  • Using clone mechanism
  • Through the serialization mechanism ObjectInputStream
32.What are the public methods in Object?
  • Object is the parent class of all classes. Any class inherits the Object clone protected method by default to implement shallow copy of the object. This method can only be called if the Cloneable interface is implemented, otherwise a CloneNotSupportedException exception will be thrown.
  • equals is the same as == in Object, and subclasses generally need to override this method.
  • hashCode This method is used for hash search. If you override the equals method, you should generally override the hashCode method. This method is used in some Collections with hash function.
  • getClass method, obtain the runtime type
  • wait makes the current thread wait for the lock of the object. The current thread must be the owner of the object, that is, it has the lock of the object.
  • The wait() method waits until the lock is acquired or interrupted.
  • wait(long timeout) sets a timeout interval and returns if the lock is not obtained within the specified time.
33. What is the difference between & and &&?
  • & is a bitwise operator, representing bitwise AND operation, && is a logical operator, representing logical AND (and).
34. Can there be multiple classes in a .java source file (except inner classes)?
  • A .java source file can include multiple classes (not internal classes), but there can only be one public class in a single file, and the public class must be the same as the file name
35. How to correctly exit a multi-level nested loop?
  • break;

  • Use alias

36.What is the function of inner classes?
  • Inner classes can be well hidden. Generally, non-inner classes are not allowed to have private and protected
    permissions, but inner classes can.

  • The inner class has access to all elements of the outer class

  • But implementing multiple inheritance

  • You can avoid modifying the interface and implement the call of two methods with the same name in the same class

38.Is String a basic data type?
  • Basic data types include byte, int, char, long, float, double, boolean and short. The java.lang.String class is of final type, so this class cannot be inherited or modified. In order to improve efficiency and save space, we should use the StringBuffer class
39. How to use static?
  • Static can modify internal classes, methods, variables, and code blocks; the class modified by Static is a static internal class; the method modified by Static is a static method, which means that the method belongs to the current class and not to an object, and static methods cannot is overridden and can be called directly using the class name. You cannot use this or super keywords in static methods.
  • Static modified variables are static variables or class variables. Static variables are shared by all instances and do not depend on objects. Static variables have only one copy in memory. When the JVM loads a class, memory is only allocated once for static variables.
    The code block modified by Static is called a static code block and is usually used for program optimization. The code in the static code block will only be executed once when the entire class is loaded. There can be multiple static code blocks. If there are multiple static code blocks, they will be executed in order.
40. What are pass-by-value and pass-by-reference?
  • Basic data types pass values, reference data types pass addresses
  • The transfer between basic data types is transfer by value, and the transfer between reference data types is transfer by reference.
41. What is the difference between overloading and rewriting?
  • Method overriding and overloading are different manifestations of Java polymorphism. Overriding
    is a manifestation of polymorphism between parent classes and subclasses, and overloading is a manifestation of polymorphism in a class. If a method defined in a subclass has the same name and parameters as its parent class, we say the method is overriding. When an object of a subclass uses this method, it will call the definition in the subclass. For it, the definition in the parent class seems to be "shielded". If multiple methods with the same name are defined in a class, and they have different number of parameters or different parameter types, it is called method overloading.
42. What are the differences between member variables and local variables?
  • From a grammatical perspective, member variables belong to the class, while local variables are variables defined in the method or parameters of the method; member variables can be modified by modifiers such as public, private, and static, but local variables cannot be accessed. Modified by control modifiers and static; member variables and local variables can be modified by final;
  • Judging from the way variables are stored in memory, member variables are part of the object, and the object exists in the heap memory, and local variables exist in the stack memory.
  • From the perspective of the survival time of variables in memory, member variables are part of the object and exist with the creation of the object, while local variables disappear automatically as the method is called.
  • If a member variable is not assigned an initial value, it will automatically be assigned a value based on the type's default value (except in one case, a member variable modified by final but not modified by static must be explicitly assigned a value); local variables will not be automatically assigned a value.
43. What is the difference between static methods and instance methods?
  • The difference between static methods and instance methods is mainly reflected in two aspects:
    when calling static methods externally, you can use the "class name. method name" method or the "object name. method name" method. Instance methods only have the latter method. In other words, calling static methods does not require creating an object.
  • When a static method accesses members of this class, it is only allowed to access static members (i.e. static member variables and static methods), but is not allowed to access instance member variables and instance methods; instance methods do not have this restriction.
44.What is polymorphism?
  • Allows objects of different classes to respond to the same message. That is, the same message can behave in many different ways depending on the person to whom it is sent. (Sending a message is a function call)
45. What are the advantages of polymorphism?
  • Substitutability. Polymorphism enables replacement of existing code. For example, polymorphism works for the Circle class, but it also works for any other circular geometry, such as a torus.
    Extensibility. Polymorphism makes code extensible. Adding new subclasses does not affect the polymorphism, inheritance, and operation and operation of other features of existing classes. In fact, it is easier to add new subclasses to obtain polymorphic functions.
46. ​​Three necessary conditions for the existence of polymorphism?
  • There must be inheritance.
  • There needs to be a method of rewriting.
  • The parent class reference points to the child class object (for methods defined in the parent class, if the method is overridden in the child class, the reference of the parent class type will call the method in the child class, which is dynamic connection)
47. What are the differences between TreeMap, HashMap and LindedHashMap?
  • LinkedHashMap can ensure that the HashMap collection is ordered. The order of depositing is the same as the order of withdrawing. TreeMap implements
    the SortMap interface and can sort the records it saves according to keys. The default is to sort in ascending order of key values. You can also specify a sorting comparator. When an Iterator is used to traverse the TreeMap, the records obtained are sorted. HashMap does not guarantee the order, that is, it is unordered and has very fast access speed. HashMap only allows the key of one record to be Null; it allows the value of multiple records to be Null; HashMap does not support thread synchronization.
48.What are the object-oriented features of Java (OOP)?
  • Abstraction: Abstraction is the process of summarizing the common characteristics of a class of objects to construct a class, including data abstraction and behavioral abstraction. Abstraction only focuses on the properties and behaviors of objects, but does not focus on the details of these behaviors.

  • Inheritance: Inheritance is the process of creating a new class by obtaining inheritance information from an existing class. The class that provides inheritance information is called a parent class (superclass, base class); the class that gets inheritance information is called a subclass (derived class). Inheritance brings a certain continuity to the changing software system. At the same time, inheritance is also an important means of encapsulating variable factors in the program.

  • Encapsulation: It is generally believed that encapsulation is the binding of data and methods of operating data, and access to data can only be through defined interfaces. The essence of object-oriented is to depict the real world as a series of completely autonomous and closed objects. The method we write in a class is an encapsulation of implementation details; the way we write a class is an encapsulation of data and data operations. It can be said that encapsulation is to hide everything that can be hidden and only provide the simplest programming interface to the outside world.

  • Polymorphism: Polymorphism allows objects of different subtypes to respond differently to the same message. Simply put, the same method is called with the same object reference but different things are done. Polymorphism is divided into compile-time polymorphism and run-time polymorphism. If the methods of an object are regarded as the services provided by the object to the outside world, then runtime polymorphism can be explained as: when system A accesses the services provided by system B, system B has multiple ways of providing services, but everything is different for system A. The system is transparent. Method overloading (overload) implements compile-time polymorphism (also known as pre-binding), while method overriding (override) implements run-time polymorphism (also known as post-binding). Runtime polymorphism is the essence of object-oriented. To achieve polymorphism, two things need to be done: 1. Method rewriting (subclass inherits the parent class and overrides existing or abstract methods in the parent class); 2. . Object modeling (use a parent type reference to refer to a subtype object, so that the same reference calling the same method will show different behaviors depending on the subtype object)

49. List some common runtime exceptions?
  • ArithmeticException (arithmetic exception)
  • ClassCastException (class conversion exception)
  • IllegalArgumentException (illegal parameter exception)
  • IndexOutOfBoundsException (index out of bounds exception)
  • NullPointerException (null pointer exception)
  • SecurityException (security exception)
50.What is reflection?
  • Reflection is to dynamically load objects and analyze the objects. In the running state, for any class, you can know all the properties and methods of this class; for any object, you can call any of its methods. This function of dynamically obtaining information and dynamically calling object methods becomes Java reflection. mechanism.
51. What is the role of reflection?
  • Determine the class to which any object belongs at runtime
  • Construct objects of any class at runtime
  • Determine the member variables and methods of any class at runtime
  • Call methods on any object at runtime
52.Three ways to obtain class?
  • The object is obtained by calling the getClass() method; it is obtained by the class name.class; it is
    obtained by the forName() static method of the Class object
53.What is the difference between break and continue?
  • break and continue are statements used to control loops. break is used to completely end a loop and jump out of the loop body to execute the statements following the loop. continue is used to skip this loop and continue to the next loop.
54. What are the similarities and differences between runtime exceptions and general exceptions?
  • Exceptions represent abnormal conditions that may occur during program running. Runtime exceptions represent abnormalities that may be encountered in the normal operation of a virtual machine and are a common operating error. The Java compiler requires that methods must be declared to throw non-runtime exceptions that may occur, but it is not required to be declared to throw uncaught runtime exceptions.
55. What are the characteristics of each of the three interfaces List, Map, and Set when accessing elements?
  • List accesses elements at specific indexes and can have duplicate elements. Set cannot store repeated elements (use the object's equals() method to distinguish whether elements are repeated). Map saves the mapping of key-value pairs. The mapping relationship can be one-to-one or many-to-one.
56.What is the difference between Collection and Collections?
  • Collection is the superior interface of the collection class. The interfaces inherited from it mainly include Set and List.
    Collections is a helper class for the collection class. It provides a series of static methods to implement operations such as searching, sorting, and thread safety for various collections. .
57.What is the difference between Error and Exception?
  • error represents a serious problem in a situation where recovery is not impossible but difficult. For example, memory overflow. It is impossible to expect a program to handle such a situation. exception represents a design or implementation problem. That is, it represents a situation that would never occur if the program were running normally.
58.EJB life cycle and how to manage transactions?
  • SessionBean: The life cycle of a Stateless Session Bean is determined by the container. When the client sends a request to create a Bean instance, the EJB container does not necessarily create a new Bean instance for the client to call, but just randomly finds an existing Bean instance. Some instances are provided to clients. When the client calls a Stateful Session Bean for the first time, the container must immediately create a new Bean instance in the server and associate it with the client. In the future, when the client calls the method of the Stateful Session Bean, the container will dispatch the call to the client. The bean instance associated with this client. EntityBean: Entity Beans can survive for a relatively long time and their state is persistent. Entity beans live as long as the data in the database exists. Rather than speaking in terms of applications or service processes. Even if the EJB
    container crashes, the Entity beans survive. Entity Beans lifecycle can be
    managed by the container or by the beans themselves. EJB manages practices through the following technologies: Object Practice Services (OTS) from the Object Management Group (OMG), Sun Microsystems' Transaction Service (JTS), Java Transaction API (JTA), and the XA interface from the Development Group (X/Open)
    .
59.What is the difference between Comparable and Comparator interfaces?
  • The Comparable interface contains only one compareTo() method. This method can sort two objects. Specifically, it returns negative numbers, 0, and positive numbers to indicate that the input object is less than, equal to, or greater than an existing object. The Comparator interface contains two methods: compare() and equals().
60.Can switch operate on byte, long, and string?
  • switch can operate on char, byte, short, and int. switch can operate on the wrapper classes of char, byte, short, and int.
    switch cannot operate on long, double, float, and boolean, including their wrapper classes. Switch can be a string type. , String (can only be used on String after Java 1.7) switch can be an enumeration type (after JDK 1.5)
61. Which classes in jdk cannot be inherited?
  • Classes that cannot be inherited are those modified with the final keyword. Generally, more basic types or types that prevent extended classes from inadvertently destroying the implementation of the original method should be final. In jdk, System, String, StringBuffer, etc. are all basic types.
62. The elements in Set cannot be repeated, so what method is used to distinguish whether they are repeated or not?
  • The elements in the Set cannot be repeated. Whether the elements are repeated or not is determined using the equals() method. The equals() and == methods determine whether a reference value points to the same object. equals() is overridden in the class to return true when the contents and types of two separate objects match.
63.What is the difference between JDK and JRE?
  • The Java Runtime Environment (JRE) is the Java virtual machine that will execute Java programs. It also contains the browser plug-ins required to execute the applet. The Java Development Kit (JDK) is a complete Java software development kit, including JRE, compiler and other tools (such as JavaDoc, Java debugger), which allows developers to develop, compile, and execute Java applications.
64. Is it possible to access non-static variables in a static environment?
  • Static variables belong to classes in Java, and their values ​​are the same in all instances. When a class is loaded by the Java virtual machine, static variables are initialized. If your code attempts to access non-static variables without using an instance, the compiler will report an error because these variables have not yet been created and are not associated with any instance.
65.Does Java support multiple inheritance?
  • No, Java does not support multiple inheritance. Each class can only inherit from one class, but can implement multiple interfaces.
66.What is an iterator?
  • The Iterator interface provides many methods for iterating over collection elements. Every collection class contains iteration methods that return iterator instances. Iterators can remove elements from the underlying collection during the iteration process.
    The semantics and meaning of cloning or serialization are related to the specific implementation. Therefore, it is up to the specific implementation of the collection class to determine how it is cloned or serialized.
67.What is the difference between Iterator and ListIterator?
  • Their differences are listed below:
    Iterator can be used to traverse Set and List collections, but ListIterator can only be used to traverse List. Iterator can only traverse a collection forward, while ListIterator can traverse both forward and backward.
    ListIterator implements the Iterator interface and includes other functions, such as adding elements, replacing elements, getting the index of the previous and next elements, etc.
69.Do List, Set, and Map inherit from Collection interface?
  • Only the List and Set interfaces inherit from the Collection interface, and Map is an interface concept parallel to Collection.
70. Where does the string constant pool exist in the memory space?
  • The string constant pool of jdk 6.0 is in the method area. The specific embodiment of the method area can be regarded as the permanent area in the heap. The method area is no longer declared in the jdk 7.0 java virtual machine specification, and the string constant pool is stored in the heap space. The jdk 8.0 java virtual machine specification also declares the metaspace, and the string constant pool is stored in the metaspace.
72.What two ways are used to sort collections?
  • You can use an ordered collection, such as a TreeSet or a TreeMap, or you can use an ordered collection, such as a list, and then sort it with Collections.sort().
73. Name three new features in JDK 1.7?
  • Although JDK 1.7 is not as big a version as JDK 5 and 8, it still has many new features, such as the try-with-resource statement, so that when you use streams or resources, you do not need to manually close them, Java will automatically closure. The Fork-Join pool implements a Java version of Map-reduce to some extent. String variables and text are allowed in Switch. The diamond operator (<>) is used for type inference. It is no longer necessary to declare generics on the right side of the variable declaration, so you can write more readable and writeable, more concise code. Another feature worth mentioning is improved exception handling, such as allowing multiple exceptions to be caught in the same catch block.
74. Name 5 new features introduced in JDK 1.8?
  • Java 8 is a groundbreaking version in the history of Java. Here are the 5 main features of JDK 8: Lambda expressions, which allow anonymous functions to be passed like objects through the Stream API, making full use of modern multi-core CPUs and writing very concise code. Date and Time API, finally, there is a stable, simple date and time library that you can use extension methods, and now you can have static, default methods in the interface. Duplicate annotations, now you can use the same annotation multiple times on the same type.
75.ArrayList source code analysis? (recite)
  • ArrayList is a variable-length collection class, implemented based on fixed-length arrays. The capacity initialized using the default construction method is 10 (after 1.7, it is delayed initialization, that is, the elementData capacity is initialized when the add method is called for the first time to add an element. is 10).
  • ArrayList allows null values ​​and duplicate elements. When the number of elements added to ArrayList is greater than the capacity of its underlying array, it will regenerate a larger array through the expansion mechanism. The expanded length of ArrayList is 1.5 times the original length
  • Since the underlying implementation of ArrayList is based on arrays, it can ensure that random search operations are completed at O(1) complexity.
  • ArrayList is a non-thread-safe class. In a concurrent environment, multiple threads operating ArrayList at the same time will cause unpredictable exceptions or errors.
  • It is convenient to add sequentially
  • Deletion and insertion require copying the array, which has poor performance (LinkindList can be used)
  • Integer.MAX_VALUE - 8: Mainly considering different JVMs, some JVMs will add some data headers. When the expanded capacity is greater than MAX_ARRAY_SIZE, we will compare the minimum required capacity with MAX_ARRAY_SIZE. If it is larger than it, only Can take Integer.MAX_VALUE, otherwise it is Integer.MAX_VALUE -8.
    This is new Object[] only available since jdk1.7
76.HashMap source code analysis? (recite)
  • Before jdk1.8 list + linked list
  • After jdk1.8 list + linked list (when the length of the linked list reaches 8, it is converted into a red-black tree)
  • The expansion factor of HashMap
    defaults to 0.75, which means 1/4 of the space will be wasted. When the expansion factor is reached, the list will be doubled. 0.75 is a balance value between time and space;
77. ConcurrentHashMap source code analysis? (recite)
  • The lock segmentation technology used by ConcurrentHashMap first divides the data into segments for storage, and then assigns a lock to each segment of data. When a thread occupies the lock to access one segment of data, the data of other segments can also be used by other threads. access. Some methods need to span segments, such as size() and containsValue(). They may need to lock the entire table instead of just a certain segment. This requires locking all segments in order. After the operation is completed, the locks of all segments are released in order. . "In order" is very important here, otherwise deadlock is very likely to occur. Inside ConcurrentHashMap, the segment array is final, and its member variables are actually final. However, just declaring the array as final does not Ensuring that array members are also final requires implementation guarantees. This ensures that no deadlock occurs because the order in which locks are acquired is fixed.
  • ConcurrentHashMap is composed of Segment array structure and HashEntry array structure. Segment is a reentrant lock ReentrantLock, which plays the role of a lock in ConcurrentHashMap, and HashEntry is used to store key-value pair data. A ConcurrentHashMap contains a Segment array. The structure of Segment
    is similar to that of HashMap. It is an array and linked list structure. A Segment contains a HashEntry array. Each HashEntry is an element of a linked list structure. Each Segment guardian contains a HashEntry array. When modifying the data of the HashEntry array, its corresponding Segment lock must be obtained first.

二、Java Web

1. What is the difference between session and cookie?
  • The session is stored on the server side, and the cookie is stored on the client side, so in terms of security, the session is more secure than the cookie. Then we obtain the information in the session through the sessionid stored in the session cookie. And since the session is stored in the server's memory, the continuous increase of things in the session will cause a burden on the server, so very important information will be stored in the session, and some minor things will be stored in the client's cookie, and then To be precise, cookies are divided into two categories: session cookies and persistent cookies. To be precise, session cookies are stored in the memory of the client browser, so its life cycle is consistent with that of the browser. The browser The session cookie disappears when the session cookie is turned off. However, the persistent cookie is stored on the client's hard drive, and the life cycle of the persistent cookie is the storage time we set when setting the cookie. Then we consider a problem when the browser is closed. Will the session be lost? From the above analysis, the session information is obtained through the sessionid of the session cookie. When the browser is closed, the session cookie disappears, so our sessionid disappears, but the session information still exists on the server side. This At that time, we just couldn't find the so-called session, but it didn't exist. So, under what circumstances is the session lost? It is when the server is shut down, or the session expires (the default time is 30 minutes), or invalidate() is called, or we want a certain piece of data in the session to disappear and call the session. .removeAttribute() method, and when is the session created? To be precise, it is created by calling getsession(). This is the difference between session and cookie.
2. What is the connection between session and cookie?
  • session 是通过 cookie 来工作的 session 和 cookie 之间是通过 C O O K I E [ ′ P H P S E S S I D ′ ] 来联系的,通过 _COOKIE['PHPSESSID']来联系的,通过 COOKIE[PHPSESSID]来联系的,通过_COOKIE[‘PHPSESSID’]可以知道 session 的 id,从而获取到其他的信息。
    在购物网站中通常将用户加入购物车的商品联通 session_id 记录到数据库中,当用户再次访问是,通过 sessionid 就可以查找到用户上次加入购物车的商品。因为 sessionid 是唯一的,记录到数据库中就可以根据这个查找了。
3. servlet 的生命周期?
  • Servlet 生命周期可以分成四个阶段:加载和实例化、初始化、服务、销毁。
    当客户第一次请求时,首先判断是否存在 Servlet 对象,若不存在,则由 Web 容器创建对象,而后调用 init()方法对其初始化,此初始化方法在整个 Servlet 生命周期中只调用一次。
    完成 Servlet 对象的创建和实例化之后,Web 容器会调用 Servlet 对象的 service()方法来
    处理请求。

  • Web 容器关闭或者 Servlet 对象要从容器中被删除时,会自动调用 destory()方法。

4. What is webservice?
  • On the surface, WebService is an application that exposes an API that can be called through the Web to the outside world. That is to say, the application can be called programmatically through the Web. We call the application that calls this WebService the client, and the application that provides this WebService is called the server. From a deeper perspective, WebService is a new platform for building interoperable distributed applications. It is a platform and a set of standards. It defines how applications can achieve interoperability on the Web. You can write Web services in any language you like and on any platform you like, as long as we can query and access these services through the Web service standard.
5. What are the differences, common points, and application scopes of jsp and servlet?
  • JSP is an extension of Servlet technology, which is essentially a simple way of Servlet. JSP is compiled into a "servlet-like" form.
    The main difference between Servlet and JSP is that the application logic of Servlet is in the Java file and is completely separated from the HTML in the presentation layer. In the case of JSP, Java and HTML can be combined into a file with a .jsp extension. JSP focuses on views, and Servlets are mainly used for control logic. In the struts framework, JSP is located in the view layer of the MVC design pattern,
    and Servlet is located in the control layer.
6. What is the difference between forward and redirect?
  • From the address bar display,
    forward means that the server requests resources. The server directly accesses the URL of the target address, reads the response content of that URL, and then sends the content to the browser. The browser has no idea where the content sent by the server comes from. Where did it come from, so its address bar is still the original address. Redirect means that the server sends a status code based on logic to tell the browser to request that address again. So the address bar displays the new URL.
  • From the perspective of data sharing,
    forward: the forwarded page and the forwarded page can share the data in the request.
    Redirect: cannot share data. 3. From the perspective of application,
    forward: generally used when users log in, forward to the corresponding page based on the role. Module.
    Redirect: Generally used to return to the main page and jump to other websites when users log out and log in. 4. In terms of efficiency, forward: high.
    Redirect: low.
7. What is the difference between request.getAttribute() and request.getParameter()?
  • request.getParameter() is obtained through the implementation of the container to obtain the data passed in through methods such as post, get, etc.
  • request.setAttribute() and getAttribute() only flow within the web container and are only in the request processing stage.
  • getAttribute returns an object, getParameter returns a string
  • getAttribute() has always been used together with setAttribute(). Only after setting it with setAttribute(), can the value be obtained through getAttribute(). They pass Object type data. And it must be used in the same request object to be valid. , and getParameter() is to receive the parameters submitted by the get or post of the form.
9. What technologies are used to implement various parts of MVC? How to achieve?
  • MVC is the abbreviation of Model-View-Controller. "Model" represents the business logic of the application (implemented through JavaBean, EJB components), "View" is the presentation surface of the application (generated by JSP pages), and "Controller" provides process control of the application (usually a Servlet) , through this design model, the application logic, processing process and display logic are divided into different components for implementation. These components can be interacted with and reused
11. The difference between the get and post methods of Http request.
  • Get is a request to the server for data, while Post is a request to submit data to the server.
  • Get is to obtain information, not to modify information. It is similar to the database query function, and the data will not be modified.
  • The parameters of the Get request will be passed after the url, and the requested data will be appended to the URL. The URL and transmission data are separated by ?, and the parameters are connected with &. The XX in %XX is the hexadecimal representation of this symbol. ASCII, if the data is English letters/numbers, send it as it is. If it is a space, convert it to +. If it is Chinese/other characters, directly encrypt the string with BASE64
    .
  • There is a size limit on the data transmitted by Get. Because GET submits data through URL, the amount of data that can be submitted by GET is directly related to the length of the URL. Different browsers have different restrictions on the length of the URL.
  • The data requested by GET will be cached by the browser, and the username and password will appear in clear text on the URL. Others can check the historical browsing records, and the data is not safe. On the server side, use Request.QueryString to obtain the data submitted by Get method.
    The Post request is sent to the web server as the actual content of the http message. The data is placed in the HTML Header for submission. Post does not limit the data submitted. Post is safer than Get. When the data is in Chinese or insensitive data, use get because when using get, the parameters will be displayed in the address. For sensitive data and data that are not Chinese characters, use post.
  • POST represents a request that may modify resources on the server. On the server side, data submitted in the Post method can only be obtained using Request.Form.
12. How does the tomcat container create a servlet class instance? What principles are used?
  • When the container starts, it will read the web.xml files in all web applications in the webapps directory, then parse the xml files, and read the servlet registration information. Then, the servlet classes registered in each application are loaded and instantiated through reflection. (Sometimes it is also instantiated on the first request)
  • Add 1 when registering the servlet. If it is a positive number, it will be instantiated at the beginning. If it is not written or it is a negative number, it will be instantiated on the first request.
13.What are the basic steps for JDBC to access the database?

​ The first step: Class.forName() loads the database connection driver;

Step 2: DriverManager.getConnection() obtains the data connection object;

​ Step 3: Obtain the sql session object based on SQL. There are two methods: Statement and PreparedStatement;

Step 4: Execute SQL. If there is a parameter value before executing SQL, set the parameter value setXXX();

Step 5: Process the result set;

Step 6: Close the result set, close the session, and close the connection.

14. Why use PreparedStatement?

The PreparedStatement interface inherits from Statement. PreparedStatement instances contain compiled SQL statements, so their execution speed is faster than Statement objects.
​ As a subclass of Statement, PreparedStatement inherits all the functions of Statement. Three methods execute, executeQuery and executeUpdate have been changed so that they no longer require parameters.
In JDBC applications, PreparedStatement is used in most cases for the following reasons:
code readability and maintainability. Statement needs to be continuously spliced, but PreparedStatement does not.
PreparedStatement maximizes performance. DB has a caching mechanism, and the same precompiled statement will not need to be compiled again if it is called again.
The most important point is that security is greatly improved. Statement is easy to be injected by SQL, and
the content passed in by PreparedStatement will not have any matching relationship with the sql statement.

15. Principle of database connection pool. Why use connection pooling?

1. Database connection is a time-consuming operation, and the connection pool allows multiple operations to share a connection.
2. The basic idea of ​​the database connection pool is to establish a "buffer pool" for database connections. Put a certain number of connections in the buffer pool in advance. When you need to establish a database connection, you only need to take one out of the "buffer pool" and put it back after use. We can prevent the system from endless connections to the database by setting the maximum number of connections in the connection pool. More importantly, we can monitor the number and usage of database connections through the connection pool management mechanism, providing a basis for system development, testing and performance adjustment.
3. The purpose of using connection pools is to improve the management of database connection resources.

16.What is the difference between execute, executeQuery and executeUpdate?

​ 1. The execute(String query) method of Statement is used to execute any SQL query. If the result of the query is a ResultSet, this method returns true. If the result is not a ResultSet, such as an insert or update query, it will return false. We can get the ResultSet through its getResultSet method, or get the number of updated records through the getUpdateCount() method.
2. The executeQuery(String query) interface of Statement is used to execute select query and return ResultSet.
Even if no records are found in the query, the ResultSet returned will not be null. We usually use executeQuery to execute query statements. In this case, if an insert or update statement is passed in, it will throw a
java.util.SQLException with the error message "executeQuery method can not be used for update". ,
​ 3. Statement’s executeUpdate(String query) method is used to execute insert or update/delete (DML)
statements, or return nothing. For DDL statements, the return value is int type. If it is a DML statement, it is an update. The number of entries, if it is DDL, returns 0.
You should use the execute() method only when you are not sure what statement it is, otherwise you should use the executeQuery or executeUpdate method.

17.What is the ResultSet of JDBC?

After querying the database, a ResultSet will be returned, which is like a data table of the query result set.
The ResultSet object maintains a cursor pointing to the current data row. At the beginning, the cursor points to the first row. If the next() method of ResultSet is called, the cursor will move down one row. If there is no more data, the next() method will return false. You can use it in a for loop to iterate over a data set.
​ The default ResultSet cannot be updated, and the cursor can only move down. In other words, you can only traverse from the first line to the last line. However, you can also create a ResultSet that can be rolled back or updated.
When the Statement object that generates the ResultSet is to be closed or re-executed or the next ResultSet is obtained, the ResultSet object will also be automatically closed. Column data can be obtained by passing in the column name or a serial number starting from 1 through the getter method of ResultSet.

18.What is a Servlet?

Servlet is a Java program that uses the Java Servlet application programming interface (API) and related classes and methods. The
core interface that all Servlets must implement is javax.servlet.servlet. Every servlet must directly or indirectly implement this interface, or inherit javax.servlet.GenericServlet or javax.servlet.HTTPServlet.
Servlet is mainly used to process HTTP requests from the client and return a response.

19.What is the difference between doGet and doPost methods?

​ doGet: The GET method appends the name-value pair to the requested URL. Because URLs have a limit on the number of characters, this limits the number of parameter values ​​used in client requests. And the parameter values ​​in the request are visible, therefore, sensitive information cannot be passed in this way.
doPOST: The POST method overcomes the limitations of the GET method by placing the request parameter values ​​in the request body. Therefore, there is no limit to the number of parameters that can be sent. Finally, sensitive information passed through POST requests is not visible to external clients.

22. How to transfer objects between pages?

​ request、session、application、cookie

23.What is the difference between dynamic INCLUDE and static INCLUDE in JSP?

​ Dynamic include is used for jsp: include action implementation <jsp: include page = “include.jsp” flush = “true” /> It will always check changes in the included files, is suitable for including dynamic pages, and can take parameters.
Static include is implemented using include pseudocode and does not check changes in included files. It is suitable for including static pages <%@include file="include.html"%>.

24. What are the four major scopes of JSP?

The four scopes in JSP include page, request, session and application. Specifically: page represents objects and attributes related to a page.
request represents objects and properties related to a request issued by a Web client. A request may span multiple pages and involve multiple Web components; temporary data that needs to be displayed on the page can be placed in this scope. session represents the objects and properties related to a session established by a user with the server. Data related to a user should be placed in the user's own session.
application represents objects and properties related to the entire Web application. It is essentially a global scope that spans the entire Web application, including multiple pages, requests, and sessions.

25. What are the connections and differences between BS and CS?

1.Different hardware environments:
C/S is generally built on a dedicated network, a small-scale network environment, and special servers are used to provide connection and data exchange services between LANs. B
/S is built on a wide area network and does not have to be dedicated Network hardware environment, such as telephone Internet access, rental equipment. Information management by yourself. It has a stronger adaptability than C/S. Generally, as long as you have an operating system and a browser, it will be enough.

2.
C/S has different security requirements. It is generally oriented to a relatively fixed user group and has strong control over information security. Generally, highly confidential information systems adopt a C/S structure. Part of the public information can be released through B/S. B
/ S is built on a wide area network, has relatively weak security control capabilities, and may be oriented to unknown users.

3.With different program architectures
, C/S programs can pay more attention to processes, can perform multi-level verification of permissions, and can pay less attention to system running speed. B/S's multiple considerations of security and access speed are based on the need for more optimization. Above. The program architecture with B/S structure has higher requirements than C/S. It is a development trend. From MS's .Net series to BizTalk 2000 Exchange 2000, etc., it fully supports the system built by network components. SUN and IBM promote JavaBean component technology, etc., make B/S more mature.

4.Software reuse of different C/S programs can inevitably be considered holistically. The reusability of components is not as good as the reusability of components under B/S requirements. The
multiple structures of B/S pairs require relatively independent functions of components. Can be relatively Better reuse. Just buy a dining table that can be reused instead of making a stone table on the wall.

5.System maintenance is different

Due to the integrity of the C/S program, it is necessary to examine it as a whole, deal with the problems that arise, and upgrade the system. Upgrading is difficult. It may be necessary to make a new system composed of
B/S components, and replace the aspect components individually to achieve a seamless upgrade of the system. System maintenance overhead is reduced to a minimum. Users can upgrade by downloading and installing from the Internet.

6.To solve the problem, different
C/S programs can handle fixed user planes, and in the same area, high security requirements are required, related to the operating system. They should all be the same system
B/S built on the WAN, facing different user groups, dispersed geographically. , this is something that C/S cannot do. It has the least relationship with the operating system platform.

7. The user interface is different.
C/S is mostly built on the Window platform, with limited expression methods and generally has higher requirements for programmers. B/S is built on the browser, and has richer and more vivid ways of expression to communicate with users. And most of them are difficult to use. Reduce and
reduce development costs.

8.Information flow is different.
C/S programs are generally typical centralized mechanical processing, with relatively low interactivity
. B/S information flow direction can change, such as BB BC BG and other changes in information and flow direction, more like a trading center.

26. Explain the life cycle of Servlet and the difference between Servlet and CGI?

After the Web container loads the Servlet and instantiates it, the Servlet life cycle begins. The container runs its init method to initialize the Servlet. When the request arrives, it runs its service method. The service method automatically dispatches the doXXX method (doGet, doPost) corresponding to the request. ), etc., when the server decides to destroy the instance, its destroy method is called. The difference from cgi is that servlet is in the server process, and it runs its service method through multi-threading. One instance can serve multiple requests, and its instance is generally not destroyed, while CGI creates a new process for each request. The service is destroyed after it is completed, so its efficiency is lower than servlet.

27. How to prevent repeated submission of forms?

The overall solution for repeated submissions:
1. Use redirect to solve the problem of repeated submissions
2. After clicking once, the button becomes invalid
3. The principle of loading (Loading) is to generate the Loading style when you click submit. Hide this style after completion)
4. Customize duplicate submission filter

28. What is the function of request?

1. Get the request parameters getParameter()
2. Get the virtual path of the current Web application getContextPath
3. Forward getRequestDispatcher(path).forward(request, response);
4. It is still a domain object

29.get request Chinese garbled characters?

1. The root cause of garbled characters:
the browser's encoding method UTF-8 is different from the server's decoding method ISO-859-1. 2. Solution: 1) The
first method uses two classes of encoding and decoding, URLEncoder and URLDecoder. First encode with iso-8895-1, and then decode with utf-8.
2) The second method uses the String class method to encode and decode.
3) The third method changes the server.xml configuration file.
The GET request passes the request parameters in the URL address bar, which will be automatically decoded by the Tomcat server. The default character set of the Tomcat server is also ISO-8859-1, so we need to modify the character set of the Tomcat server to UTF-8.

30. Post request with Chinese garbled characters?

1. The reason why the post request method is garbled is because the post is sent to the server in the form of a binary stream. After the server receives the data. The default is to encode in iso-8859-1.
2. To solve the garbled post request, you only need to call the request.setCharacterEncoding("UTF-8"); method to set the character set before obtaining the request parameters.

31. Garbled response?

1. Reason: Encoded by the server, ISO-8859-1 is used by default.
Decoded by the browser, GBK is used by default.
2. Solution method 1: Set the response header
response.setHeader("Content-Type", "text/ html;charset=utf-8”);
Method 2: Set the content type of the response

response.setContentType("text/html;charset=utf-8");
In this way, the browser can be told in the response header that the encoding method of the response body is UTF-8; at the same time, the server will also use this character set for encoding but It should be noted that the two methods must be performed before response.getWriter().

32. What are the flaws of Cookie objects?

1. Cookies are clear text and unsafe.
2. Different browsers have restrictions on the number and size of Cookie objects.
3. Cookie objects carry too much traffic.
4. The value in a Cookie object can only be a string, not an object. Data transmitted over the network can only be strings

33. What is the operating mechanism of Session?

1. Create a Session object on the server side, which has a globally unique ID.

2. When creating the Session object, create a special Cookie object. The name of the Cookie object is
JSESSIONID. The value of the Cookie object is the globally unique ID of the Session object, and this special Cookie object will be sent to Browser

3. When the browser sends a request in the future, it will carry this special Cookie object.
4. The server searches for the corresponding Session object in the server based on the value of this special Cookie object to distinguish different users.

34. Passivation and activation?

1. The process in which Session and objects in the session domain are serialized from memory to the hard disk is called passivation. Passivation occurs when the server is shut down.
2. The process of deserializing the Session and the objects in the session domain from the hard disk to the memory is called activation. Activation will occur when the server is powered on again.
3. To ensure that the objects in the session domain can be passivated and activated together with the Session, you must ensure that the class corresponding to the object implements the
Serializable interface .

35.How does Filter work?

There is a doFilter method in the Filter interface. After we write the Filter and configure which web resources to intercept, the WEB server will call the doFilter method of the filter every time before calling the service method of the web resource. Therefore, in this Writing code within a method can achieve the following goals:
let a piece of code execute before calling the target resource.
Whether to call the target resource (that is, whether to allow the user to access web resources). After calling the target resource, let a piece of code execute.
When the web server calls the doFilter method, it will pass in a filterChain object. The filterChain object is
the most important object in the filter interface. It also provides a doFilter method. Developers can decide whether to call this method according to their needs. Call this method. Then the web server will
call the service method of the web resource, that is, the web resource will be accessed, otherwise the web resource will not be accessed.

36. What is the Filter chain?

In a web application, multiple Filters can be developed and written. The combination of these Filters is called a Filter chain. The web server determines which Filter to call first based on the order in which the Filter is registered in the web.xml file. When the doFilter method of the first Filter is called, the web server will create a FilterChain object representing the Filter chain and pass it to the method
. In the doFilter method, if the developer calls the doFilter method of the FilterChain object, the web server will check
whether there is another filter in the FilterChain object. If there is, the second filter will be called. If not, the target resource will be called.

38. Servlet Filter Listener startup sequence?

The startup sequence is listener->Filter->servlet.
It is simply recorded as: listener, filter, servlet. The
execution sequence will not change due to the order of the three tags in the configuration file.

3. Open source framework

  1. Advantages of MyBatis?

1. Programming based on SQL statements is quite flexible and will not have any impact on the existing design of the application or database. SQL is written in XML, which decouples SQL from program code and facilitates unified management; XML tags are provided to support dynamic writing SQL statements and can be reused.
2. Compared with JDBC, the amount of code is reduced by more than 50%, eliminating a large amount of redundant code in JDBC, and there is no need to manually switch the connection; 3. Very compatible with various databases (because MyBatis uses JDBC to connect to the database, So as long as JDBC supports the database MyBatis supports it).
4. Ability to integrate well with Spring;
5. Provide mapping tags to support ORM field relationship mapping between objects and databases; provide object relationship mapping tags to support object relationship component maintenance.
3. What are the disadvantages of the MyBatis framework?
(1) The workload of writing SQL statements is relatively large, especially when there are many fields and related tables, which requires developers to have certain skills in writing SQL statements.
(2) SQL statements depend on the database, resulting in poor database portability and the database cannot be replaced at will.

  1. SpringMVC workflow?

1. The user sends a request to the front-end controller DispatcherServlet.
2. DispatcherServlet receives the request and calls the HandlerMapping processor mapper.
3. The processor mapper finds the specific processor according to the request URL, generates the processor object and the processor interceptor (if any) and returns them to DispatcherServlet.
4. DispatcherServlet calls the processor through the HandlerAdapter processor adapter.
5. Execution processor (Controller, also called back-end controller).
6. After the Controller execution is completed, it returns to ModelAndView
7. HandlerAdapter returns the controller execution result ModelAndView to DispatcherServlet
8. DispatcherServlet passes ModelAndView to ViewReslover view parser
9. ViewReslover returns the specific View after parsing
10. DispatcherServlet renders the View (that is, fills in the model data into view).
11. DispatcherServlet responds to users

4. What is SpringMVC?

SpringMVC is an mvc mode framework provided by spring

5.When is the MyBatis framework used?

(1) MyBatis focuses on SQL itself and is a flexible enough DAO layer solution.
(2) For projects that have high performance requirements or have changing needs, such as Internet projects, MyBatis will be a good choice.

6.What are the connections and differences between beanFactory and ApplicationContext in Spring?

BeanFactory is a relatively primitive Factory in spring and cannot support many plug-ins of spring, such as AOP functions,
Web applications, etc.
The ApplicationContext interface is derived from the BeanFactory interface. In addition to
the functions of the BeanFactory interface, it also has functions such as resource access, event propagation, and internationalized message access. The overall difference is as follows:
1) Use ApplicationContext to configure beans. The default configuration is singleton, which will be instantiated whether it is used or not.
The advantage is pre-loading, but the disadvantage is waste of memory; 2) When using BeanFactory to instantiate objects, the configured beans will not be instantiated until they are used. The advantage is that it saves
memory, but the disadvantage is that it is relatively slow and is mostly used for the development of mobile devices;
3) If there are no special requirements, it should be completed using ApplicationContext. ApplicationContext can realize
all the functions that can be realized by BeanFactory, and also has other more functions. .

7.What are the methods of SpringIOC injection?

Constructor injection set method injection interface injection

8. What is the difference between interceptors and filters?

​ 1. The interceptor is based on Java's reflection mechanism, while the filter is based on function callbacks.
2. The interceptor does not depend on the servlet container, but the filter depends on the servlet container.
3. Interceptors can only work on action requests, while filters can work on almost all requests.
​ 4. The interceptor can access the objects in the action context and value stack, but the filter cannot.
5. In the life cycle of the action, the interceptor can be called multiple times, but the filter can only be called once when the container is initialized.

9.What is SpringIOC?

Spring IOC is responsible for creating objects, managing objects (through dependency injection (DI)), assembling objects, configuring objects, and managing the entire life cycle of these objects.

10.What are the implementation methods of AOP?
实现 AOP 的技术,主要分为两大类:
静态代理 - 指使用 AOP 框架提供的命令进行编译,从而在编译阶段就可生成 AOP 代理类,因此也称为编译时增强;编译时编织(特殊编译器实现)
类加载时编织(特殊的类加载器实现)。
动态代理 - 在运行时在内存中“临时”生成 AOP 动态代理类,因此也被称为运行时增强。
  1. Explain the proxy model?

    1. Agency mode: The agency mode is what I should do. If I don’t do it, I leave it to the agent to complete. For example, I produce some products but I don’t sell them myself. I entrust agents to sell them for me and let the agents deal with customers. I am responsible for the production of the main products myself. The use of the proxy mode requires this class and the proxy class. This class and the proxy class jointly implement a unified interface. Then just call it in main. The business logic in this class generally does not change. When we need it, we can continuously add proxy objects or modify the proxy class to implement business changes.
    2. The proxy mode can be divided into: Static proxy Advantages: It can extend the target function without modifying the function of the target object. Disadvantages: Because the original and proxy classes need to implement a unified interface, many proxy classes will be generated. There are too many classes. Once methods are added to the interface, both the target object and the proxy object must be maintained. Dynamic proxy (JDK proxy/interface proxy) proxy object does not need to implement the interface. The generation of the proxy object uses the API of JDK to dynamically build the proxy object in the memory. We need to specify the type of interface implemented by the proxy object/target object. . Cglib proxy features: Construct a subclass object in memory to extend the functionality of the target object.
    3. Usage scenarios: When modifying code. You don't have to modify the code that others have written. If you need to modify it, you can extend the method through a proxy. When hiding a class, we can provide a proxy class for it. When we want to extend the functionality of a class, we can use a proxy class. When a class needs to provide different calling permissions to different callers, we can use a proxy class. accomplish. When reducing the amount of code in this category. When you need to increase processing speed. For example, when we access a large system, generating an instance at one time will take a lot of time. We can use the proxy mode to generate instances when needed, which can improve the access speed.

12.How does Mybatis encapsulate SQL execution results into target objects? What are the mapping forms?
第一种是使用<resultMap>标签,逐一定义数据库列名和对象属性名之间的映射关系。第二种是使用 sql 列的别名功能,将列的别名书写为对象属性名。
有了列名与属性名的映射关系后,Mybatis 通过反射创建对象,同时使用反射给对象的属性逐一赋值并返回,那些找不到映射关系的属性,是无法完成赋值的。
13. Spring bean life cycle?
1、Spring 容器根据配置中的 bean 定义中实例化 bean。
2、Spring 使用依赖注入填充所有属性,如 bean 中所定义的配置。
3. If bean Implement the BeanNameAware interface, and the factory is called by passing the bean ID.
setBeanName()。
4. If bean Implement the BeanFactoryAware interface, and the factory is called by passing its own instance.
setBeanFactory()。
5. If there are any BeanPostProcessors associated with the bean, call preProcessBeforeInitialization()
method.
6. If an init method (init-method attribute of ) is specified for the bean, it will be called.
7. Finally, if there are any BeanPostProcessors associated with the bean, it will be called
postProcessAfterInitialization() method.
8. If the bean implements the DisposableBean interface, destroy() will be called when the spring container is closed. 9. If the destroy method (destroy-method attribute of ) is specified for the bean, it will be called.
51
14.What design patterns are used in the Spring framework?

Proxy mode is the most used in AOP.
Singleton mode, the default is singleton mode when defining a bean in the Spring configuration file. Factory pattern, BeanFactory is used to create instances of objects.
Template method to solve repetitive code.
Front-end controller, Spring provides DispatcherSerclet to distribute requests. View help, Spring provides a series of JSP tags.
Dependency injection, which is the core concept used in the BeanFactory/ApplicationContext interface.

16.What are the benefits of using the Sping framework?

1. Simplify development, decouple, and integrate other frameworks.
2. Low intrusive design, low code pollution level.
3. Spring's DI mechanism reduces the complexity of business object replacement and improves the decoupling between software.
4. Spring AOP supports centralized management of some common tasks, such as security, transactions, logs, etc., so that code can be better reused.

17.Explain the scopes of several beans supported by Spring? (Remember the first two and recite the rest)

When creating a bean instance through the Spring container, not only can the bean instance be strengthened, but the scope can also be specified for the bean. Spring bean elements support the following five scopes:
Singleton: Singleton mode. In the entire spring IOC container, a bean defined using singleton will have only one instance
.
Prototype: Multiple instance mode, every time the beans defined by prototype are obtained through the getBean method in the container, a new bean instance will be generated.
Request: For each HTTP request, the bean defined using request will generate a new instance. This scope will only be valid in web applications.
Session: For each Http Session, the Bean defined using session will generate a new instance. Globalsession: Each global Http Session defined using session will generate a new instance.

18.How to inject a java collection in Spring?

Spring provides configuration elements for four theoretical collection classes:

lt;List&: This tag is used to assemble a list value with duplicate values
​​lt;set&: This tag is used to assemble a set value without duplicate values ​​lt;map&: This tag can be used to inject key-value pairslt;props&: This tag Used to support injection of key-value pairs and string type key-value pairs.

19.What are Spring beans?

They are the objects that form the backbone of a user's application.
Beans are managed by the Spring IoC container.
They are instantiated, configured, assembled and managed by the Spring IoC container. Beans are created based on configuration metadata provided by the user to the container.

23. What are the important annotations of Spring?

@Controller - Controller class used in Spring MVC projects. @Service - for service classes.
@RequestMapping - used to configure URI mapping in controller handler methods.
@ResponseBody - used to send Object as response, usually used to send XML or JSON data as response.
@PathVariable - Used to map dynamic values ​​from URIs to handler method parameters.
@Autowired - Used for autowiring dependencies in spring beans.

@Qualifier - Use @Autowired annotation to avoid confusion when there are multiple instances of bean type. @Scope - used to configure the scope of spring beans.
@Configuration, @ComponentScan and @Bean - for java based configuration. @Aspect, @Before, @After, @Around, @Pointcut - used in aspect programming (AOP).

24. What are the differences between @Component, @Controller, @Repository, and @Service?

1. @Component: This marks the java class as a bean. It is the common stereotype for any Spring managed component. Spring's component scanning mechanism can now pick it up and pull it into the application environment.
2. @Controller: This marks a class as a Spring Web MVC controller. Beans marked with it are automatically imported into the IoC container.
3. @Service: This annotation is a specialization of the component annotation. It does not provide any additional behavior for the @Component annotation. You can use @Service instead of @Component in service layer classes as it specifies the intent in a better way.
4. @Repository: This annotation is a specialization of the @Component annotation with similar purposes and functions.
It provides additional benefits to DAO . It imports DAO into the IoC container and makes unchecked exceptions eligible for conversion to Spring DataAccessException.

27.What is the principle of Spring AOP (aspect-oriented) programming?

1. AOP aspect-oriented programming is an idea. It is to extract aspects in the business processing process to achieve the purpose of optimizing the code and reducing duplication of code. For example, when writing business logic code, we are accustomed to writing: logging, transaction control, and permission control, etc. Each sub-module must write these codes, and there is obvious duplication of code. At this time, we use aspect-oriented programming ideas and cross-cutting technology to extract the repetitive parts of the code that do not affect the main business logic and place them somewhere for centralized management and calling. Form log aspects, transaction control aspects, and authority control aspects. In this way, we only need to deal with the logic of the business, which improves work efficiency and makes the code simple and elegant. This is the aspect-oriented programming idea, which is an extension of the object-oriented programming idea.
2. AOP usage scenarios: caching, rights management, content delivery, error handling, lazy loading, record tracking, optimization, calibration,
debugging, persistence, resource pools, synchronization management, transaction control, etc. Related concepts of AOP: Aspect,
JoinPoint, Advice, Pointcut, Proxy: WeaVing 3. The programming principle of Spring AOP? Proxy mechanism JDK's dynamic proxy: can only be used to generate proxies for classes that implement interfaces. Cglib proxy: Proxies are generated for classes that do not implement interfaces. The underlying bytecode enhancement technology is applied to generate subclass objects of the current class.

28.What is the use of Spring MVC framework?

The Spring Web MVC framework provides a model-view-controller architecture and ready-to-use components for developing flexible and loosely coupled web applications. The MVC pattern helps separate different aspects of the application such as input logic, business logic, and UI logic while providing loose coupling between all these elements.

31.What is the difference between #{} and ${} in Mybatis?

#{} is precompiled, KaTeX parse error: Expected 'EOF', got '#' at position 22: ...replacement. When Mybatis processes #̲{}, it will replace ${} with the value of the variable when #{... {} in SQL. Using #{} can effectively prevent SQL injection and improve system security.

32.What is the difference between @Autowire and @Resource in Spring?

@Autowire assembles by type by default. By default, it requires that the dependent object must exist. If it is allowed to be null, you can set its required attribute to false. If we want to assemble by name, we can use it in conjunction with the @Qualifier annotation; @Resource defaults by name. Assembly, when a bean matching the name cannot be found, it will be assembled according to the type. It can be
specified through the name attribute. If the name attribute is not specified, when the annotation is marked on the field, the name of the field will be used as the bean name by default to find the dependent object. The annotation is marked on the setter method of the attribute, that is, by default, the attribute name is used as the bean name to find the dependent object.

33.What is Inversion of Control (IOC) and what is Dependency Injection (DI)?

IOC: The dependency relationship between objects is created by the container. The relationship between objects is originally created and maintained by our developers themselves. After we use the Spring framework, the relationship between objects is created and maintained by the container. Let the container do what the developer does. This is inversion of control. The BeanFactory interface is the core interface of the Spring Ioc container.
DI: When we use the Spring container, the container establishes dependencies between objects by calling the set method or constructor.
Inversion of control is the goal, and dependency injection is a means for us to achieve inversion of control.

34.How does Spring work?

1. The most important thing inside is IOC. It used to be a new object, but now it can be obtained directly from the container and injected dynamically. This is actually using reflection in Java. Reflection actually means dynamically creating and calling objects at runtime. Spring dynamically creates objects and calls methods in objects at runtime based on the xml Spring configuration file.
2. Another core of Spring is AOP aspect-oriented programming, which can supervise and control a certain type of object (that is, calling the module you specify before and after calling the specific method of this type of object), thereby achieving the function of expanding a module. . These are achieved through configuration classes. (Logs, transactions, etc.)
3. The purpose of Spring: is to make the relationship between objects and objects (modules and modules) not related through code, but all managed through configuration class descriptions (Spring uses reflection internally based on these configurations to dynamically Assembly objects) Remember: Spring is a container, and only objects in the container will have the services and functions provided by Spring.
4. The most classic design pattern used in Spring: template method pattern. (Students who are interested can learn more about it). The core container component is BeanFactory, which is the implementation of the factory pattern. BeanFactory uses the Inversion of Control (IOC) pattern to separate an application's configuration and dependency specifications from the actual application code.

36. What is the running process of SpringMVC?

DispatcherServlet front controller | HandlerMapping request mapping (to Controller)
| HandlerAdapter request mapping (to the method of Controller class) | Controller controller | HandlerIntercepter interceptor | ViewResolver view mapping | View view processing

Guess you like

Origin blog.csdn.net/lanlan112233/article/details/129706390