24. Tell me about the implementation principle of HashSet?
-
The bottom layer of HashSet is implemented by HashMap
-
The value of HashSet is stored on the key of HashMap
-
The value of HashMap is unified as PRESENT
25. What is the difference between ArrayList and LinkedList?
The most obvious difference is that the underlying data structure of ArrayList is array, which supports random access, while the underlying data structure of LinkedList is bidirectional circular linked list, which does not support random access. Using subscripts to access an element, the time complexity of ArrayList is O(1) and LinkedList is O(n).
26. How to realize the conversion between array and List?
-
Convert List to array: call the toArray method of ArrayList.
-
Convert an array to a List: call the asList method of Arrays.
27. What is the difference between ArrayList and Vector?
-
Vector is synchronous, but ArrayList is not. However, if you seek to change the list during iterations, you should use CopyOnWriteArrayList.
-
ArrayList is faster than Vector. Because it has synchronization, it will not be overloaded.
-
ArrayList is more general because we can easily get synchronized lists and read-only lists using the Collections tool class.
28. What is the difference between array and ArrayList?
-
Array can hold basic types and objects, while ArrayList can only hold objects.
-
Array is of specified size, while ArrayList is of fixed size.
-
Array does not provide as many functions as ArrayList, such as addAll, removeAll and iterator.
29. What is the difference between poll() and remove() in the Queue?
Both poll() and remove() take an element from the queue, but poll() will return null when it fails to get the element, but an exception will be thrown when remove() fails.
30. Which collection classes are thread safe?
-
vector: there is more synchronization mechanism (thread safety) than arraylist. It is not recommended to use it now because of its low efficiency. In web applications, especially foreground pages, efficiency (page response speed) is often given priority.
-
statck: Stack class, first in, last out.
-
hashtable: more thread safety than hashmap.
-
Enumeration: enumeration, equivalent to iterator.
31. What is Iterator?
Iterator is a design pattern. It is an object. It can traverse and select objects in a sequence, and developers do not need to understand the underlying structure of the sequence. Iterators are often referred to as "lightweight" objects because they are inexpensive to create.
32. How to use iterator? What are the characteristics?
The Iterator function in Java is relatively simple and can only move in one direction:
(1) Using the method iterator() requires the container to return an Iterator. The first time the Iterator's next() method is called, it returns the first element of the sequence. Note: the iterator() method is Java Lang. Iterable interface, inherited by Collection.
(2) Use next() to get the next element in the sequence.
(3) Use hasNext() to check whether there are any elements in the sequence.
(4) Use remove() to delete the newly returned element from the iterator.
Iterator is the simplest implementation of Java iterator. The ListIterator designed for List has more functions. It can traverse the List from two directions, or insert and delete elements from the List.
33. What is the difference between iterator and ListIterator?
-
Iterator can be used to traverse Set and List sets, but ListIterator can only be used to traverse List.
-
The Iterator can only traverse the collection forward, and the ListIterator can be forward or backward.
-
ListIterator implements the Iterator interface and contains other functions, such as adding elements, replacing elements, obtaining the indexes of the previous and subsequent elements, and so on.
3, Multithreading
35. What is the difference between parallelism and concurrency?
-
Parallelism means that two or more events occur at the same time; Concurrency means that two or more events occur at the same time interval.
-
Parallelism refers to multiple events on different entities, and concurrency refers to multiple events on the same entity.
-
"Simultaneous" processing of multiple tasks on one processor and simultaneous processing of multiple tasks on multiple processors. Such as hadoop distributed cluster.
Therefore, the goal of concurrent programming is to make full use of each core of the processor to achieve the highest processing performance.
36. What is the difference between threads and processes?
In short, process is the basic unit of program operation and resource allocation. A program has at least one process and a process has at least one thread. The process has independent memory units during execution, and multiple threads share memory resources to reduce the number of switches, so it is more efficient. Thread is an entity of a process. It is the basic unit of cpu scheduling and dispatching. It is a smaller basic unit that can run independently than a program. Multiple threads in the same process can execute concurrently.
37. What is a daemon thread?
A daemon thread is a service thread. To be precise, it is a thread that serves other threads.
38. What are the ways to create threads?
①. Inherit Thread class to create Thread class
-
Define the subclass of Thread class and override the run method of this class. The method body of the run method represents the task to be completed by the Thread. Therefore, the run() method is called the execution body.
-
Create an instance of Thread subclass, that is, create a Thread object.
-
Call the start() method of the thread object to start the thread.
②. Create thread class through Runnable interface
-
Define the implementation class of the runnable interface and rewrite the run() method of the interface. The method body of the run() method is also the thread execution body of the thread.
-
Create an instance of the Runnable implementation class, and use this instance as the target of the Thread to create the Thread object, which is the real Thread object.
-
Call the start() method of the thread object to start the thread.
③. Creating threads through Callable and Future
-
Create the implementation class of the Callable interface and implement the call() method. The call() method will be used as the thread executor and has a return value.
-
Create an instance of the Callable implementation class, and use the FutureTask class to wrap the Callable object, which encapsulates the return value of the call() method of the Callable object.
-
Create and start a new Thread using the FutureTask object as the target of the Thread object.
-
Call the get() method of the FutureTask object to get the return value after the execution of the child thread.
39. What's the difference between runnable and callable?
It's a little deep. It also shows the breadth of knowledge a Java programmer can learn.
-
The return value of the run() method in the Runnable interface is void. What it does is simply to execute the code in the run() method;
-
The call() method in the Callable interface has a return value and is a generic type. It can be used to obtain the results of asynchronous execution in combination with Future and FutureTask.
40. What are the status of threads?
Threads usually have five states: create, ready, run, block, and die.
-
Create status. When generating a thread object, the start method of the object is not called, which means that the thread is in the creation state.
-
Ready status. After calling the start method of the thread object, the thread enters the ready state, but the thread scheduler has not set the thread as the current thread, and it is in the ready state. After the thread runs and comes back from waiting or sleep, it will also be in the ready state.
-
Running status. The thread scheduler sets the thread in the ready state as the current thread. At this time, the thread enters the running state and starts running the code in the run function.
-
Blocking state. When a thread is running, it is suspended, usually to wait for a certain time (for example, a resource is ready) before continuing. sleep,suspend, wait and other methods can cause thread blocking.
-
State of death. If the execution of a thread's run method ends or the stop method is called, the thread will die. For dead threads, you can no longer use the start method to make them ready
41. What is the difference between sleep() and wait()?
sleep(): the method is a static method of the Thread class, which allows the calling Thread to enter the sleep state and give execution opportunities to other threads. After the sleep time is over, the Thread enters the ready state and competes with other threads for cpu execution time. Because sleep() is a static method, it cannot change the machine lock of the object, When a sleep() method is invoked in a synchronized block, though the Thread is asleep, the machine lock of the object is not released, and other threads are still unable to access the object.
Wait(): wait() is a method of the Object class. When a thread executes the wait method, it enters a waiting pool related to the Object and releases the machine lock of the Object so that other threads can access it. You can wake up the waiting thread through the notify and notifyAll methods.
42. What is the difference between notify() and notifyAll()?
-
If the thread calls the wait() method of the object, the thread will be in the waiting pool of the object, and the threads in the waiting pool will not compete for the lock of the object.
-
When a thread calls the notifyAll() method (wake up all wait threads) or notify() method of the object (only one wait thread is awakened randomly), the awakened thread will enter the lock pool of the object, and the threads in the lock pool will compete for the lock of the object. That is, after calling notify, as long as a thread will enter the lock pool from the waiting pool, and notifyAll will move all threads in the waiting pool of the object to the lock pool to wait for lock competition.
-
The thread with high priority has a high probability of competing for the object lock. If a thread does not compete for the object lock, it will remain in the lock pool. Only when the thread calls the wait() method again will it return to the waiting pool. The thread competing for the object lock will continue to execute until the synchronized code block is executed. It will release the object lock. At this time, the threads in the lock pool will continue to compete for the object lock.
43. What is the difference between run() and start() of a thread?
Each Thread completes its operation through the method run() corresponding to a specific Thread object. The method run() is called the Thread body. Start a Thread by calling the start() method of the Thread class.
start() method to start a Thread, which really realizes multi-threaded operation. At this time, you can continue to execute the following code directly without waiting for the Run method body code to be executed; At this time, the Thread is in a ready state and is not running. Then, the Thread class calls the method run() to complete its running state. Here, the method run() is called the Thread body, which contains the content of the Thread to be executed. The Run method ends and the Thread terminates. The CPU then schedules other threads.
The run() method is in this thread. It is only a function in the thread, not multithreaded. If you call run() directly, it is actually equivalent to calling an ordinary function. The run() method to be used directly must wait for the run() method to execute before executing the following code. Therefore, there is only one execution path and there is no thread feature at all. Therefore, the start() method should be used instead of the run() method during multithreading execution.
44. What are the ways to create a thread pool?
①. newFixedThreadPool(int nThreads)
Create a fixed length thread pool. Each time a task is submitted, create a thread until the maximum number of thread pools is reached. At this time, the thread size will not change. When the thread ends with unexpected errors, the thread pool will supplement a new thread.
②. newCachedThreadPool()
Create a cacheable thread pool. If the size of the thread pool exceeds the processing requirements, idle threads will be recycled automatically. When the requirements increase, new threads can be added automatically. There is no limit on the size of the thread pool.
③. newSingleThreadExecutor()
This is a single threaded Executor. It creates a single worker thread to execute tasks. If the thread ends abnormally, it will create a new one to replace it; Its characteristic is that it can ensure the serial execution of tasks according to the order of tasks in the queue.
④. newScheduledThreadPool(int corePoolSize)
A fixed length thread pool is created, and tasks are executed in a delayed or timed manner, similar to Timer.
45. What are the status of thread pools?
Thread pools have five statuses: Running, ShutDown, Stop, Tidying, and Terminated.
Frame diagram of state switching of thread pool:
46. What is the difference between the submit() and execute() methods in the thread pool?
-
The received parameters are different
-
submit has a return value, but execute does not
-
submit is convenient for Exception handling
47. How to ensure the safe operation of multithreading in java programs?
Thread safety is embodied in three aspects:
-
Atomicity: provides mutually exclusive access. Only one thread can operate on data at a time (atomic,synchronized);
-
Visibility: a thread's modification of main memory can be seen by other threads in time (synchronized,volatile);
-
Orderliness: a thread observes the execution order of instructions in other threads. Due to the reordering of instructions, the observation results are generally disordered (happens before principle).
48. What is the upgrade principle of multithreaded locks?
In Java, locks have four states, from low to high: stateless lock, biased lock, lightweight lock and heavyweight lock. These States will gradually upgrade with the competition. Locks can be upgraded but not downgraded.
Graphic process of lock upgrade:
49. What is deadlock?
Deadlock is a blocking phenomenon caused by two or more processes competing for resources or communicating with each other in the execution process. If there is no external force, they will not be able to move forward. At this time, it is said that the system is in a deadlock state or the system has a deadlock. These processes that are always waiting for each other are called deadlock processes. It is an error at the operating system level and the abbreviation of process deadlock. It was first proposed by Dijkstra when studying banker algorithm in 1965. It is one of the most difficult problems in the computer operating system and even the whole field of concurrent programming.
50. How to prevent deadlock?
Four necessary conditions for Deadlock:
-
Mutually exclusive condition: the process does not allow other processes to access the allocated resource. If other processes access the resource, they can only wait until the process occupying the resource is used and releases the resource
-
Request and hold conditions: after a process obtains a certain resource, it makes a request for other resources, but the resource may be occupied by other processes. The request is blocked, but it still keeps the resources it obtains
-
Inalienable conditions: refers to the resources obtained by the process, which cannot be deprived before the use is completed, and can only be released after the use is completed
-
Loop wait condition: refers to a loop wait resource relationship formed between several processes after a process deadlock
These four conditions are the necessary conditions for deadlock. As long as the system deadlock occurs, these conditions must be true, and as long as one of the above conditions is not satisfied, deadlock will not occur.
Understanding the causes of deadlock, especially the four necessary conditions for deadlock, can avoid, prevent and release deadlock as much as possible.
Therefore, in terms of system design and process scheduling, pay attention to how to prevent these four necessary conditions from being established, and how to determine the reasonable allocation algorithm of resources to avoid processes permanently occupying system resources.
In addition, prevent the process from occupying resources when it is waiting. Therefore, reasonable planning should be given to the allocation of resources.
51. What is ThreadLocal? What are the usage scenarios?
Thread local variables are variables limited to the thread itself and are not shared among multiple threads. Java provides ThreadLocal class to support thread local variables, which is a way to realize thread safety. However, be careful when using thread local variables in the management environment (such as web server). In this case, the life cycle of the working thread is longer than that of any application variable. Once any thread local variable is not released after the work is completed, there is a risk of memory leakage in Java applications.
52. Talk about the underlying implementation principle of synchronized?
synchronized can ensure that only one method can enter the critical area at the same time when the method or code block is running. At the same time, it can also ensure the memory visibility of shared variables.
Every object in Java can be used as a lock, which is the basis for synchronized synchronization:
-
Common synchronization method, lock is the current instance object
-
Static synchronization method. The lock is the class object of the current class
-
Synchronization method block, lock is the object in parentheses
53. What is the difference between synchronized and volatile?
-
volatile essentially tells the jvm that the value of the current variable in the register (working memory) is uncertain and needs to be read from main memory; synchronized locks the current variable, only the current thread can access the variable, and other threads are blocked.
-
volatile can only be used at the variable level; synchronized can be used at the variable, method, and class levels.
-
volatile can only realize the modification visibility of variables and cannot guarantee atomicity; synchronized ensures the visibility and atomicity of variable modification.
-
volatile does not cause thread blocking; synchronized may cause thread blocking.
-
Variables marked volatile are not optimized by the compiler; Variables marked synchronized can be optimized by the compiler.
54. What is the difference between synchronized and Lock?
-
Firstly, synchronized is the built-in keyword of java. At the jvm level, Lock is a java class;
-
synchronized cannot judge whether to obtain the Lock status, and Lock can judge whether to obtain the Lock;
-
synchronized will automatically release the lock (a} thread will release the lock after executing the synchronization code; b thread will release the lock if an exception occurs during execution). Lock needs to release the lock manually in finally (unlock() method releases the lock), otherwise it is easy to cause thread deadlock;
-
Two threads 1 and 2 with the synchronized keyword. If the current thread 1 obtains a Lock, the thread 2 waits. If thread 1 is blocked, thread 2 will wait all the time, but the Lock lock does not necessarily wait. If you try to obtain the Lock, the thread can end without waiting all the time;
-
synchronized locks are reentrant, non interruptible and unfair, while Lock locks are reentrant, judgmental and fair (both);
-
Lock lock is suitable for the synchronization of a large number of synchronized codes, and synchronized lock is suitable for the synchronization of a small number of codes.
55. What is the difference between synchronized and ReentrantLock?
Synchronized is the same keyword as if, else, for and while, and ReentrantLock is a class, which is the essential difference between the two. Since ReentrantLock is a class, it provides more and more flexible features than synchronized. It can be inherited, have methods, and have a variety of class variables. The extensibility of ReentrantLock than synchronized is reflected in the following points:
-
ReentrantLock can set the waiting time for obtaining the lock, so as to avoid deadlock
-
ReentrantLock can obtain the information of various locks
-
ReentrantLock provides flexibility for multiple notifications
In addition, the locking mechanisms of the two are actually different: the underlying call of ReentrantLock is to lock the Unsafe park method, and the synchronized operation should be the mark word in the object header.
56. Talk about the principle of atomic?
The basic feature of classes in Atomic package is that in a multithreaded environment, When multiple threads operate on a single variable (including basic type and reference type) at the same time, it is exclusive, that is, when multiple threads update the value of the variable at the same time, only one thread can succeed, while the unsuccessful thread can continue to try like a spin lock until the execution is successful.
The core methods in the Atomic family of classes call several local methods in the unsafe class. One thing we need to know first is the unsafe class, whose full name is sun misc. Unsafe, this class contains a large number of operations on C code, including many direct memory allocation and Atomic operation calls. The reason why it is marked as unsafe is to tell you that a large number of method calls in this class will have security risks and need to be used carefully. Otherwise, it will lead to serious consequences. For example, when allocating memory through unsafe, If you specify some regions by yourself, it may lead to the problem that some pointers like C + + cross the boundary to other processes.
4, Reflection
====
57. What is reflection?
Reflection mainly refers to the ability of a program to access, detect and modify its own state or behavior
Java reflection:
In the Java runtime environment, for any class, can you know what properties and methods this class has? Can any method of any object be called
Java reflection mechanism mainly provides the following functions:
-
Determine the class to which any object belongs at run time.
-
Construct an object of any class at run time.
-
Judge the member variables and methods of any class at run time.
-
Call the method of any object at run time.
58. What is java serialization? When do I need serialization?
In short, it is to save the state of various objects in memory (that is, instance variables, not methods), and you can read the saved object state again. Although you can use your own various methods to save object states, Java provides you with a better mechanism to save object states than yourself, that is serialization.
When serialization is required:
a) When you want to save the object state in memory to a file or database;
b) When you want to use sockets to transfer objects over the network;
c) When you want to transfer objects through RMI;
59. What is a dynamic agent? What are the applications?
Dynamic proxy:
When you want to add some extra processing to the methods in the class that implements an interface. For example, add logs, add transactions, etc. You can create a proxy for this class, so the name suggests that you create a new class. This class not only contains the functions of the original class methods, but also adds a new class with additional processing on the basis of the original class. This proxy class is not well-defined, but dynamically generated. It has decoupling significance, flexibility and strong expansibility.
Application of dynamic agent:
-
AOP for Spring
-
Add transaction
-
Add authority
-
Add log
60. How to implement dynamic agent?
First, you must define an interface and an InvocationHandler (which passes the object of the class implementing the interface to it) processing class. There is also a tool class proxy (it is habitually called a proxy class because calling its newInstance() can generate a proxy object. In fact, it is only a tool class that generates a proxy object). Use the InvocationHandler to splice the proxy class source code, compile it to generate the binary code of the proxy class, load it with the loader, instantiate it to generate the proxy object, and finally return.
5, Object copy
==========
61. Why use cloning?
If you want to process an object and keep the original data for the next operation, you need to clone. Cloning in Java language is for class instances.
62. How to implement object cloning?
There are two ways:
1). Implement the clonable interface and override the clone() method in the Object class;
2). The Serializable interface is implemented to realize cloning through object serialization and deserialization, which can realize real deep cloning. The code is as follows:
import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; public class MyUtil { private MyUtil() { throw new AssertionError(); } @SuppressWarnings("unchecked") public static <T extends Serializable> T clone(T obj) throws Exception { ByteArrayOutputStream bout = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(bout); oos.writeObject(obj); ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray()); ObjectInputStream ois = new ObjectInputStream(bin); return (T) ois.readObject(); // Note: calling the close method of ByteArrayInputStream or ByteArrayOutputStream object has no meaning // These two memory based streams can release resources as long as the garbage collector cleans up objects, which is different from the release of external resources such as file streams } }
Here is the test code:
import java.io.Serializable; /** * human beings * @author nnngu * */ class Person implements Serializable { private static final long serialVersionUID = -9102017020286042305L; private String name; // full name private int age; // Age private Car car; // Car public Person(String name, int age, Car car) { this.name = name; this.age = age; this.car = car; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public Car getCar() { return car; } public void setCar(Car car) { this.car = car; } @Override public String toString() { return "Person [name=" + name + ", age=" + age + ", car=" + car + "]"; } }
/**
-
Cars
-
@author nnngu
*/
class Car implements Serializable {
private static final long serialVersionUID = -5713945027627603702L; private String brand; // brand private int maxSpeed; // Top speed public Car(String brand, int maxSpeed) { this.brand = brand; this.maxSpeed = maxSpeed; } public String getBrand() { return brand; } public void setBrand(String brand) { this.brand = brand; } public int getMaxSpeed() { return maxSpeed; } public void setMaxSpeed(int maxSpeed) { this.maxSpeed = maxSpeed; } @Override public String toString() { return "Car [brand=" + brand + ", maxSpeed=" + maxSpeed + "]"; }
}
class CloneTest { public static void main(String[] args) { try { Person p1 = new Person("Guo Jing", 33, new Car("Benz", 300)); Person p2 = MyUtil.clone(p1); // Deep cloning p2.getCar().setBrand("BYD"); // Modify the brand attribute of the car object p2 associated with the cloned Person object // The car associated with the original Person object p1 will not be affected // Because when cloning the Person object, its associated car object is also cloned System.out.println(p1); } catch (Exception e) { e.printStackTrace(); } } } ``` Note: cloning based on serialization and deserialization is not only deep cloning, but more importantly, it can check whether the object to be cloned supports serialization through generic qualification. This check is completed by the compiler rather than throwing an exception at run time. This scheme is obviously better than using Object Class clone Method to clone an object. It's always better to expose problems at compile time than to leave them at run time. ### **63\. What is the difference between deep copy and shallow copy** * Shallow copy only copies the reference address of the object. Two objects point to the same memory address. Therefore, if you modify any value, the other value will change. This is called shallow copy (for example: assign()) * Deep copy copies objects and values. When two objects modify any value, the other value will not change. This is called deep copy (for example: JSON.parse()and JSON.stringify(),However, this method cannot copy function types) * * * Vi**Java Web** ============== ### **64\. What is the difference between JSP and servlet** 1. jsp After compiling, it becomes Servlet.(JSP The essence of is Servlet,JVM Can only identify java Class, unrecognized JSP Your code, Web Container will JSP The code is compiled into JVM Recognizable java Class) 2. jsp Better at page display, servlet Better at logic control. 3. Servlet There are no built-in objects in the, Jsp All built-in objects in must pass HttpServletRequest Object, HttpServletResponse Objects and HttpServlet Object gets. 4. Jsp yes Servlet A simplification of, using Jsp Just complete what the programmer needs to output to the client, Jsp Medium Java How scripts are embedded into a class is determined by Jsp Container complete. and Servlet Is a complete Java Class, of this class Service Method is used to generate a response to the client. ### **65\. What are the built-in objects of JSP? What are the functions** JSP There are 9 built-in objects: * request: Encapsulates the request from the client, including the GET or POST Requested parameters; * response: Encapsulate the response of the server to the client; * pageContext: Other objects can be obtained through this object; * session: Encapsulating the object of the user session; * application: Encapsulate the object of the server running environment; * out: The output stream object of the output server response; * config: Web Configuration object of the application; * page: JSP Page itself (equivalent to Java In the program this); * exception: Encapsulates the object that the page throws an exception. ### **66\. What are the four scopes of jsp** JSP The four scopes in include page,request,session and application,Specifically: * **page**Represents the objects and properties associated with a page. * **request**Representative and Web Objects and properties related to a request made by a client. A request may span multiple pages and involve multiple users Web Components; Temporary data that needs to be displayed on the page can be placed in this scope. * **session**Represents objects and properties related to a session established between a user and the server. The data related to a user should be placed in the user's own session Yes. * **application**Representative and the whole Web Application related objects and attributes, which essentially span the entire Web An application, including a global scope for multiple pages, requests, and sessions. ### **67\. What is the difference between session and cookie** * because HTTP The protocol is a stateless protocol, so when the server needs to record the user's status, it needs to use some mechanism to identify the specific user. This mechanism is Session.A typical scenario, such as a shopping cart, when you click the order button, because HTTP The protocol is stateless, so it does not know which user operates, so the server needs to create a specific protocol for a specific user Session,It is used to identify the user and track the user, so as to know how many books are in the shopping cart. this Session It is saved on the server and has a unique ID. Save on the server Session There are many methods, including memory, database and files. Cluster should also be considered Session For the transfer, in large websites, there will generally be special Session The server cluster is used to save user sessions at this time Session The information is stored in memory, and some caching services are used, such as Memcached Or something Session. * Think about how the server identifies specific customers? This time Cookie It's on the stage. every time HTTP When requesting, the client will send the corresponding message Cookie Information to the server. In fact, most applications use Cookie To achieve Session Tracked, first created Session When, the server will HTTP The protocol tells the client that it needs to Cookie Record one in it Session ID,Every time you request this session ID Send it to the server and I'll know who you are. Someone asked if the client's browser was disabled Cookie What should I do? In this case, a method called URL Rewrite the technology to perform session tracking, that is, each time HTTP Interaction, URL Will be followed by a sid=xxxxx With such parameters, the server identifies the user accordingly. * Cookie In fact, it can also be used in some user-friendly scenarios. Imagine that you have logged in to a website once and don't want to enter your account again when you log in next time. What should you do? This information can be written to Cookie Inside, when visiting the website, the script of the website page can read this information and automatically fill in the user name for you, which can be convenient for users. This too Cookie The origin of the name gives users a little sweetness. So, to sum up: Session It is a data structure saved in the server to track the user's status. This data can be saved in clusters, databases and files; Cookie It is a mechanism for the client to save user information. It is used to record some user information. It is also an implementation Session A way of. ### **68\. How does session work** actually session Is a file similar to a hash table that exists on the server. It contains the information we need, which can be taken out when we need it. Similar to a large one map Well, the keys inside store the user's sessionid,The user will bring this when sending a request to the server sessionid. At this time, you can take the corresponding value from it. ### **69\. If the client prohibits cookie s, can session still be used** Cookie And Session,It is generally considered to be two independent things, Session It adopts the scheme of maintaining state on the server side, and Cookie It adopts the scheme of maintaining state on the client. But why is it disabled Cookie You can't get it Session And? because Session Yes Session ID To determine the server corresponding to the current conversation Session,and Session ID Yes Cookie To pass, disable Cookie Equivalent to losing Session ID,You won't get it Session Yes. Assume that the user is turned off Cookie Use in case of Session,There are several ways to realize it: 1. set up php.ini In the configuration file“ session.use\_trans\_sid = 1",Or open at compile time“--enable-trans-sid"Options, let PHP Automatic cross page delivery Session ID. 2. Manual pass URL Value transfer, hidden form transfer Session ID. 3. Save in the form of file, database, etc Session ID,Called manually during page spread. ### **70\. What is the difference between spring MVC and struts** # 1200 pages of Java architecture interview topics and answers It's not easy to make up, right**1200 page Java Architecture interview topics and answers**Interested, please help**forward/give the thumbs-up** **[CodeChina Open source project: [first tier big factory] Java Analysis of interview questions+Core summary learning notes+Latest explanation Video]](https://codechina.csdn.net/m0_60958482/java-p7)** ![](https://img-blog.csdnimg.cn/img_convert/956d04130251c7383e12606838d7e6fa.png) ![](https://img-blog.csdnimg.cn/img_convert/b876b25de80a46f701f7471b953103a4.png) # Common interview questions of Baidu, byte, meituan and other large factories A mechanism used to record some user information is also an implementation Session A way of. ### **68\. How does session work** actually session Is a file similar to a hash table that exists on the server. It contains the information we need, which can be taken out when we need it. Similar to a large one map Well, the keys inside store the user's sessionid,The user will bring this when sending a request to the server sessionid. At this time, you can take the corresponding value from it. ### **69\. If the client prohibits cookie s, can session still be used** Cookie And Session,It is generally considered to be two independent things, Session It adopts the scheme of maintaining state on the server side, and Cookie It adopts the scheme of maintaining state on the client. But why is it disabled Cookie You can't get it Session And? because Session Yes Session ID To determine the server corresponding to the current conversation Session,and Session ID Yes Cookie To pass, disable Cookie Equivalent to losing Session ID,You won't get it Session Yes. Assume that the user is turned off Cookie Use in case of Session,There are several ways to realize it: 1. set up php.ini In the configuration file“ session.use\_trans\_sid = 1",Or open at compile time“--enable-trans-sid"Options, let PHP Automatic cross page delivery Session ID. 2. Manual pass URL Value transfer, hidden form transfer Session ID. 3. Save in the form of file, database, etc Session ID,Called manually during page spread. ### **70\. What is the difference between spring MVC and struts** # 1200 pages of Java architecture interview topics and answers It's not easy to make up, right**1200 page Java Architecture interview topics and answers**Interested, please help**forward/give the thumbs-up** **[CodeChina Open source project: [first tier big factory] Java Analysis of interview questions+Core summary learning notes+Latest explanation Video]](https://codechina.csdn.net/m0_60958482/java-p7)** [External chain picture transfer...(img-5cPpFotv-1630382215601)] [External chain picture transfer...(img-Axnv8qw5-1630382215602)] # Common interview questions of Baidu, byte, meituan and other large factories ![](https://img-blog.csdnimg.cn/img_convert/f7c028675fe2b2f249553361c8a93d6d.png)