🍅 Programmer Xiao Wang's blog: Programmer Xiao Wang's blog
🍅 Welcome to praise 👍 Collection ⭐ Leaving a message. 📝
🍅 If you have an editor's error and contact the author, if you have a good article, welcome to share it with me, I will extract the essence and discard the dross.
🍅 Learning route of java self-study: Learning route of java self-study
1. java language features?
# Three features: written test questions simple: Automatic syntax checking and automatic garbage collection mechanism Object oriented everything is object-oriented Cross platform can run on any operating system platform jvm java virtual machine Simple object-oriented cross platform - Cross platform: JVM Implement cross platform standards - Simplicity: java Language, strongly typed language, automatic syntax checking java Support automatic garbage collection mechanism c++/c Dispose of garbage collection by yourself - object-oriented: stay java Everything in the world is an object
2. java language operating mechanism?
# Written test questions of operation mechanism - Compile first and then interpret and run .java---> .class file operating system jvm Virtual machine version window linux macos oralce hotspot g9 IBM virtual machine ...
3. What is a JVM?
# JVM: (Java virtual machine) Java virtual machine JVM = = = = = > classloader class loader = = = = > class - 1.JVM implement.class(Sub section code file)Execution engine for - 2.JVM Shielding the important embodiment of the cross platform of the underlying operating system
4. Java Naming Conventions?
The alphanumeric underscore $cannot start with a number. It is strictly case sensitive. Note: it is best not to use keyword special characters
Package name: all in lowercase
Class name: capitalize multiple words
Method name: hump naming method: the first word is lowercase, and then the first word is uppercase
Variable name: hump nomenclature
Constant name: all uppercase String TIME_OUT =
# Note: package names are all lowercase, class names are capitalized (multiple words are capitalized), method / variable hump naming (the first word is lowercase, and later words are capitalized), constants are all capitalized, and multiple words are used_ separate com.baizhi.dao UserServiceImpl getMethod() static findal String USER_NAME = "xiaochen"; # Named identifier - 1),The name can only consist of letters, numbers, underscores $Symbol composition 2),Naming cannot begin with a number 3),Must not appear when naming Java keyword. 4),Chinese and Pinyin naming are absolutely not allowed. # proposal 1,Project name and package name are all lowercase 2,The first word of the method's name should begin with a lowercase letter, and the following words should begin with a capital letter 3,The hump naming method is used to name the variable name composed of multiple words 4,When naming constants, you need to follow the principle of all uppercase names 5,about Service and DAO class,be based on SOA(Service Oriented Architecture)The exposed services must be interfaces, and the internal implementation classes are used Impl The suffix is different from the interface. 6,If design patterns are used for modules, interfaces, classes and methods, specific patterns shall be reflected in naming Note: reflecting the design pattern in the name is helpful for readers to quickly understand the architecture design concept. Positive example: public class OrderFactory; Factory design mode public class LoginProxy; Agent design pattern public class ResourceObserver;Listener setup mode 7,When defining an array, the type is next to the brackets Positive example: int[] array = new int[10]; int array[] = new int[10]; // This is not recommended
5. Common basic data types and corresponding bytes
byte 1
short 2
int 4
long 8 0l
float 4 23.23F
double 8 23.23D
boolean 1 true false
char 2
# Basic data type byte 1B 0 -128~~~127 short 2B 0 -32768~~~32767 int 4B 0 -2147483648~~~2147483647 long 8B 0L float 4B 0.0F|f double 8B 0.0===>1.2D|d boolean 1B false char 2B '\u0000'
# Test questions - 1. 0.553423 What type is this ===>double Literal double 2. short What is the value range of? ~32768===32767 3. int a=32766 a=a+3 a=? 32769 4. short a=32766; //Once the data of a data type exceeds the range, it will change from the minimum negative value a++; ====> //32767 a++;//-32768 / / self increasing and self decreasing cannot be promoted automatically System.out.println(a); ====> -32768 short a=1; 1. a++; 2 2.a=a+1 Compilation error int 5. double a = 0.6454D; (correct) float f = 0.993434;(error) Must join F|f 6. short a=12; a++;(correct) a=a+3;(error) explain:Arithmetic operation will automatically type promotion, and self increasing and self decreasing operation will not automatically type promotion
6. Automatic type lifting?
# byte -> short -> int -> long -> float -> double - When one of the two operands is double When, the operation result is double No, double,appear float, The result is float No, float,appear long, The result is long No, long,appear int, The result is int except long Outside the type, The operation results of other integer types are int type
7. What is the difference between & & and &, |, and |?
# &&(and), | (or)! (non) = = = = > logical operation - And: Both sides are true The result is true - or: As long as one result on both sides is true The result is true - wrong: Either true or false # &, |, ~, ^ =============> bit operation int a = 1 0000 0000 0000 0000 0000 0000 0000 0001 int b = 2 0000 0000 0000 0000 0000 0000 0000 0010 1&2 = 0 1|2 = 3 ~2 = -3 1^2 = 3 - &(And): From the highest order operation, the result is 1 when both bits of the operator are 1, otherwise the result is 0 - |(or): As long as one of the two bits of the operator is 1, the result is 1, otherwise it is 0 - "~"(wrong): Indicates that the bit is 0 and the result is 1. If the bit is 1, the result is 0 - "^"(XOR): The result is 0 if they are the same, and 1 if they are different
8. Bubble sort selection sort
1 3 2 6 7 4 5 9 You have to memorize it # Bubble sorting idea: compare two adjacent elements and exchange positions for (int i = 0; i < a.length; i++) { for (int j = 0; j < a.length-1; j++) { if(a[j]>a[j+1]){ int tmp = a[j]; a[j] = a[j+1]; a[j+1] =tmp; } } } # Select Sorting idea: specify the subscript to compare with all numbers for (int i = 1; i < a.length; i++) { for (int j = i; j < a.length; j++) { if(a[i-1] > a[j]){ int tmp = a[i-1]; a[i-1] = a[j]; a[j] = tmp; } } }
9. The idea of array expansion?
# 1. Create a larger array to move int [] a = {12,23,23345}; int[] b = new int[a.lenght*2] # 2.java. util. Arrays. Copyof (original array name, new array length); # 3.System. Arraycopy (original array name, starting subscript, new array name, starting subscript, copy length);
10. Three characteristics of object-oriented
# 1. Encapsulation inheritance polymorphism - encapsulation: Improve class and system installability reflect: Property private provides public GET and SET method - inherit: The hierarchy and level of classes are established to facilitate extension: Subclass inherits parent class. Only one parent class is allowed to inherit a subclass - polymorphic: A parent class reference points to a child class object reflect: When the parent class reference calls the method in the parent class, the actual execution is the method after the child class overrides
11. What polymorphism
# Polymorphism: a parent class reference points to a child class object class Animal{ public void eat(){.. Animal eat} } class Dog extends Animal{ public void eat(){.. Dog eat} public void play(){....} } class Cat extends Animal{ public void eat(){.. Cat eat} public void runing(){...} } Animal a = new Dog(); a.eat(); //Dog eat Animal b = new Cat(); b.eat(); //cat eat Reference calls a method declared in a reference class Method after subclass override is performed at actual execution time
12. About construction method?
# Construction method effect: Used to create objects characteristic: 1.Constructor has no return value 2.The method name must be consistent with the class name 3.Manual invocation is not allowed,Called automatically when an object is created new Student(); 4.When no constructor is defined in the class, the system will assign a public parameterless constructor by default:Once the class shows the default constructor that defines the constructor, it does not exist
13.this and super keywords
# this: the current reference refers to me - this.Attribute name this.Method name: Used to call the properties or methods of the current object in a construction method or a common method. - this(): Can only be used in construction methods,It can only appear in the first line of the constructor to call the constructor in this class # super: the parent class object referred to by the parent class reference - super.attribute super.method : Call the properties or methods of the parent class in the construction method or common method of the subclass. - super() : Can only be used in construction methods,It can only appear in the first line of the constructor to call the constructor in the parent class be careful:this() super()Cannot appear at the same time
14. Create object during inheritance?
# Object creation process - Allocate space - Initialize property defaults - Call constructor # The creation process of objects during inheritance - Allocate space (Parent and child class spaces are allocated together) - Initialize parent class properties - Call the parent class constructor(Create parent object) - Initialize subclass properties - Call subclass constructor(Create subclass objects)
15. Inheritance relationship in Java
# Single class inheritance in java - A class can only have one parent class, but can implement multiple interfaces # Interface multi inheritance in java - An interface can inherit multiple interfaces # Why can interfaces inherit more - Because the interface defines abstract methods, and methods cannot be implemented in the interface. Therefore, if an interface inherits multiple interfaces, the structure of the interface will not become very complex. class extends Parent class implemplents interface,interface1 # Why can JAVA only inherit? - Because in C++A class in can inherit from multiple classes,But such a mechanism will make the structure of the class very complex,therefore JAVA take C++This mechanism is improved through the interface. JAVA Class multiple inheritance is not allowed in,Only single inheritance is allowed,However, in some cases, single inheritance can not express some logical relations in the real world,Therefore, it is proposed to realize multiple inheritance through interface.
16. Overload, override?
# Overload: method overload - The method name is the same, and the parameter list is different(Number of parameters,type,order) It has nothing to do with the return value # Override: Method override - The method name is the same, the parameter list is the same, the return value is the same, the access right decoration is the same or wider, and the exception thrown is the same or less
18. Function of instanceof keyword? transient keyword function?
# instanceof - Used to determine the usage of the actual type of reference: a instanceof Dog Return value: Consistent type true atypism false if(a instanceof Dog){ } Animal a = new Dog(); a intanceof Dog Animal b = new Cat(); # transient - Used to act on member variable properties,Represents that this property does not participate in object serialization
19. Three modifiers
# Static: static - class : Static class - attribute : Static attributes can be shared by all classes, and the class name can be used directly.Property names are used directly - method : Static method: Types can be used directly by whole class sharing.Method name direct call - Code block: Static code: Static is executed when the class is loaded, Execute only once # final: final - class: Final class: (die without descendants) This class cannot be inherited - attribute: Final Attributes: Once an attribute is assigned, it cannot be modified - method: Final method: Can be inherited,Cannot be overwritten try{}catch(Exception e){}finally{} //Always executed finallize() //Automatic invocation of garbage collection in jvm # abstract: abstract - class: abstract class: Can't pass new Create key objects - method: Abstract method: Only the declaration is not implemented be careful: 1.Abstract classes must contain abstract methods incorrect 2.Abstract class pair when abstract method class exists 3.Constructor in abstract class yes 4.In an abstract class because it cannot pass new create object,Therefore, there is no constructor in the class 5.What is the purpose of constructing methods in abstract classes? Used to create subclass objects when subclassing inheritance 6.String Can classes be inherited? Cannot be inherited final keyword Why final Keyword modification? All methods in the string class are thread safe,If inheritance is allowed,May destroy string Thread safety in #interview * 1.The existence of abstract method classes must be abstract classes yes * 2.Abstract classes must have abstract methods incorrect * 3.cover static Only external static members can be used within a modifier method yes * 4.Common methods can be used directly static Modification method yes * 5.static Modification methods can directly use external common methods incorrect * 6.jdk in String Classes can be inherited? No Why? String To be designed as final of String Immutable string String name="Xiao Chen" name+"xiaohei"; * 7.There is no constructor in the abstract class? existence,Used to create a parent class object when a child class inherits the parent class
20. Static code block, dynamic code block, execution sequence of construction method
public class Student extends People{ //Static code block: class loading is executed only once: the jvm uses this for the first time Class file for class loading classloader = = > jvm static{ System.out.println("1"); } //Object: initializing properties and calling construction methods //Dynamic code block: used to assign values to attributes in a class { System.out.println("2"); } //Construction method: automatically executed when creating objects public Student() { System.out.println("3"); } public static void main(String[] args) { Student student = new Student();//5 1 6 4 2 3 } } class People{ static { System.out.println("5"); } { System.out.println("6"); } public People() { System.out.println("4"); } }
21. The execution sequence of the following code
public class Test{ private String name; static{ System.out.println("1"); } { name = "Xiao Chen"; System.out.println("2"); } public Test() { System.out.println("3"); } public static void main(String[] args) { new Test(); } }
# Explanation: - 1.When jvm Class loading is performed the first time class information is read,static The code block is executed when the class is loaded,Therefore, output 1 is executed first - 2.{}Code block: Initialization code block,Initialization execution is performed for the property when the object is created,Therefore, before creating an object, you need to go through property initialization before creating an object, so output 2 - 3.Construction method: Called automatically when an object is created,Last output 3
22. What is class loading?
# Class loading - Class loading, in JVM When using a class for the first time, first classpath Find the corresponding.class File, read the.class Content in file(package/name/attribute/method...)To memory and save(Class object)The process of getting up. Class loading is performed only once
23. Briefly describe the difference between final finalized and finally?
# Final final - class: Modifiers cannot be inherited - attribute: Once the final attribute is assigned, it cannot be modified - method:The final method can be inherited and cannot be overridden - String Can classes be inherited? No, the reason is:cover final Keyword modified - String:Why is it designed to final? String You don't want subclasses,Reason why subclasses break method rules in parent classes:All methods in string classes are thread safe,If subclasses exist, the thread safety of methods in the parent class is violated # Method automatically executed by jvm during finalized garbage collection # Finally, the final general try catch is used in conjunction with try{}finally {} - finally Content in code: Always execute in any case
24. Differences between interfaces and abstract classes
# Interface interface - 1.Interface can be inherited before interface A extends B,C... 2.class implements A,B,... - 2.All variables defined in the interface are static constants, and all variables in the interface are static constants public static final String NAME = "xiaochen"; Modified static constant - 3.Methods in the interface expose abstract methods, which are only declared but not implemented (jdk8) (jdk8)in the future,The method in the interface can have a default implementation # abstract class - 1.Class contains constructor - 2.Abstract classes can only inherit from single - 3.Abstract classes have common methods - 4.Abstract methods exist in abstract classes. They are only declared but not implemented
25. = = "what's the difference with equals?
# == - Compare address memory address user1 == user2 # equals - Is the comparison content consistent user1.equals(user2); //Comparison object: euqals and hashCode methods must be overridden
26. What is the difference between StringBuilder and Stringbuffer?
# StringBuilder , StringBuffer - common ground: Are used for string splicing - difference: 1.StringBuilder Unsafe thread and high efficiency 2.StringBuffer Thread safety Low efficiency
27. Briefly describe the differences among ArrayList, LinkedList and Vector?
# ArrayList LinkedList Vector are all List interface implementation classes are collections - ArrayList: Underlying implementation: Array features:A contiguous memory space Quick query based on subscript(O(1)) Slow addition and deletion O(n) Thread unsafe - LinkedList: Underlying implementation: Linked list features:The pointer concept connects nodes together Fast addition and deletion(O(1)) Query slow(O(n)) - Vector: Underlying implementation: Array features: A contiguous memory space Quick query based on subscript(O(1)) Slow addition and deletion O(n) Thread safety
28. What is the difference between HashMap and HashTable?
# hashmap - Thread unsafe allowed key value At the same time null # hashtable - Thread safe not allowed key value At the same time null # Concurrent HashMap (concurrent hashmap) thread safety efficiency hashtable - Thread safety is much more efficient than hashtable Hashtable and ConcurrentHashMap What's the difference? They can be used in multithreaded environments, But when Hashtable When the size increases to a certain value, the performance will decline sharply, because the iteration needs to be locked for a long time. array+Linked list because ConcurrentHashMap Segmentation is introduced(segmentation),No matter how big it becomes, it just needs to be locked map The table is segmented and locked by 16 segments Other threads do not have to wait for the iteration to complete map. In short, during the iteration, ConcurrentHashMap Lock only map A part of, and Hashtable The entire is locked map.
29. How does HashSet realize non repetition of elements?
# Custom type - Need to override in class hashcode and equals method # Non custom type - Automatic coverage of internal bottom layer hashcode and equals
30. Briefly describe the classification of flow?
# direction - Input stream: Read data into jvm in - Output stream: take jvm Write out data in # function - Node flow : The stream that is actually responsible for transmitting data - Filter flow : Enhance node flow function (processing flow, decoration class) and rely on node flow # Company - Byte stream: Read all data - Character stream: Read text type data InputStream is = new FileInputStream("") OutputStream os = new FileOutputStream("") File copy code 1.Define input stream define output stream InputStream is = new FileInputStream(new File("d://aa.txt")); 900byte OutputStream os = new FileOutputStream(new File("e://bb.txt")); 2.File copy byte[] b = new byte[1024]; //1KB int len = 0; while(true){ len = is.read(b); if(len=-1)break; os.write(b,0,len); } //2.IOUtils.copy(is,os); // Introducing commons IO Toolkit 3.Release resources is.close(); os.close();
31. What is a thread?
# thread - process: A process can be divided into multiple threads. Threads are the basic unit of program scheduling - Multithreading: It can improve the running efficiency of the program new Thread(()=>{ }).start(); java Implementation of multithreading in: 1.inherit Thread class 2.realization runable Interface 3.Thread pool 4.Thread helper class FeatureTask Callable # Thread state 5 states (operating system perspective) - NEW New status - RUNNABLE start Enter after method Operational status - RUNNING obtain cpu Time slice running state - BLOCKED Thread.sleep(1000); IO ... Blocking state - DEAD Death state
32. What is thread safety?
# Thread safety - If your code is in a process where multiple threads are running at the same time, These threads may run this code at the same time. If the result of each run is the same as that of a single thread run, And the values of other variables are the same as expected, which is thread safe. A thread safe counter class When the same instance object is used by multiple threads, there will be no calculation error.
33. Thread safety case
- Class objects are unique and can be locked using class objects
Class object in jvm Just one, the only one
[external chain image transfer failed. The source station may have anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-gtCivnQq-1640409536714)(image/image.png)]
- Object lock
public class TestThread { private static int count = 0; private static Object o = new Object(); //synchronized object lock public static synchronized void main(String[] args) throws InterruptedException { synchronized(TestThread.class){ // getstatic +1 value putstatic t1 Thread t1 = new Thread(() -> { try { Thread.sleep(10000); } catch (InterruptedException e) { e.printStackTrace(); } synchronized (o){ for (int i = 0; i < 10000; i++) { count++; } } }); Thread t2 = new Thread(() -> { //t2 synchronized (o) { for (int i = 0; i < 10000; i++) { count--; } } }); t1.start(); t2.start(); t1.join();//Block main and wait for thread execution to complete t2.join();//Block main and wait for thread execution to complete System.out.println(count); } }
34. Implement multithreading
# 1. Inherit Thread class
Thread1 extends Thread { public void run(){ // Function code of thread } } //Use: a. create thread object Thread1 t1 = new Thread1(); //b. Start thread t1.start(); // Start the thread, and the JVM automatically calls the run method // t1.run(); //error. It is equivalent to calling a method in an object
# 2. Implement the Runable interface
Thread2 implements Runnable{ //Implement run method @Override public void run(){ //Code function of thread } } //use Thread thread = new Thread(new Thread2()); thread.start();
# 3. Implement Callable interface
Thread1 implements Callable { public void run(){ // Function code of thread } } //Use: a. create thread object Thread1 t1 = new Thread1(); //b. Start thread t1.start(); // Start the thread, and the JVM automatically calls the run method // t1.run(); //error. It is equivalent to calling a method in an object
# 4. Use FeaturTask - Get the result of the task executed by the thread
//Thread task object FutureTask<Integer> futureTask = new FutureTask<>(new Callable<Integer>() { @Override public Integer call() throws Exception { System.out.println(Thread.currentThread().getName()+ "-----------"); return 10; } }); new Thread(futureTask).start(); System.out.println(futureTask.get());
35. What's the difference between sleep() and wait()
# Common ground: both let the thread enter the waiting state, sleep finite waiting, wait indefinitely # Method in sleep() thread object - After the thread enters the wait,Object locks are not released,After waiting, the recovery thread continues to execute # Wait() method in object class - After the thread enters the wait,Release the lock of the current object,Only receive notify() perhaps notfiyall() Before you can resume operation,When resuming the run, re-enter the waiting queue to obtain the lock table flag
36. Three ways to obtain class objects through reflection
# Reflection get object - 1)By class name.class obtain Class object Class s = Student.class; - 2)Create objects, through objects . getClass() obtain Class object Strudet student = new Student(); Class s = student.getClass(); - 3)adopt Class.forName("Package name.Class name"); obtain Class object Class s = Class.forName("java.util.HashSet");
37. Single case design mode
//Only one object can be created
# Lazy style
class User{ private static User user; private User(){} public synchronized static User getInstance(){ //Thread safety problem: thread lock must be added if(user == null){ user = new User(); } return user; } }
# Evil Han style
class User{ private static final User user = new User(); private User(){} public static User getInstance(){ return user; } }
38. Single case model case
public class TestSingleton { public static void main(String[] args) { for (int i = 0; i < 100; i++) { new Thread(()->{ System.out.println(Dept.getInstance()); }).start(); } //Lazy: there is a thread safety problem with each use creation class Dept{ private static Dept dept; private Dept(){} //t1 bb t2 aa public synchronized static Dept getInstance(){ if(dept==null){ dept = new Dept(); } return dept; } } //Hungry Chinese style: there is no thread safety problem whether you use or do not directly create an instance class Emp{ private static final Emp emp = new Emp(); private Emp(){}//Construction method private //Returns an object public static Emp getInstance(){ return emp; } }
Java Web
39. What is the automatic generation strategy of primary key in oracle? How to create?
# Strategy of generating primary key in sequence sequence oracle 1. establish create sequence seq_user start with 1 increment by 2 maxvalue 100 minvalue 1; 2. use sequence Sequence name.nextval Use next sequence value insert into t_user values(seq_user.nextval Sequence name .currval //To get the value of the current sequence, the sequence must be executed once select Sequence name.currval from dual; Note: once the sequence is created, it can be used in any table. Once the value is generated, it cannot be obtained repeatedly. # Auto generated by mysql primary key policy_ Automatic generation of increment mysql create table t_user( id int(4) primary key auto_incrment, name ) insert into t_user('name') values('xiaochen')
40.select statement execution order
# select statement - Writing order: select * from Table name where condition group by grouping having Condition 2 order by sort - Execution sequence: from Table name where condition group by grouping having Condition 2 select order by 1.FROM Determine the table to query 2.WHERE Filter data by criteria 3.GROUP BY Group filtered data 4.HAVING Filter the grouped data again 5.SELECT Generate result set 6.ORDER BY Sort the result set
41. What is ACID?
ACID: atomic isolation consistency persistence
# Four characteristics of transaction - ACID,Database management system( DBMS)In the process of writing or updating data, to ensure transaction( transaction)To be correct and reliable, we must have four characteristics: atomicity( atomicity,Or indivisibility), consistency( consistency),Isolation( isolation,Also known as independence), persistence( durability). 1. Atomicity Atomic Transaction must be an atomic unit of work ( inseparable ) ;For its data modification, either all or none are executed. 2. uniformity Consistent The data before and after operation shall be consistent. 3. Isolation Insulation To ensure the data security of multi-user concurrent access, the modifications made by concurrent transactions must be isolated from those made by any other concurrent transactions. 4. persistence Duration The data of transaction operations is persisted to the database , The impact on the system is permanent.
42. Transaction isolation level
# Transaction isolation level - read_uncommit Read uncommitted: One client reads data that is not submitted by another client Dirty reading phenomenon client1 insert clinet2 - read_commit Read commit: One client can only read the data submitted by another client Avoid dirty reading oracle Default isolation level - repeat_read Repeatable reading: A client reads the same record multiple times in a transaction, and the results are consistent multiple times, so as to avoid the phenomenon of non repeatable reading mysql Default data isolation level zhangsan 1000 client1 clinet2 100 300 commit 100 - serialiable Serialized read(Stringency):A client reads the same table record multiple times in a transaction,The results of multiple reads are consistent Avoid phantom reading table 1 zhangsan client1 client2 1 insert commit be careful:The higher the isolation level, the lower the query efficiency
43.sql optimization scheme
# Optimization scheme - (1)Select the most efficient table name order user video category (2)Used when only one row of data is needed limit 1; (3)SELECT Avoid using in Clause'*' (4)use Where Clause substitution HAVING clause (5)Improved by internal functions SQL efficiency concat... max min ... (6)Avoid using calculations on index columns. //Calculating on an index column will invalidate the index (7)increase GROUP BY Statement efficiency, You can record unwanted in GROUP BY Filter it out before.
44. What is sql injection?, How to prevent sql injection
# sql injection ?name=xiaoor1=1 so-called SQL Injection is by putting SQL Insert command into Web The form submits or inputs the query string of the domain name or page request, and finally deceives the server to execute malicious SQL Command. Specifically, it takes advantage of existing applications and will (malicious) SQL The ability to inject commands into the background database engine, which can be executed in Web Input in form (malicious) SQL Statement to get a database on a website with security vulnerabilities, rather than executing it according to the designer's intention SQL sentence. [1] For example, many previous film and television websites leaked VIP Most member passwords are passed WEB When the query character of form submission is exposed, this kind of form is particularly vulnerable SQL Injection attack. mybatis Must use#{} avoid sql injection mybatis ${} When do you use this to get data? If you want to get data as sql Statement must be used for partial execution ${} existence sql injection order by ${} # sql injection case user=request("user") ===> ss or a=a passwd=request("passwd") ===> 1234 or 1=1 sql="select admin from adminbate where user= 'ss or a=a' and passwd='1234 or 1=1'" pstm sql="select admin from adminbate where user= ss or a=a and passwd= 1234 or 1=1" statement be careful:in use jdbc When using statement Object execution sql Will appear sql injection pstm: Does not exist in placeholder form sql injection
45. How to implement JDBC core steps?
# Import database driver jar - 1.Load the driver. Class.forName("oracle.jdbc.OracleDriver") - 2.Create database connection object Connection Connection conn=DriverManager.getConnection("","root","root"); jdbc:oracle:thin:@localhost:1521:xe jdbc:mysql://localhost:3306 / database name? characterEncoding=UTF-8 - 3.establish Statement object PrpepareStatement String sql="select * from user whnere username=?"; PrepareStatement pstm=Conn.prepareStatement(sql); Pstm.setString(1,name) - 4.implement Sql pstm.executeUpdate(); ResultSet rs = executeQuery(); - 5.Processing result set - 6.Release resources rs.close(); pstm.close(); conn.close();
46. What is JDBC
JDBC yes java One of 13 specifications (13 interfaces) application Java The underlying code for program access and operation of database ,SUN A set of specifications proposed by the company ( Interface ) . 1.1 Interface specification: a variety of database products, Sun The company just makes program development rules. Interface type: shield the difference of underlying code implementation (access to different databases) 1.2 Where is the implementation: Driver Jar( Provided by database manufacturer ) oracle ojdbc mysql mysql-connet sql JDBC = SUN A set of specifications proposed by the company ( Interface ) + drive Jar
47. Difference between statement and PreparedStatement
# Common ground: they are used to execute sql statements - 1.Statement yes PreparedStatement Parent interface - 2.Statement use sql Splicing mode sql existence sql injection - 3.PreparedStatement Placeholders can be used, which are precompiled and batch processing Statement efficient . prevent SQL injection
48. Transaction control
# A transaction is a series of operations performed as a single logical unit of work, either completely or not. Transaction processing ensures that data oriented resources are not permanently updated unless all operations within the transactional unit are successfully completed. Atomicity - 1.JDBC The default transaction in is a Sql A statement becomes a transaction, that is, a Sql The transaction will be submitted automatically after the statement is executed; The integrity of business functions cannot be guaranteed. Require programmers to manually control transactions: 1.1 Set manual control transactions: conn.setAutoCommit(false); Manual submission 1.2 Manually commit transactions: conn.commit(); 1.3 Manually rollback transactions: conn.rollback();
49. Three tier architecture MVC
# M:model layer Dao + service + entity JDBC # C:controller control layer servlet action 1 Data collection 2 Call service 3 Response results # 5: The view layer tries to display the data HTML / JSP Ajax HTML -- > interface MVC
50. Three ways to customize servlet s and their differences
# Method 1: the implements Servlet interface (not recommended) implements all abstract methods in the interface 1 , destroy() 2 , init() 3 , service() //service method 4 , getServletConfig() 5 , getServletInfo() # Method 2: extend genericservlet, override service method: not recommended, And http Protocol independent service(ServletRequest req, ServletResponse res) # Method 3: Extensions httpservlet in this abstract class, all methods are ordinary methods Just overwrite service Method accepts the request, processes the request, and responds to the result Client{ 1.Collect data 2.Call business object 3.Process jump }
51. Role of connection pool
# The establishment of database connection is a time-consuming, low-performance and high-cost operation. Frequent establishment and closure of database connection greatly affect the performance of the system. Database connection pool is to create a certain number of database connections in the connection pool during system initialization. When the program needs to access the database, it will no longer establish a new connection, but take out an established idle connection from the connection pool. After use, the program will return the connection to the connection pool for other requests, so as to realize the sharing of resources, The establishment and disconnection of connections are managed by the connection pool itself. # Database connection pool brings the following advantages to the operation of the system: Expensive database connection resources are reused; Reduce the time overhead of database connection establishment and release, The system response speed is improved; Unified database connection management avoids the leakage of connection resources. tomcat: jndi configuration file dhcp c3p0 druid(Ali connection pool)
52. What are the three scope objects in servlet? And their respective scope of action?
# Request: a valid request # session: valid request for one reply getSession() # application(servletContext): globally shared application level scope is unique request.getSession().getServletContext(); request.getServletContext();
53. There are two ways to submit forms
# Get mode get Method of data transmission: through the address bar, data is transmitted in plaintext, which is unsafe and the amount of data transmitted is small. # Post mode post Data transmission mode: data is transmitted through the request body, and data is transmitted through ciphertext, which is safe and has a large number of transmission. - How to solve javaweb Chinese garbled code in development? get mode: On server tomcat configuration file servet.xml URIEncoding="UTF-8" tomcat8 Default already post mode: servlet request/response.setCharacterEncoding("") struts2 default springmvc springboot Auto configuration - What should I pay attention to when uploading files? 1.Form submission method must be post 2.form enctype="multipart/form-data"
- post to solve the problem of Chinese garbled code
class MyFilter implements Filter { @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { servletRequest.setCharacterEncoding("UTF-8"); servletResponse.setCharacterEncoding("UTF-8"); filterChain.doFilter(servletRequest,servletResponse); } }
54. Nine implicit objects of JSP?
- 1 request Scope related operations. request.getContextPath();// Used to dynamically obtain the application name (project name) `<form method="post/get" action="<%= request.getContextPath()%>/url-pattern"> - 2 response( Not really ) response.getWriter();Returned is PrintWriter,This is a printout stream. response.sendRedirect(); response.setContentType("text/html;charset=UTF-8"); - 3 session Scope related operations. - 4 application(ServletContext) - 5 (out) Equivalent to <%= %> - 6 (cofig) ServletConfig get Servlet Initialization parameter information in web.xml - 7 (exception) Exceptions in the previous interface can only be generated in the isErrorPage Used in the page. - 8 page page Only the current page is similar to this . - 9 pageContext The page minimum scope is only valid for the current page ${pageContext.request.contextPath} ====> Get project path jsp
55. Is servlet running a singleton?
# Servlet: all requests of a single instance share the same servlet object - be careful: Singleton threads are not safe to use as much as possible servlet Avoid using member variables to manipulate data as much as possible # Struts 2: multiple instances request a new instance object - stay struts2 A large number of member variables are used to collect data and transfer data for multiple instances to avoid multithreading safety problems # Spring MVC: Singleton - stay springmvc Collect parameter using controller method parameter list @RestController @Scope("singleton|prototype") xxxController
56. Knowledge points of struts 2 framework interview
# 1) A brief introduction to struts 2 Framework Struts2 Is a typical mvc Frame, throughout mvc As a controller in the framework, struts2 Replace native servlet Technology is to the original servlet Reasonable encapsulation of code. # 2) The class name of the front controller of struts 2 is important StrutsPrepareAndExecuteFilter /* # 3) Execution process of struts 2 Background received request,after struts2 Front controller for strutsPrepareAndExecuteFilter Parse request path, go to struts2 The corresponding is not found in the configuration file of namespace and action of name Property, and then find the corresponding class and method,Execute the relevant code, and then complete the process jump. # 4) How does struts 2 receive parameters a.To collect parameters using member variables, you need to provide the corresponding get/set Method scattered type object property array type collection # 5) How to obtain request and response in the method of controller in struts 2 ServletActionContext.getRequest().getSession(); servletActionContext.getResponse() request.getSession().getServletContext(); # 6) Jump mode of struts 2 servlet Medium jump forward : Request forwarding features: The address bar of a request does not change, and the server jumps internally tomcat redirect: Request redirection features: Multiple requests for address bar change client jump chrome Action--->jsp: forward:default(dispatcher) <result name="success" >/index.jsp</result> redirect: type="redirect" <result name="success" >/index.jsp</result> Action--->Action forward: type="chain" redirect: type="redirectAction" <result name="ok" type="redirectAction|chain"> <param name="namespace">/xx</param> <param name="actionName">xxx</param> </result> # 7) Interceptor in struts 2 is similar to Java Web filter effect: Put the same business code executed in multiple controllers into the interceptor to perform reduction action Code redundancy in characteristic: 1.The interceptor can only intercept controller related requests jsp Static resources 2.Interceptors can interrupt user requested tracks 3.Request arrives via interceptor,The response will also pass through the interceptor MyInter implemenets Interceptor be careful: intercept Action Related requests cannot be intercepted jsp custom interceptor A1 A2 Custom interceptor stack stack Default interceptor stack extends="struts-default" Custom interceptor stack my-default-stack <interceptors> <interceptor name="myInter" class="com.baizhi.action.MyInter"></interceptor> <interceptor name="myInter1" class="com.baizhi.action.MyInter1"></interceptor> <!--Custom interceptor stack--> <interceptor-stack name="aa"> <interceptor-ref name="myInter"> <interceptor-ref name="myInter1"> </intercrptor-stack> <!--System interceptor stack--> <interceptor-stack name="aa"> <interceptor-ref name="defaultStack(System interceptor)"/> <interceptor-ref name="myInter"/> <interceptor-ref name="myInter1"/> </interceptor-stack> </interceptors> <!--Default interceptor--> <default-interceptor-ref name="aa"/> # 8) File upload and download in struts 2 Precautions for file upload: 1).Import jar package commons -io commonsfileupload 2).Form submission method must be post 3).form enctype Property must be multipart/form-data form method="post" enctype="multipart/form-data" input type="file" name="aaaa" 4).stay Action Member variables defined in private File aaaa; get set private String aaaaFileName get set original filename //1. Obtain the absolute path according to the relative path String realPath = ServletActionContext.getServletContext().getRealPath("/back/photo"); //Find the folder according to the file path File file = new File(realPath); //Determine whether the folder exists if(!file.exists()){ file.mkdir(); } //Get file name frequency timestamp String newName= new Date().getTime()+"."+FileNameUtils.getExtension(aaaaFileName); //File upload FileUtils.copyFile(aaa, new File(file,newName));