Wrap-up
Array 7-day entry variable Eight basic types of function branch arrays
Object-oriented programming 10 days Object-oriented encapsulation Inheritance polymorphic method override method overload this super uses three major modifications of the static final abstrace interface in the parent-child object creation process
JAVASE API Common API Weekly String IO Thread Exception Collection Reflection
java language features?
# Three main features: written examination simple: Automatic Grammar Check Automatic Garbage Collection Mechanism Object Oriented Everything Is Object 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 Strongly typed languages, automatic grammar checking, java Support for automatic garbage collection c++/c Handle your own garbage collection - Object-oriented: stay java Everything in the world is an object
How does the java language work?
# Running Mechanism Written Test - Compile then interpret the run .java---> .class file operating system jvm Virtual Machine Version window linux macos oralce hotspot g9 IBM virtual machine ...
What is JVM?
# JVM: (Java Virtual Machine) Java virtual machine JVM ====> ClassLoader class loader =====>.Class - 1.JVM implement.class(Subsection Code File)Execution Engine - 2.JVM Shield the important manifestation of the underlying operating system across platforms
Naming Specification for Java?
Alphanumeric Underline$Don't start with a number and be case sensitive Note: It's best not to use keyword special characters
Package name: all lowercase
Class name: First letter uppercase Multiple words First letter uppercase
Method Name: The first word of the hump nomenclature is lowercase and the first word is capitalized
Variable name: hump nomenclature
Constant name: All uppercase String TIME_OUT =
# Note: Package names are all lowercase, class names are all capitalized (multiple words are capitalized), method/variable hump naming (the first word is lowercase, the next word is capitalized), constant capitalization is used to separate multiple words with _ com.baizhi.dao UserServiceImpl getMethod() static findal String USER_NAME = "xiaochen"; # Named Identifier - 1),Names can only be letters, numbers, underscores, $Symbol Composition 2),Naming cannot begin with a number 3),Never appear when naming Java Keyword. 4),Chinese and Pinyin naming is absolutely not allowed in naming. # proposal 1,Project name, package name in lowercase 2,The first word of the method's name should start with a lowercase letter, followed by a capital letter 3,Naming variables with multiple words using the hump nomenclature 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)Idea, exposed services must be interfaces, internal implementation classes Impl The suffix differs from the interface. 6,If the module, interface, class, method uses the design pattern, the specific pattern should be reflected in the naming Description: By embodying the design pattern in the name, readers can quickly understand the architecture design concept. Example: public class OrderFactory; Plant Design Mode public class LoginProxy; Agent Design Mode public class ResourceObserver;Monitor Setup Mode 7,When defining an array, the type is next to the bracket Example: int[] array = new int[10]; int array[] = new int[10]; // This is not recommended
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 types 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 range of values for? ~32768===32767 3. int a=32766 a=a+3 a=? 32769 4. short a=32766; //A data type changes from the minimum negative number once the data exceeds the range a++; ====> //32767 a++;//-32768 //self-increasing and self-decreasing cannot automatically type-promote System.out.println(a); ====> -32768 short a=1; 1. a++; 2 2.a=a+1 Compile 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-elevate self-increasing and self-decreasing operations will not automatically type-elevate
Automatic type promotion?
# byte -> short -> int -> long -> float -> double - When one of the two operands is double The result of the operation 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 of type, All other integer type operations result in int type
What's the difference between &&and &, || and |?
# &&& (and), || (or),!(not) ====> logical operation - and: Both sides are true The result is true - or: Only one result on either side is true The result is true - wrong: Not True or False # Ampersand, |, ~, ^=============> bitwise 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 bit operation, both bits of the operator are 1, the result is 1, otherwise the result is 0 - |(or): If only one of the two bits of an operator is 1, the result is 1, otherwise it is 0 - "~"(wrong): Represents a bit of 0, the result is 1, and if the bit is 1, the result is 0 - "^"(XOR): Represents two bits, the same result is 0, different result is 1
Bubble Sort Selection Sort
1 3 2 6 7 4 5 9 Must recite it down # Bubble sorting idea: comparing two adjacent elements and exchanging locations 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 ideas: specify subscripts 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; } } }
The idea of array expansion?
# 1. Create a larger array to move int[] a = {12,23,23,345};Int[] B = new int[a.lenght*2] # 2.java.util.Arrays.copyOf (original array name, new array length); # 3.System.arraycopy (original array name, start subscript, new array name, start subscript, copy length);
Three Object-Oriented Features
# 1. Encapsulate Inheritance Polymorphism - encapsulation: Improving class and system installability Reflect: Property Private Provides Public GET and SET Method - inherit: Establish the hierarchy and hierarchy of classes for easy expansion: Subclass inherits parent class Single inheritance of a subclass Only one parent class is allowed - polymorphic: Parent Reference Points to Subclass Object Reflect: A parent reference invokes a method in a parent class that actually executes after the child class overrides the method
What Polymorphism
# Polymorphism: parent reference points to 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 declared methods in reference classes Method after subclass override is performed at actual execution time
About construction methods?
# Construction method Effect: Used to create objects Characteristic: 1.Construction method does not return a value 2.Method name must match class name 3.Manual calls are not allowed,Called automatically when an object is created new Student(); 4.When no constructor is defined in the class, a common, parameterless constructor note is assigned by default:Once a default construction method for defining a construction method is displayed in the class, it does not exist
this, super keywords
# this: The current reference refers to: Me - this.Property Name this.Method Name: Used to invoke properties or methods of the current object in a construction or common method - this(): Can only be used in construction methods,Can only appear on the first line of a construction method to call a construction method in this class # super: parent reference refers to the parent object - super.attribute super.Method : Used in the construction or common method of a subclass to invoke the properties or methods of the parent class - super() : Can only be used in construction methods,Only the first line of a construction method can appear on behalf of the calling parent Be careful:this() super()Can't appear at the same time
Creation of objects when inheriting?
# Object creation process - Allocate space - Initialization property defaults - Call Construction Method # Object Creation Process on Inheritance - Allocate space (Parent-Child Space Allocated Together) - Initialize parent class properties - Call parent class construction method(Create parent object) - Initialize subclass properties - Call subclass construction method(Create Subclass Object)
Inheritance relationship in java
# Class single inheritance in java - A class can only have one parent but can implement multiple interfaces # Interface multiple inheritance in java - An interface can inherit multiple interfaces # Why interfaces can inherit more - Because interface definitions are abstract methods and methods cannot be implemented in an interface, an interface inherits multiple interfaces and does not complicate the structure of the interface. class extends Parent Class implemplents interface,interface1 # Why can JAVA only inherit? - Because C++A class in can inherit from more than one class,However, such a mechanism can complicate the class structure,therefore JAVA take C++This mechanism is improved through interfaces. JAVA Multiple inheritance of classes is not allowed,Only single inheritance,In some cases, however, a single inheritance does not convey some logical relationship in the real world.,Therefore, it is proposed to implement multiple inheritance through interfaces.
Overload, override?
# Overload: Method overload - Method Name Same Parameter List Different(Number of parameters,type,order) Not related to return value # Override: Method override method override - Method Name Same Parameter List Same Return Value Same Access Permission Modify Same or Wider Throw Exceptions Same or Less
What is the effect of the instanceof keyword?transient keyword effect?
# instanceof - Used to determine what the actual type of reference is used for: a instanceof Dog Return value: Type Consistency 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 when the object is serialized
Three Modifiers
# static:Static - class : Static Class - attribute : Static attributes can be shared across classes using class names directly.Property names are used directly - Method : Static method: Full class sharing can use types directly.Method name direct call - code block: Static code: Statically executed when class is loaded, Execute only once # Final:final - class: Final Class: (Die without descendants) This class cannot be inherited - attribute: Final Properties: Property cannot be modified once it is assigned - Method: Final method: Can be inherited,Cannot be overwritten try{}catch(Exception e){}finally{} //Always executed finallize() //Auto-call in jvm garbage collection # Abstract:abstract - class: abstract class: Cannot Pass new Key Creation Objects - Method: Abstract method: Only declarations are not implemented Be careful: 1.An abstract class must contain an abstract method Incorrect 2.Abstract method class pairs exist at some point 3.There are construction methods in abstract classes Yes 4.In an abstract class because it cannot pass new create object,So no construction method in the class is wrong 5.What constructors in abstract classes do? Used to create subclass objects for subclass inheritance 6.String Can a class be inherited? Cannot be inherited final Keyword Why use final Keyword Modifiers? All methods in a string class are thread-safe,If inheritance is allowed,Possible damage string Thread Security in Medium #Interview * 1.An abstract method class must be an abstract class Yes * 2.There must be abstract methods in abstract classes Incorrect * 3.cover static Only external static members can be used inside modifier methods Yes * 4.Common methods can be used directly static Modification Method Yes * 5.static Modifiers can use external general methods directly Incorrect * 6.jdk in String Classes can be inherited? cannot Why String To be designed as final Of String Invariant String String name="Xiao Chen" name+"xiaohei"; * 7.No construction method in abstract class? existence,Create parent object when child inherits parent using
Static code block, dynamic code block, execution order of construction methods
public class Student extends People{ //Static code block: class loading is performed only once when the class is loaded: jvm first uses this.class file for class loading classLoader ==> jvm static{ System.out.println("1"); } //Object: Initialize property call construction method //Dynamic Code Block: Role: Used to assign values to attributes in a class { System.out.println("2"); } //Construction method: Automatically executes when an object is created 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"); } }
Execution order 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 occurs when class information is first read,static Code blocks are executed when classes are loaded,So execute output 1 first - 2.{}code block: Initialization Code Block,Initialize execution for properties when creating objects,So before you create an object, you need to go through property initialization before you create it. So output 2 - 3.Construction method: Called automatically when an object is created,Last Output 3
What is class loading?
# Class Loading - Class loading, in JVM The first time you use a class, start with classpath Find the corresponding.class File, read the.class Contents in the file(package/name/attribute/Method...)To memory and save(Class object)Class loading occurs only once
Briefly describe the difference between final finalized final?
# final - class: Decorations cannot be inherited - attribute: The final attribute cannot be modified once it is assigned - Method:The final method can be inherited and cannot be overridden - String Can a class be inherited? No reason:cover final Keyword-modified - String:Why is it designed to final? String Do not want subclasses,Subclass breaks method rules in parent:All methods in a string class are thread safe,If a subclass exists, destroying method thread security in the parent # Method of jvm auto-execution during finalized garbage collection # Finally finally use try{}finally {} with the final general try catch - finally Content in Code: Always execute in any case
Interface and abstract class differences
# Interface interface - 1.Multiple inheritance before interface interface A extends B,C... 2.class implements A,B,... - 2.Variables defined in an interface are static constants Variables in an interface are all defined by public static final String NAME = "xiaochen"; Modified Static Constants - 3.Methods in interfaces expose abstract methods only declarations are not implemented (jdk8) (jdk8)In the future,Default implementations can exist for methods in interfaces # abstract class - 1.Class contains construction methods - 2.Abstract classes can only inherit singly - 3.There are common methods for abstract classes - 4.There are abstract methods in abstract classes that only declarations do not implement
What is the difference between'=='and equals?
# == - Compare Address Memory Addresses user1 == user2 # equals - Compare content consistency user1.equals(user2); //Comparison object: must override euqals and hashCode methods
What is the difference between StringBuilder and Stringbuffer?
# StringBuilder , StringBuffer - Common ground: They are used for string stitching - Difference: 1.StringBuilder Thread insecurity and efficiency 2.StringBuffer Thread Security Inefficient
Briefly describe the differences between ArrayList, LinkedList and Vector?
# ArrayList LinkedList Vector s are List interface implementation classes are collections - ArrayList: Bottom level implementation: Array characteristics:A continuous memory space Quick query based on Subscripts(O(1)) Increase or decrease O(n) Thread insecurity - LinkedList: Bottom level implementation: Chain List Features:Pointer concept connects nodes together Increase or delete faster(O(1)) Query Slow(O(n)) - Vector: Bottom level implementation: Array characteristics: A continuous memory space Quick query based on Subscripts(O(1)) Increase or decrease O(n) Thread Security
What is the difference between HashMap and HashTable?
# hashmap - Thread insecure permission key value Simultaneously for null # hashtable - Thread Security Not Allowed key value Simultaneously for null # Concurrent HashMap (concurrent hashmap) thread security efficiency hashtable - Thread security is much more efficient than hashtable Hashtable and ConcurrentHashMap What's the difference? They can be used in a multithreaded environment. But when Hashtable When the size increases to a certain point, performance decreases dramatically, because iterations require a long time to lock in. Arrays+linked list because ConcurrentHashMap Split introduced(segmentation),No matter how big it gets, it just needs to be locked map A section of a table that is segmented and locked for 16 segments Other threads do not need to wait until the iteration is complete to access it map. In short, during an iteration, ConcurrentHashMap Lock only map And Hashtable Will lock the whole map.
How does HashSet implement element non-repetition?
# Custom Type - Need to override in class hashcode and equals Method # Non-Custom Type - Inner Bottom Auto Cover hashcode and equals
Briefly describe the classification of streams?
# direction - Input stream: Read data in jvm in - output stream: take jvm Write out data in # function - Node Flow : Stream actually responsible for transferring data - Filter flow : Enhance node flow capabilities (processing flow, decoration class), depend on node flow # Company - Byte Stream: Read all data - Character Stream: Read data of type text InputStream is = new FileInputStream("") OutputStream os = new FileOutputStream("") File Copy Code 1.Define Input Flow Define Output Flow 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 the commons-io Toolkit 3.Release Resources is.close(); os.close();
What is a thread?
# thread - process: Threads that can be divided into threads in a process are the basic unit of program scheduling - Multithreaded: Can improve program efficiency new Thread(()=>{ }).start(); java Implement 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 angle) - NEW New Status - RUNNABLE start Enter after method Runnable state - RUNNING Obtain cpu Time slice running state - BLOCKED Thread.sleep(1000); IO ... Blocking state - DEAD Death status
What is thread security?
# Thread Security - 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, And other variables have the same value as expected, which is thread-safe. A thread-safe counter class There will be no calculation errors for the same instance object when it is used by multiple threads.
Thread Security Cases
- Class objects are unique and can be locked using class objects
Class object in jvm Just one, only one
- Object Lock
public class TestThread { private static int count = 0; private static Object o = new Object(); //synchronized (object) 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();//Blocking main waiting for thread execution to complete t2.join();//Blocking main waiting for thread execution to complete System.out.println(count); } }
Implement multithreading
# 1. Inherit the Thread class
Thread1 extends Thread { public void run(){ // Functional code for threads } } //Use: a.Create Thread Object Thread1 t1 = new Thread1(); //b.Start Thread t1.start(); // Start thread, JVM automatically calls run method // t1.run(); //error.Equivalent to calling a method in an object
# 2. Implement Runable Interface
Thread2 implements Runnable{ //Implementing run method @Override public void run(){ //Code functions of threads } } //Use Thread thread = new Thread(new Thread2()); thread.start();
# 3. Implement Callable Interface
Thread1 implements Callable { public void run(){ // Functional code for threads } } //Use: a.Create Thread Object Thread1 t1 = new Thread1(); //b.Start Thread t1.start(); // Start thread, JVM automatically calls run method // t1.run(); //error.Equivalent to calling a method in an object
# 4. Use FeaturTask - Get Thread Execution Task Results
//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());
What is the difference between sleep() and wait()
# What they all have in common is that they allow a thread to enter a waiting state. sleep waits for a finite period of time. wait indefinitely # Method in sleep() thread object - After a thread enters a wait,Object locks will not be released,Restore thread to resume execution after waiting to end # Method in wait() Object class - After a thread enters a wait,Release current object lock,Only receive notify() perhaps notfiyall() Running will not resume until,Re-enter the waiting queue to get the lock table flag when recovery runs
Three Ways to Obtain Class Objects by Reflection
# Reflect Get Object - 1)By class name.class Obtain Class object Class s = Student.class; - 2)Create objects by object . 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");
Singleton Design Mode
//Only one object can be created
# Lazy-man style
class User{ private static User user; private User(){} public synchronized static User getInstance(){ //Thread security issues: Thread locks must be added if(user == null){ user = new User(); } return user; } }
# Bad Han Style
class User{ private static final User user = new User(); private User(){} public static User getInstance(){ return user; } }
Single Case Pattern 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: Thread security issues created per use 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 Han: Thread security issues do not exist whether you are using or not directly creating an instance class Emp{ private static final Emp emp = new Emp(); private Emp(){}//Construction method private //Return an object public static Emp getInstance(){ return emp; } }
Java Web
oracle jdbc html css servlet jsp struts2 mybatis maven js jquery
What is the auto-generation strategy for primary keys in Oracle and how can it be created?
# Primary Key Generation Strategy in oracle sequence 1. Establish create sequence seq_user start with 1 increment by 2 maxvalue 100 minvalue 1; 2. Use sequence Sequence Name.nextval Use the next sequence value insert into t_user values(seq_user.nextval Sequence Name .currval //Getting the numeric precondition of the current sequence must be executed once select Sequence Name.currval from dual; Note: Once a sequence is created, it can be used in any table, and once a value is generated, it cannot be retrieved repeatedly. # mysql primary key policy auto_increment mysql auto-generation create table t_user( id int(4) primary key auto_incrment, name ) insert into t_user('name') values('xiaochen')
select statement execution order
# select statement - Writing Order: select * from Table Name where condition group by Grouping having Condition 2 order by sort - Execution order: from Table Name where condition group by Grouping having Condition 2 select order by 1.FROM Determine the table for the query 2.WHERE Conditional filtering of data 3.GROUP BY Grouping filtered data 4.HAVING Filter the grouped data again 5.SELECT Generate Result Set 6.ORDER BY Sort the result set
What is ACID?
ACID: Atomic Isolation Consistency Persistence
# Transaction Four Features - ACID,Refers to the database management system ( DBMS)In the process of writing or updating data, to ensure transactions ( transaction)It is correct and reliable and must possess four characteristics: Atomicity ( atomicity,Or indivisibility), consistency ( consistency),Isolation ( isolation,Also known as independence), persistence ( durability). 1. Atomicity Atomic Transactions must be atomic units of work ( Inseparable ) ;Modifications to their data are either all or none. 2. Uniformity Consistent Data before operation and data after operation are consistent. 3. Isolation Insulation Ensure data security for concurrent multiuser access, and changes made by concurrent transactions must be isolated from those made by any other concurrent transactions. 4. Persistence Duration Data for transactional operations is persisted to the database , The impact on the system is permanent.
Transaction isolation level
# Transaction isolation level - read_uncommit Read uncommitted: One client read data that another client did not submit Dirty Reading client1 insert clinet2 - read_commit Read Submit: One client can only read data submitted by another client Avoid Dirty Reading oracle Default isolation level - repeat_read Repeatable Read: A client reads the same record multiple times in a single transaction and consistently reads the results multiple times to avoid non-repeatable reads mysql Default isolation level of data zhangsan 1000 client1 clinet2 100 300 commit 100 - serialiable Serialized Read(Seriousness):A client reads the same table record multiple times in a transaction,Consistent results read multiple times Avoid phantom reading table 1 zhangsan client1 client2 1 insert commit Be careful:The higher the isolation level, the lower the query efficiency
sql optimization scheme
# Optimized scheme - (1)Select the most efficient table order user video category (2)Use when only one row of data is needed limit 1; (3)SELECT Avoid using in Clauses'*' (4)use Where Clause substitution HAVING clause (5)Enhanced by internal functions SQL efficiency concat... max min ... (6)Avoid using calculations on indexed columns. //Calculating in an indexed column will invalidate the index (7)increase GROUP BY Efficiency of statements, By recording unnecessary records in GROUP BY Filter before.
What is sql injection? How to prevent sql injection
# sql inject ?name=xiaoor1=1 So-called SQL Injection is done by placing SQL Insert command into Web Form submission or entry of a query string for a domain name or page request, which ultimately deceives the server for malicious execution SQL Command. Specifically, it takes advantage of existing applications and will (maliciously) SQL The ability to inject commands into the background database engine for execution by Web Input in Form (Malicious) SQL Statement yields a database on a Web site with a security vulnerability, not executed as intended by the designer SQL Sentence. [1] For example, many previous movie and television websites leaked VIP Membership passwords are mostly passed WEB Form submission query character burst, such forms are particularly vulnerable SQL Injection Attack. mybatis Must be used#{} Avoid sql injection mybatis ${} When to use this to get data? If you will get data as sql A part of a statement must be executed using ${} 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 Use when statement Object Execution sql Will appear sql injection pstm: No through placeholder form sql injection
How are the core JDBC steps implemented?
# Import Database Driven jar - 1.Load 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/library 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();
What is jdbc
JDBC yes java One of 13 specifications (13 interfaces) application Java The underlying code for program access and operation of the database ,SUN A set of specifications proposed by the company ( Interface ) . 1.1 Interface specification: a variety of database products, Sun The company is just making rules for program development. Interface type: Blocking differences in underlying code implementation (accessing different databases) 1.2 Where to Implement: Driver Jar( Provided by the database vendor ) oracle ojdbc mysql mysql-connet sql JDBC = SUN A set of specifications proposed by the company ( Interface ) + drive Jar
Differences between Statement and PreredStatement
# Common: they are used to execute sql statements - 1.Statement yes PreparedStatement Parent Interface - 2.Statement Use sql Stitching method execution sql existence sql injection - 3.PreparedStatement Placeholders are available, pre-compiled, batch ratio Statement Efficient . Prevent SQL injection
Transaction Control
# Transactions are a series of operations performed as a single logical unit of work, either completely or not. Transactions ensure that data-oriented resources are not permanently updated unless all operations within a transactional unit are successfully completed. - 1.JDBC The default transaction in is one Sql A statement has its own transaction, that is, one Sql Transactions are automatically committed when the statement is executed; the integrity of business functions cannot be guaranteed. Transactions need to be controlled manually by the programmer: 1.1 Set up manual transaction control: conn.setAutoCommit(false); Manual Submission 1.2 Manually commit the transaction: conn.commit(); 1.3 Manually roll back the transaction: conn.rollback();
Three-tier architecture MVC
# M:model model layer dao+service+entity JDBC # C:controller control layer servlet action 1.Collect data 2.Call business 3.Response results # V:view attempts to layers display data html/Jsp Ajax HTML --->interfaces MVC
Three ways to customize a servlet, and the differences
# Mode 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() # Mode 2: extends GenericServlet, overrides service method: not recommended, and http Agreement is not relevant service(ServletRequest req, ServletResponse res) # Mode three: extends Httpservlet In this abstract class, all methods are common Just overwrite service Method accepts requests, processes requests, and responds to results Client{ 1.Collect data 2.Call Business Object 3.Process Jump }
Role of connection pools
# 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 the process of system initialization to create a certain number of database connections in the connection pool, when programs need to access the database, no longer establish a new connection, but take it from the connection poolAn established idle connection is returned to the connection pool for use by other requests. The resource sharing is achieved. The connection pool itself manages the establishment and disconnection of connections. # Database connection pooling provides the following benefits to running the system: Expensive database connection resources are reused; time spent on database connection establishment and release is reduced. It improves the response speed of the system, unifies the database connection management, and avoids the leakage of connection resources. tomcat: jndi configuration file dhcp c3p0 druid(Ali Connection Pool)
What are the three scope objects in a Servlet and their respective scopes?
# Request:A valid request is requested once # session: valid request.getSession() for one call # application(servletContext): The global shared application-level scope is unique request.getSession().getServletContext(); request.getServletContext();
There are two ways to submit a form
# Get Method get How to transfer data: Pass it through the address bar, pass it in clear text, is not secure, and transfer a small amount of data. # Post mode post How to transfer data: Pass data through the request body, Pass data in cipher, Secure, and Pass a large number. - How to Solve javaweb Chinese Scrambling 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 Automatic Configuration - What do you need to pay attention to when uploading files? 1.Form submission must be post 2.form enctype="multipart/form-data"
- post Solves Chinese Scrambling
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); } }
9 implied objects of jsp?
- 1 request Scope-related operations. request.getContextPath();// Used to dynamically get the application name (project name) `<form method="post/get" action="<%= request.getContextPath()%>/url-pattern"> - 2 response( Not very useful ) response.getWriter();Return 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 from the previous interface can only occur in isErrorPage Used in pages of. - 8 page page Just the current page looks like this this . - 9 pageContext Page minimum scope is only valid on the current page ${pageContext.request.contextPath} ====> Get Project Path jsp
Is the servlet run as a singleton?
# Servlet: Single case All requests share the same servlet object - Be careful: Single threads are unsafe to use whenever possible servlet Avoid using member variables to manipulate data whenever possible # struts2: Multiple instances one request for a new instance object - stay struts2 Use a large number of member variables to collect data for transfer Multiple examples to avoid multithreaded thread security issues # springmvc: Single case - stay springmvc Collect Parameters Using Controller Method Parameter List @RestController @Scope("singleton|prototype") xxxController
Struts2 Framework Review
# 1) Brief description of struts2 framework Struts2 Is a typical mvc Framework, throughout mvc Acting as a controller in the framework, struts2 Replace native servlet Technology is native servlet Proper encapsulation of code. # 2) Class name focus of the pre-controller of Struts 2 StrutsPrepareAndExecuteFilter /* # 3) Execution process of Struts2 Background Receive request,after struts2 Front Controller strutsPrepareAndExecuteFilter Resolve the request path to struts2 Find the corresponding in the configuration file namespace and action Of name Property, and then find the corresponding class and method,Execute the code and complete the process jump. # 4) How Struts2 receives parameters a.To collect parameters using member variables, you need to provide the appropriate get/set Method Scattered Type Object Attribute Array Type Collection # 5) How to get request and response from the controller in struts2 ServletActionContext.getRequest().getSession(); servletActionContext.getResponse() request.getSession().getServletContext(); # 6) The Jump Mode of Struts2 servlet Mid Jump forward : Request Forwarding Features: One request address bar unchanged server internal jump tomcat redirect: Request redirection feature: 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 Struts2 is similar to javaweb filter Effect: Place the same business code execution in multiple controllers into interceptors to reduce execution action Code redundancy in Characteristic: 1.Interceptors can only intercept Controller-related requests jsp Static Resources 2.Interceptors can interrupt user request trajectories 3.Request arrival 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 Struts2 Notes on file upload: 1).Import jar package commons -io commonsfileupload 2).Form submission 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. Obtaining absolute paths from relative paths String realPath = ServletActionContext.getServletContext().getRealPath("/back/photo"); //Find folders by file path File file = new File(realPath); //Determine if a 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));