@[TOC]

Javaweb internal review material

Question type and score:

1. Multiple choice questions (20 points, 1 point/question, single choice/multiple choice);

2. Short answer questions (30 points, choose 6 from 7, 5 points per question, only the first 6 questions will be judged if you do all of them)

3. Fill in the blanks (50 marks, 2 marks/blank)

30 percent web front-end 30 percent Javaweb backend 40 percent

The examination site

1.java:

Internal classes should not be tested on abstract class interfaces. They should definitely be tested on/call

2.web

CSS master four style sheets master four selectors CSS does not require much JS positioning object master

3.Javaweb

Background Servlet principle Class architecture method life cycle Session must master redirection and forward JSP principle Comment declaration expression code section instruction JSP action JSP action Publag does not have to master Java bean writing rules MVC patterns EL and JSTL and Ajax do not have to look at JDBC steps to master prepareSTatment and Statment differences

First, Java knowledge

1. Object-oriented thinking

1.1 Overview of object-oriented thinking

An overview of the

Java language is a kind of object-oriented programming language, and object-oriented thought is a kind of programming thought, we under the guidance of object-oriented thought, using Java language to design and develop computer programs. The object here generally refers to all things in reality, and every thing has its own attributes and behaviors.

The object oriented thought is the design thought of abstracting the attribute and behavior characteristics of things and describing them as computer events in the process of computer programming.

It is different from the process-oriented thought, emphasizing the realization of functions by calling the behavior of objects, rather than the realization of operations step by step.

For example,

Wash the clothes.

Process oriented: take off your clothes — — — — > > find one dish to put some washing powder — — > add some water > soak for 10 minutes — > rub – > wash clothes — — > dry — – > drying up Object-oriented: take off your clothes — — — — > > open the full-automatic washing machine throwing clothes — — — — > > button dried up

The difference between:

Process-oriented: Emphasize steps. Object orientation: Emphasize objects, in this case washing machines.

The characteristics of

Object oriented thinking is more in line with our thinking habits, it can simplify complex things and turn us from the executor to the leader. Object-oriented languages contain three basic features, namely encapsulation, inheritance and polymorphism.

1.2 Classes and Objects

Look around, you will find many objects, such as desks, chairs, classmates, teachers and so on. Desks and chairs belong to office supplies. Teachers and students are human beings. So what is a class? What is an object?

What is the class

Class: A collection of related properties and behaviors.

It can be regarded as the template of a class of things, which can be described by the attribute characteristics and behavior characteristics of things.

In reality, describe a class of things:

  • Attribute: is the state information of the thing.
  • Behavior: what the thing is capable of doing.

Example: a dog.

  • Attributes: name, weight, age, color.
  • Behavior: walk, run, bark.

What is an object

Object: is the concrete embodiment of a class of things. An object is an instance of a class (it’s not looking for a girlfriend) and must have the properties and behavior of that class.

In real life, an example of one kind of thing: a kitten.

Example: a kitten.

Attributes: Tom, 5kg, 2 years, Yellow. Behavior: Walk away from the wall, skip running, bark.

Relationships between classes and objects

A class is an abstract description of a class of things. An object is an instance of a class of things; it is concrete.

A class is a template for an object, and an object is an entity of the class.

As shown below: Abstract humanoid modeling versus real people

1.3 Class definition

Contrast between things and classes

3. A class of things in the real world:

  • Attribute: Information about the state of a thing.
  • Behavior: what things can do.

The same is true of classes used to describe things in Java:

  • Member variables: Properties corresponding to things
  • Member methods: Actions that correspond to things

Class definition format

public class ClassName {
// Member variables // member methods
}
Copy the code

Class definition: Defines the members of a class, including member variables and member methods. Member variables: Almost the same as before. It’s just that the location has changed. In a class, outside of a method. Member methods: Almost the same as before. Static has been removed, and will be explained in more detail later in the object-oriented course.

Class definition format example:

public class Student {
	// Member variablesString name;// name int age; / / age
	// Member methods // Methods of learning
	publicvoid study(a) { System.out.println("Study hard and make progress every day.");
}

// How to eat
publicvoid eat(a) {
	System.out.println("Study hungry, eat."); }}Copy the code

1.4 Use of objects

The usage format of the object

Create an object:

Class name Object name =newThe name of the class ();Copy the code

Using objects to access members of a class:

Object name. Member variable; Object name. Member method ();

An example of the format of the object:

public class Test01_Student {
	public static void main(String[] args) { 
		// Create object format: class name object name = new class name ();
		Student s = new Student();
		System.out.println("s:"+s); //cn.itcast.Student@100363
		
		// Outputs the values of member variables directly
		System.out.println("Name:"+s.name); //null 
		System.out.println("Age:"+s.age); / / 0
		System.out.println("‐ ‐ ‐ ‐ ‐ ‐ ‐ ‐ ‐ ‐");
		
		// Assign a value to a member variable
		s.name = "Zhao Liying"; 
		s.age = 18;
		
		// Print the value of the member variable again
		System.out.println("Name:"+s.name); / / li-ying zhao
		System.out.println("Age:"+s.age); / / 18
		System.out.println("‐ ‐ ‐ ‐ ‐ ‐ ‐ ‐ ‐ ‐");
		
		// Call the member method
		s.study(); // "Good good study, day day up"
		s.eat(); // "When you are hungry, eat."}}Copy the code

Default value for a member variable

1.5 Class and object exercises

Define mobile phone class:

public class Phone {
	// Member variables
	String brand; 	/ / brand
	int price; 		/ / price
	String color; 	/ / color
	
	// Member method // call
	public void call(String name) {
		System.out.println("To"+name+"Make a call");
	}
	/ / text
	public void sendMessage(a) {
		System.out.println("Group texting"); }}Copy the code

Define test classes:

public class Test02Phone {
	public static void main(String[] args) {
		// Create an object
		Phone p = new Phone();
		
		// Outputs the value of the member variable
		System.out.println("Brand:"+p.brand);//null 
		System.out.println("Price:"+p.price);/ / 0
		System.out.println("Color:"+p.color);//null
		
		System.out.println("‐ ‐ ‐ ‐ ‐ ‐ ‐ ‐ ‐ ‐ ‐ ‐");
		
		// Assign a value to a member variable
		p.brand = "The hammer"; 
		p.price = 2999; 
		p.color = "Brown";
		
		// Print the member variable values again
		System.out.println("Brand:"+p.brand);/ / the hammer
		System.out.println("Price:"+p.price);/ / 2999
		System.out.println("Color:"+p.color);/ / brown
		System.out.println("‐ ‐ ‐ ‐ ‐ ‐ ‐ ‐ ‐ ‐ ‐ ‐");
		
		// Call the member method
		p.call("Purple xia"); p.sendMessage(); }}Copy the code

1.6 Object memory map (readable but not readable)

An object that calls a method memory map

From the figure above, we can understand that the method of running in stack memory follows the principle of “first in, last out, last in, first out”. The variable p points to space in heap memory, looking for method information to execute that method.

But there are still problems. When creating multiple objects, it would be a waste of memory to keep a copy of method information inside each object, because the method information is the same for all objects. So how to solve this problem? Please look at the diagram below.

Two objects that call the same method memory map

When the object calls a method, it looks for method information in the class based on the method token (address value) in the object. In this way, even if there are multiple objects, only one copy of method information is saved, saving memory space.

A reference passed as a parameter to the method’s memory map

The reference type is passed as an argument, and the address value is passed.

1.7 Differences between member variables and local variables

Variables are given different names depending on where they are defined. As shown below:

  • The position in the class has different emphasis

    Member variable: in a class, outside a method Local variable: in a method or on a method declaration (formal parameters)

  • The scope of action is different

    Member variables: local variables in a class: methods

  • Different emphasis on initialization values

    Member variables: have default values Local variables: have no default values. It must be defined, assigned, and then used

  • The location in memory is different

    Member variables: heap memory Local variables: stack memory

  • The life cycle is understood differently

    Member variables: exist with the creation of the object and disappear with the disappearance of the object. Local variables: exist with the invocation of the method and disappear with the completion of the invocation of the method

2. Java packages

2.1 Encapsulation Overview

An overview of the

Object oriented programming language is the simulation of the objective world, in which the member variables are hidden inside the object and cannot be manipulated and modified directly by the outside world. Encapsulation can be thought of as a protective barrier that prevents the code and data of that class from being arbitrarily accessed by other classes. To access data for this class, you must use the specified method. Proper encapsulation makes code easier to understand and maintain, and also enhances code security.

The principle of

Hide properties and provide public methods to access a property if needed.

2.2 Steps of encapsulation

  1. Use the private keyword to decorate member variables.
  2. A pair of getXxx and setXxx methods are provided for the member variables that need to be accessed.

2.3 Encapsulated operations — the private keyword

The meaning of the private

  1. Private is a permission modifier that represents the minimum permission.
  2. You can modify member variables and member methods.
  3. Member variables and member methods that are private are accessible only in this class.

The use format of private

privateData type variable name;Copy the code
  1. Use private to decorate a member variable as follows:

    public class Student { 
    	private String name; 
    	private int age;
    }
    
    Copy the code
  2. Provide getXxx method/setXxx method, can access the member variable, code as follows:

    public class Student { 
    	private String name; 
    	private int age;
    
    	public void setName(String n) {
    		name = n;
    	}
    	
    	public String getName(a) {
    		return name;
    	}
    	
    	public void setAge(int a) {
    		age = a;
    	}
    	
    	public int getAge(a) {
    		returnage; }}Copy the code

2.4 Package optimization 1 — This keyword

We find that the parameter name in setXxx method does not conform to the requirement of knowing meaning by name, so if the modification is consistent with the name of the member variable, will it be known by name?

The code is as follows:

public class Student { 
	private String name; 
	private int age;
	public void setName(String name) {
		name = name;
	}

	public void setAge(int age) { age = age; }}Copy the code

After modification and testing, we found a new problem, member variable assignment failed. In other words, the setXxx() method does not assign a value to a member variable after changing the parameter name! This is because the parameter variable name is the same as the member variable name, so the member variable name is hidden, and the variable name in the method cannot access the member variable, so the assignment fails. So, we can only use this keyword to solve the duplication problem.

The meaning of this

This represents a reference (address value) to the current object of the class, that is, a reference to the object itself.

Note:

This in the method represents the object on which the method is called. This is whoever is calling it.

This uses formatting

this. Member variable name;Copy the code

Use this to modify the variables in this method to solve the problem that member variables are hidden as follows:

public class Student { 

	private String name; 
	private int age;
	
	public void setName(String name) {
		//name = name; 
		this.name = name;
	}
	
	public String getName(a) {
		return name;
	}
	
	public void setAge(int age) {
		//age = age; 
		this.age = age;
	}
	
	public int getAge(a) {	
		returnage; }}Copy the code

Note:

If a method has only one variable name, this is used by default and can be omitted.

2.5 Package optimization 2 — Construction method

When an object is created, constructors are used to initialize the object, assigning initial values to its member variables.

Tip: All classes have constructors, whether you customize them or not, because Java automatically provides a no-argument constructor. Once you define your own constructor, the default no-argument constructor provided by Java automatically becomes invalid.

Constructor definition format

Modifier constructor name (argument list){/ / the method body

}
Copy the code

A constructor is written with the same name as its class. It doesn’t return a value, so you don’t need a return value type, or even void. After using the constructor, the code looks like this:

public class Student { 
	private String name; 
	private int age;
	// No argument constructor
	public Student(a) {} 
	// There is a parameter constructor
	public Student(String name,int age) {
		this.name = name; 
		this.age = age; }}Copy the code

Matters needing attention

  1. If you do not provide a constructor, the system will provide a no-argument constructor.
  2. If you provide a constructor, the system will no longer provide a no-argument constructor.
  3. Constructors can be overloaded, with or without parameters.

2.6 Standard code – JavaBean

Javabeans are a standard specification for writing classes in the Java language. Javabean-compliant classes must be concrete and common and have parameterless constructors that provide set and GET methods for manipulating member variables.

Public class name {// member variable // constructor // no argument constructor [required] // parameter constructor [recommended] // member method //getXxx() //setXxx()} public class name {// member variable // constructor // no argument constructor [required] // Parameter constructor [recommended] // member method //getXxx() //setXxx()}Copy the code

Write classes that conform to the JavaBean specification, taking the student class as an example, the standard code is as follows:

public class Student {
	// Member variables
	
	private String name; 
	private int age;
	
	// constructor
	
	public Student(a) {}
	
	public Student(String name,int age) {
		this.name = name; 
		this.age = age;
	}
	
	// Member methods
	
	publicvoid setName(String name) {
		this.name = name;
	}
	
	public String getName(a) {
		return name;
	}
	
	publicvoid setAge(int age) {
		this.age = age;
	}
	
	publicint getAge(a) {
		returnage; }}Copy the code

Test class, the code is as follows:

public class TestStudent {
	public static void main(String[] args) {
		// No parameter construction is used
		Student s= new Student(); 
		s.setName("Ada"); 
		s.setAge(18);
		
		System.out.println(s.getName()+"‐ ‐ ‐"+s.getAge());
		
		// The parameter construction is used
		Student s2= new Student("Zhao Liying".18);
		System.out.println(s2.getName()+"‐ ‐ ‐"+s2.getAge()); }}Copy the code

3. The inheritance

1.1 an overview of the

origin

If the same properties and behaviors exist in multiple classes, the content can be extracted into a single class, so that multiple classes no longer need to define these properties and behaviors, just inherit from that one class.

As shown in the figure:

Multiple classes may be called subclasses, and a single class may be called a parent, superclass, or base class.

Inheritance describes the ownership relationship between things, which is the relationship between IS-A. For example, rabbits are herbivores, and herbivores are animals. As you can see, the parent class is more general and the child class is more specific. We can form a system of relationships between various things through inheritance.

define

Inheritance: A subclass inherits the attributes and behaviors of its parent class, making the subclass object have the same attributes and behaviors as the parent class. Subclasses have direct access to non-private properties and behaviors in their parent class.

benefits

  1. Improve code reuse.
  2. Relationships arise between classes, which is the premise of polymorphism.

1.2 Inherited Formats

With the extends keyword, you can declare that a subclass extends from another parent class in the following format:

classThe parent class{... }classA subclassextendsThe parent class{... }Copy the code

Inheritance demonstration, the code is as follows:

/* * Defines the Employee class as the parent */
class Employee {
String name; // Define the name attribute
// Define how employees work
public void work(a) {
		System.out.println("The teacher worked with all his heart."); }}/* * define Teacher class to inherit Employee */
class Teacher extends Employee {
	// Define a method to print name
	public void printName(a) {
	System.out.println("name="+ name); }}/* * Define the test class */
public class ExtendDemo01 {
	public static void main(String[] args) {
		// Create a lecturer object
		Teacher t = new Teacher();
		// Assign the name attribute of the employee class
		t.name = "Xiao Ming";
		// Call the employee's printName() method
		t.printName(); // name = xiaoming
		// call the work() method inherited from Teacher
		t.work(); // The teacher works with his heart and soul}}Copy the code

1.3 Inherited features – member variables

When there are relationships between classes, what are the effects of member variables in each class?

Member variables have different names

If a member variable with a different name is present in the subclass parent, the access is not affected.

The code is as follows:

class Fu {
	// Member variables in the Fu.
	int num = 5;
}
class Zi extends Fu {
	// member variables in Zi
	int num2 = 6;
	// member methods in Zi
	public void show(a) {
		// access num from the parent class,
		System.out.println("Fu num="+num); // It is directly accessed.
		// Access num2 in subclasses
		System.out.println("Zi num2="+num2); }}class ExtendDemo02 {
		public static void main(String[] args) {
		// Create a subclass object
		Zi z = new Zi();
		// Call the show method in the subclassz.show(); }}Copy the code

Demo Results:

Fu num = 5
Zi num2 = 6
Copy the code

Member variables have the same name

Access matters if a member variable with the same name is present in the subclass parent. The code is as follows:

class Fu {
	// Member variables in the Fu.
	int num = 5;
}
class Zi extends Fu {
	// member variables in Zi
	int num = 6;
	public void show(a) {
		// Access num in the parent class
		System.out.println("Fu num=" + num);
		// Access num in the subclass
		System.out.println("Zi num="+ num); }}class ExtendsDemo03 {
	public static void main(String[] args) {
		// Create a subclass object
		Zi z = new Zi();
		// Call the show method in the subclassz.show(); }}Copy the code

Demo Results:

Fu num = 6
Zi num = 6
Copy the code

When a member variable of the same name appears in a child class, the super keyword is used to modify the parent class member variable when the child class needs to access the non-private member variable of the parent class, similar to what we learned earlier.

Use format:

super. Parent member variable nameCopy the code

The subclass method needs to be modified as follows:

class Zi extends Fu {
	// member variables in Zi
	int num = 6;
	public void show(a) {
		// Access num in the parent class
		System.out.println("Fu num=" + super.num);
		// Access num in the subclass
		System.out.println("Zi num=" + this.num); }}Copy the code

Demo Results:

Fu num = 5
Zi num = 6
Copy the code

Note:

Member variables in a Fu class are non-private and can be accessed directly by subclasses. If a member variable in a Fu class is private, subclasses cannot access it directly. In general, when we code, we follow the principle of encapsulation, use private to modify the member variables, so how to access the parent class private member variables? Right! Public getXxx and setXxx methods can be provided in parent classes.

1.4 Inherited feature – member method

When there are relationships between classes, what are the effects of the member methods in the classes?

Member methods have no same name

If a non-identical member method is present in the subclass parent class, the call has no effect. When an object calls a method, it looks for the corresponding method in the subclass. If the method in the subclass exists, the method in the subclass is executed. If the method in the subclass does not exist, the corresponding method in the parent class is executed.

The code is as follows:

class Fu{
	public void show(a){
		System.out.println("Show method execution in Fu class"); }}class Zi extends Fu{
	public void show2(a){
		System.out.println("Show2 method execution in Zi class"); }}public class ExtendsDemo04{
	public static void main(String[] args) {
		Zi z = new Zi();
		// There is no show method in subclasses, but you can find a superclass method to executez.show(); z.show2(); }}Copy the code

Member method name — Override

If a member method with the same name appears in a subclass parent, access is a special case, called method Override.

Method override: When a subclass has a method identical to its parent class (return value type, method name, and argument list), an override effect occurs. Also known as an override or overwrite. Declaration unchanged, re-implement.

The code is as follows:

class Fu {
	public void show(a) {
		System.out.println("Fu show"); }}class Zi extends Fu {
	// Subclasses override the show method of their parent class
	public void show(a) {
		System.out.println("Zi show"); }}public class ExtendsDemo05{
	public static void main(String[] args) {
		Zi z = new Zi();
		// There is a show method in the subclass, which only executes the overridden show method
		z.show(); // Zi show}}Copy the code

Application of rewriting

Subclasses can define their own specific behavior as needed. Both inherit the function name of the parent class, and according to the needs of the subclass to re-implement the parent class method, so as to extend and enhance. For example, new phones add a caller ID profile picture,

The code is as follows:

class Phone {
	public void sendMessage(a){
		System.out.println("Texting");
	}
	public void call(a){
		System.out.println("Make a call");
	}
	public void showNum(a){
		System.out.println("Caller ID number"); }}// Smart phone class
class NewPhone extends Phone {
	// Rewrite the caller ID function of the parent class and add its own name and picture function
	public void showNum(a){
		// Use super to call functions that already exist in the parent class
		super.showNum();
		// Add your own unique display of names and images
		System.out.println("Display caller name");
		System.out.println("Show your avatar"); }}public class ExtendsDemo06 {
	public static void main(String[] args) {
		// Create a subclass object
		NewPhone np = newNewPhone ();// Call the method inherited from the parent class
		np.call();
		// Call the subclass overridden methodnp.showNum(); }}Copy the code

Note: When overridden, the super. member method is used, indicating that the member method of the parent class is called.

Matters needing attention

  1. Subclass methods override superclass methods. Ensure that the permissions are greater than or equal to the permissions of the superclass.
  2. The subclass method overrides the parent method, with the same return value type, function name, and argument list.

1.5 Inherited characteristics — construction method

When there are relationships between classes, what are the effects of the constructors in each class?

First we need to recall two things, the definition format and function of the constructor.

  1. The constructor name is consistent with the class name. So a subclass cannot inherit a superclass constructor.
  2. The constructor is used to initialize a member variable. Therefore, the initialization of a subclass must first perform the initialization action of the parent class. A subclass of the structure

By default, there is a super() that calls the constructor of the parent class. After the parent class member variable is initialized, it can be used by the child class.

The code is as follows:

class Fu {
	private int n;
	Fu(){
		System.out.println("Fu()"); }}class Zi extends Fu {
	Zi(){
		// super (), calls the superclass constructor
		super(a); System.out.println("Zi ()"); }}public class ExtendsDemo07{
	public static void main (String args[]){
		Zi zi = newZi(); }}Copy the code

Output result:

Fu () Zi ()Copy the code

1.6 super and this

Superclass space takes precedence over subclass objects

Each time a subclass object is created, the parent space is initialized before the subclass object itself is created. The purpose is that the subclass object contains its corresponding superclass space, then it can contain the member of the parent class. If the parent class member is not private, then the subclass can use the parent class member at will.

When code is called in a constructor of a subclass, the constructor of the parent class must be called first. The understanding diagram is as follows:

Super and this

  • Super: represents the storage space identifier of the parent class (interpreted as a reference to the parent).
  • This: represents a reference to the current object (whoever calls it represents it).

The use of super and this

  1. Access to members

    this. Member variables -- of this classsuper. Member variables -- of the parent classthis.member method name () -- of this classsuper.member method name () -- parent classCopy the code

    Usage demonstration, the code is as follows:

    class Animal {
    	public void eat(a) {
    		System.out.println("animal : eat"); }}class Cat extends Animal {
    	public void eat(a) {
    		System.out.println("cat : eat");
    	}
    	public void eatTest(a) {
    		this.eat();
    		// this calls a method of this class
    		super.eat(); // super calls the method of the parent class}}public class ExtendsDemo08 {
    	public static void main(String[] args) {
    		Animal a = new Animal();
    		a.eat();
    		Cat c = newCat(); c.eatTest(); }}Copy the code

    The output is:

    animal : eat
    cat : eat
    animal : eat
    Copy the code
  2. Access constructor

    this(...). Constructor of this classsuper(...). Constructor of the parent classCopy the code

    A subclass has a default super() in each constructor that calls the empty argument constructor of the parent class. Manually calling the superclass construct overrides the default super().

    Both super() and this() must be on the first line of the constructor, so they cannot occur together.

1.7 Characteristics of inheritance

1. Java supports only single inheritance, not multiple inheritance.

// A class can have only one parent, not more than one parent.
class C extends A{} //ok
class C extends A.B. //error
Copy the code

2. Java supports multi-layer inheritance (inheritance system).

class A{}
class B extends A{}
class C extends B{}
Copy the code

The top parent class is the Object class. All classes inherit Object as their parent by default.

3. Subclasses and superclasses are relative concepts.

4. Abstract classes (apply to understand, identify key points)

1.1 an overview of the

origin

A method in a parent class is overridden by its subclasses, each with a different implementation. So the parent class method declaration and method body, only the declaration has meaning, and the method body has no meaning. Methods without a method body are called abstract methods. Java syntax dictates that a class that contains abstract methods is an abstract class.

define

Abstract method: a method without a method body. Abstract class: A class that contains abstract methods.

1.2 Format used for abstract

Abstract methods

Using the abstract keyword to decorate a method is an abstract method that contains only a method name, but no method body.

Definition format:

Modifier abstract Return value type method name (parameter list);

Code examples:

public abstract void run(a);Copy the code

An abstract class

If a class contains abstract methods, the class must be abstract. Definition format:

abstract classThe class name{}Copy the code

Code examples:

public abstract class Animal {
    public abstract void run(a); }Copy the code

Use of abstractions

A subclass that inherits an abstract class must override all the abstract methods of its parent class. Otherwise, the subclass must also be declared abstract. Finally, there must be a subclass that implements the abstract methods of the parent class; otherwise, no object can be created from the original parent class to the final subclass, making no sense.

Code examples:

public class Cat extends Animal {
    public void run (a){
        System.out.println("Kitty walking on the wall..."); }}public class CatTest {
    public static void main(String[] args) {
        // Create a subclass object
        Cat c = new Cat();
        // Call the run methodc.run(); }}Copy the code

Output result:

The cat walks on the wallCopy the code

The method rewrite is the complete implementation of the abstract method of the parent class by the subclass. The operation of this method rewrite is also called the implementation method.

1.3 Matters needing attention (Often selected)

Here are some syntax details to note about the use of abstract classes. Although there are many items, there is no need to memorize them if you understand the nature of abstraction.

  1. An abstract class cannot create an object. If it does, compilation fails and an error is reported. Only objects whose subclasses are not abstract can be created.

Understanding: Suppose you create an abstract class object and call an abstract method that has no concrete method body and makes no sense. 2. An abstract class can have a constructor that a subclass uses to initialize a member of its parent class when creating an object. Understanding: Subclasses have a default super() constructor that requires access to the superclass constructor. 3. An abstract class does not necessarily contain abstract methods, but a class with abstract methods must be an abstract class. Understanding: An abstract class that does not contain abstract methods for the purpose of preventing the caller from creating objects of that class. 4. A subclass of an abstract class must override all the methods in the abstract parent class, otherwise, the compiler will fail and an error will be reported. Unless the subclass is also abstract. Understanding: Classes may contain abstract methods, assuming that you do not override all of them. So it doesn’t make sense to call an abstract method after you create an object.

5. The interface

1.1 an overview of the

Interface, is a kind of reference type Java language, is the collection method, if the interior of the class encapsulates the member variables, method of construction methods and members, so = = interface method of main is encapsulated inside contains abstract methods (JDK 7 and before), the default method and static method (JDK 8), a private method (JDK 9) = =.

Definition of an interface, which is similar to defining a class but uses the interface keyword. It will also be compiled into a.class file, but make it clear that == it is not a class, but another reference data type. = =

Reference data types: array, class, interface.

The use of an interface, which cannot create objects but can be implemented (implements, similar to being inherited). A class that implements an interface (considered a subclass of the interface) needs to implement all of the abstract methods in the interface, create the class object, and then call the method, otherwise it must be an abstract class.

1.2 Defining Formats

public interfaceThe name of the interface{
	// Abstract methods
	// The default method
	// Static method
	// Private methods
}
Copy the code

Contains abstract methods

  • Abstract methods: use the abstract keyword, which can be omitted without a method body. This method is used by subclass implementations.

The code is as follows:

```java public interface InterFaceName { public abstract void method(); } ` ` `Copy the code

Contains default methods and static methods

  • Default method: use default modifier, cannot be omitted, can be called by subclasses or overridden by subclasses.
  • Static methods: Use the static modifier to be called directly by the interface.

The code is as follows:

Java public interface InterFaceName {public default void method() {// execute statement} public static void method2() {// execute statement }} ` ` `Copy the code

Contains private methods and private static methods

  • Private methods: Use the private modifier to be called by default methods or static methods in the interface.

The code is as follows:

Java public interface InterFaceName {private void method() {// Execute statement}} ' 'Copy the code

1.3 Basic implementation

Overview of the implementation

The relation between a class and an interface is the implementation relation, that is, the class implements the interface. The class can be called the implementation class of the interface or the subclass of the interface. Implements actions similar to inheritance, the format is similar, but the keyword is different, implementation uses the implements keyword.

Non-abstract subclasses implement interfaces:

  1. All abstract methods in the interface must be overridden.
  2. Inherits the default methods of the interface, which can be called directly or overridden.

Implementation format:

Java class name implements interface name {// Rewrite the abstract method of the interface [required] // rewrite the default method of the interface [optional]} ' 'Copy the code

Use of abstract methods

All must be implemented with the following code:

  • Define the interface:

    public interface LiveAble {
    	// Define abstract methods
    	public abstract void eat(a);
    	public abstract void sleep(a);
    }
    Copy the code
  • Define the implementation class:

    public class Animal implements LiveAble {
    	@Override
    	public void eat(a) {
    		System.out.println("吃东西");
    	}
    	@Override
    	public void sleep(a) {
    		System.out.println("Sleep at night"); }}Copy the code
  • Define test classes:

    public class InterfaceDemo {
    	public static void main(String[] args) {
    		// Create a subclass object
    		Animal a = new Animal();
    		// Call the implemented methoda.eat(); a.sleep(); }}Copy the code
  • Output result:

    Eat and sleep at nightCopy the code

Use of default methods

You can inherit, you can override, or you can choose one or the other, but you can only call it from an object that implements the class.

  1. Inherit the default method with the following code:

Define the interface:

	public interface LiveAble {
		public default void fly(a){
			System.out.println("Fly in the sky"); }}Copy the code

Define the implementation class:

public class Animal implements LiveAble {
	// inherit, do not write anything, directly call
}
Copy the code

Define test classes:

public class InterfaceDemo {
	public static void main(String[] args) {
		// Create a subclass object
		Animal a = new Animal(a);// Call the default method
		a.fly();
	}
}
Copy the code

Output result:

Fly in the skyCopy the code

2. Override the default method as follows:

Define the interface:

public interface LiveAble {
	public default void fly(a){
		System.out.println("Flying in the sky"); }}Copy the code

Define the implementation class:

public class Animal implements LiveAble {
	@Override
	public void fly(a) {
		System.out.println("Free to fly."); }}Copy the code

Define test classes:

public class InterfaceDemo {
	public static void main(String[] args) {
		// Create a subclass object
		Animal a = new Animal(a);// Call the override method
		a.fly();
	}
}
Copy the code

Output result:

Free to flyCopy the code

Use of static methods

Statically associated with.class files, can only be called by the interface name, not by the class name of the implementation class or the object that implements the class, code as follows:

public interface LiveAble {
	public static void run(a){
		System.out.println("Run ~~~"); }}Copy the code

Define the implementation class:

public class Animal implements LiveAble {
	// Static methods cannot be overridden
}
Copy the code

Define test classes:

public class InterfaceDemo {
	public static void main(String[] args) {
		// Animal.run(); // [error] method cannot be inherited or called
		LiveAble.run(); //}}Copy the code

Output result:

Run ~ ~ ~Copy the code

Use of private methods

  • Private methods: Only default methods can be called.
  • Private static methods: Default methods and static methods can be called.

If there are multiple default methods in an interface and duplicate contents in the methods, they can be extracted and encapsulated in private methods for the default method to call.

From a design point of view, private methods are an adjunct to the default and static methods. Students can test their own skills on the basis of what they have learned.

Define the interface:

public interface LiveAble {
	default void func(a){
		func1();
		func2();
	}
	private void func1(a){
		System.out.println("Run ~~~");
	}
	private void func2(a){
		System.out.println("Run ~~~"); }}Copy the code

1.4 Multiple implementations of interfaces

We learned earlier that in inheritance, a class can only inherit from one parent. In the case of interfaces, a class can implement multiple interfaces, which is called multiple implementations of interfaces. In addition, a class can inherit from a parent class and implement multiple interfaces simultaneously.

Implementation format:

classThe name of the class [extendsThe parent class name]implementsInterface name 1, interface name 2, interface name 3...{
	// Override abstract methods in interfaces [must]
	// Override the default method in the interface.} [] : indicates an optional operation.Copy the code

Abstract methods

When there are more than one abstract method in an interface, the implementation class must override all the abstract methods. If the abstract method has the same name, you only need to rewrite it once. The code is as follows:

Define multiple interfaces:

interface A {
	public abstract void showA(a);
	public abstract void show(a);
}
interface B {
	public abstract void showB(a);
	public abstract void show(a);
}
Copy the code

Define the implementation class:

public class C implements A.B{
	@Override
	public void showA(a) {
		System.out.println("showA");
	}
	@Override
	public void showB(a) {
		System.out.println("showB");
	}
	@Override
	public void show(a) {
		System.out.println("show"); }}Copy the code

The default method

Interface, when there are more than one default method, implementation class can inherit use. If the default method has the same name, it must be overridden. Define multiple interfaces:

interface A {
	public default void methodA(a){}
	public default void method(a){}}interface B {
	public default void methodB(a){}
	public default void method(a){}}Copy the code

Define the implementation class:

public class C implements A.B{
	@Override
	public void method(a) {
		System.out.println("method"); }}Copy the code

A static method

The presence of static methods with the same name in an interface does not conflict because static methods can only be accessed by their respective interface names.

The question of priorities

When a class inherits a parent class and implements several interfaces, the member methods in the parent class have the same name as the default methods in the interface, and the subclass chooses the nearest member method to execute the parent class.

The code is as follows:

Define the interface:

interface A {
	public default void methodA(a){
		System.out.println("AAAAAAAAAAAA"); }}Copy the code

Define the parent class:

class D {
	public void methodA(a){
		System.out.println("DDDDDDDDDDDD"); }}Copy the code

Define subclasses:

class C extends D implements A {
	// methodA method is not overwritten
}
Copy the code

Define test classes:

public class Test {
	public static void main(String[] args) {
		C c = newC(); c.methodA(); }}Copy the code

Output result:

DDDDDDDDDDDD
Copy the code

1.5 Interface Multiple Inheritance

An interface can inherit from one or more interfaces, similar to inheritance between classes. Interfaces inherit using the extends keyword, and subinterfaces inherit the methods of their parent interfaces. If the default method in the parent interface has the same name, then the subinterface needs to be overridden. = =. The code is as follows:

Define the parent interface:

interface A {
	public default void method(a){
		System.out.println("AAAAAAAAAAAAAAAAAAA"); }}interface B {
	public default void method(a){
		System.out.println("BBBBBBBBBBBBBBBBBBB"); }}Copy the code

Define subinterfaces:

interface D extends A.B{
	@Override
	public default void method(a) {
		System.out.println("DDDDDDDDDDDDDD"); }}Copy the code

Tip:

When the subinterface overrides the default method, the default keyword can be retained.

When a subclass overrides the default method, the default keyword cannot be retained.

1.6 Characteristics of other members

In the interface, member variables cannot be defined, but constants can be defined and their values cannot be changed. By default, public static final is used.

Interface, there are no constructors, cannot create objects.

There are no static code blocks in the interface.

1.7 Interface and Inheritance Cases

Yangyongli.blog.csdn.net/article/det…

6. Supplementary knowledge: Permission modifiers

An overview of the

There are four types of access rights provided in Java. The content to be modified has different access rights when modified with different access modifier.

  • Public: public.
  • Protected: Protected
  • Default: indicates the default value
  • Private: private

The ability to access different permissions

public protected Default (empty) private
In the same class Square root Square root Square root Square root
In the same package (subclasses and unrelated classes) Square root Square root Square root
Subclasses of different packages Square root Square root
Unrelated classes in different packages Square root

As you can see, public has the maximum permission. Private is the minimum permission. When writing code, without special consideration, it is recommended to use permissions like this:

  • Member variable useprivate, hiding details.
  • Constructor usepublicTo facilitate object creation.
  • Member methods usepublicTo facilitate method calls.

Tip: Without the permission modifier, it has the same access as the default modifier

This section describes the default keyword

This is the first time in my life to see this keyword. Then I searched it and found that it is a new feature of Java8. So I simply studied it in detail and sorted out the following things.

The default keyword is used to modify a method in the interface, so the method can have a method body. Let’s take a look at an example.

For example,

The Default class

public interface Default {
 
    default public void method(a){
        System.out.println("Methods in interface"); }}Copy the code

An interface, method methods can have a body after using the keyword default.

public class DefaultImpl implements Default {
 
    @Override
    public void method(a) {
        System.out.println("Method in class");
    }
 
    public static void main(String[] args){
        Default d = newDefaultImpl(); d.method(); }}Copy the code

DefaultImpl implements the Default interface.

Methods in a classCopy the code

DefaultImpl does not implement the Default keyword. If the Default keyword is not used, DefaultImpl does not implement the Default keyword. We continue to modify the Default interface.

The Default interfaces are as follows:

public interface Default {
 
    default public void method(a){
         System.out.println("Methods in interface");
    }
 
    default public void doSomeThing(a){
         System.out.println("Doing something in the interface"); }}Copy the code

DefaultImpl does not rewrite the doSomeThing method

public class DefaultImpl implements Default {
	@Override
	public void method(a) {
	     System.out.println("Method in class");
	}
	// The interface method doSomeThing is not overridden at this point
	// One is generated by default here, and the subclass object is called directly using the doSomeThing method in the interface
	public static void main(String[] args){
	    Default d = newDefaultImpl(); d.method(); d.doSomeThing(); }}Copy the code

The running results are as follows:

Methods in a class do things in the interfaceCopy the code

Run results conform to the characteristics of Java polymorphism, the default keyword allows the interface methods can have default function body, when a class implements this interface, can need not to implement this method, of course, if this class implement this method, it is equal to the subclasses override this method, the final results accord with Java polymorphism characteristics.

7. Supplementary knowledge: final keywords

1.1 an overview of the

Now that we’ve learned about inheritance, we know that a subclass can override a parent class based on its parent class, for example, method override. So can we inherit the classes provided in the API at will and rewrite their content? Obviously this is not appropriate. To avoid this arbitrary rewriting, Java provides the final keyword to modify immutable content.

final: unalterable. Can be used to modify classes, methods, and variables.

  • Class: A modified class that cannot be inherited.
  • Method: a decorated method that cannot be overridden.
  • Variable: A variable that is decorated and cannot be reassigned.

1.2 Usage Mode

decorator

The format is as follows:

final classThe name of the class{}Copy the code

Querying apis finds that many of the classes we have studied, such as public Final Class String, Public Final Class Math, and Public Final Class Scanner, are final modifiers. The purpose is for us to use it without letting us change its content.

Modification methods

The format is as follows:

The modifierfinalReturn value type Method name (argument list){/ / the method body
}
Copy the code

Overrides methods decorated with final, and an error is reported at compile time.

Modify variables

1. Local variables — Primitive types

Local variables of basic types are final modified and can only be assigned once and cannot be changed again. The code is as follows:

public class FinalDemo1 {
	public static void main(String[] args) {
		// Declare variables with final
		final int a;
		// First assignment
		a = 10;
		// The second assignment
		a = 20; // An error is reported and cannot be reassigned
		// Declare variables, assign values directly, use final modifier
		final int b = 10;
		// The second assignment
		b = 20; // An error is reported and cannot be reassigned}}Copy the code

Think, which of the following two ways can be compiled?

Method 1:

final int c = 0;
for (int i = 0; i < 10; i++) {
	c = i;
	System.out.println(c);
}
Copy the code

Method 2:

for (int i = 0; i < 10; i++) {
	final int c = i;
	System.out.println(c);
}
Copy the code

According to the definition of final, write method 1 error! Write 2. Why does it compile?

Because every time we go through this loop, it’s a new variable c.

2. Local variables — reference types

Local variables that reference types are final modified and can only refer to one object, the address cannot be changed. But does not affect the internal object member variable value modification, the code is as follows:

public class FinalDemo2 {
	public static void main(String[] args) {
		// Create the User object
		final
		User u = new User();
		Create another User object
		u = new User(); // Error indicating new object, address value changed.
		// Call setName
		u.setName("Zhang"); // It can be modified}}Copy the code

3. Member variables

Member variables are involved in the initialization of the problem, there are two ways to initialize, can only be two:

  1. Display initialization;

    public class User {
    	final String USERNAME = "Zhang";
    	private int age;
    }
    Copy the code
  2. Constructor initialization:

    public class User {
    	final String USERNAME ;
    	private int age;
    	public User(String username, int age) {
    		this.USERNAME = username;
    		this.age = age; }}Copy the code

Unde final names are constants that are often modified and generally have writing norms, with all letters capitalized.

8. Common core classes and their methods are being sorted out

* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *Copy the code

Second, Web knowledge

1. The HTML based

Composition of Web standards

Web standards are not a single standard, but a collection of standards developed by the W3C and other standardization organizations.

It mainly includes three aspects: Structure, Presentation and Behavior.

Structure standard: structure is used to organize and classify the elements of the web page, we mainly learn HTML. The most important performance standard: performance used to set the layout, color, size and other appearance styles of web elements, mainly refers to CSS. Behavior standards: behavior refers to the definition of web model and interactive writing, we mainly learn JavascriptCopy the code

Ideally our source code:.html.css.js

HTML first

Generally, learn HTML+CSS first. Here we set a small goal, learn HTML first, then learn CSS.

HTML (English Hyper Text Markup Language abbreviation) Translated into Chinese “hypertext Markup Language”. Is a language used to describe web pages.

It’s called hypertext because it can add pictures, sounds, animations, multimedia and more, and it can jump from file to file, connecting to files on hosts around the world.

<h1>I'm a headline</h1>
Copy the code

Note: experience a few words in text label language

  • HTML stands for Hyper Text Markup Language
  • HTML is not a programming language, but a Markup language.
  • A markup language is a set of markup tags.

Summary: HTML is used to describe a web page with tags and display the content in the browser.

Use text to describe web page tags

HTML skeleton format

HTML has its own syntax skeleton format:

<HTML>   
    <head>     
        <title></title>
    </head>
    <body>
    </body>
</HTML>
Copy the code
1 HTML tag: A root node for all tags in HTML. The header of a document describes various properties and information about the document, including the title of the document, its location on the Web, and its relationship to other documents. Most document headers contain data that is never actually displayed to the reader as content. Note that in the head tag we must set the tag title 3. The title tag is used to give the page its own title. 4. Body tag: The body of the document from now on, the content of our page is basically placed inside the body. The body element contains all the content of the document (such as text, hyperlinks, images, tables and lists, etc.).Copy the code

HTML tag classification

In HTML pages, elements with the “< >” symbol are called HTML tags, such as <HTML>, <head>, and <body> mentioned above are HTML skeleton tags. Tags are encoded commands that represent a function in the “< >” tag, also known as HTML tags or HTML elements

1. Double label

< tag name > Content </ tag name >Copy the code

In this syntax, < label name > indicates the start of the label, and is generally called start tag. </ Label name > indicates the end of the label, and is generally called end tag. In contrast to the start tag, the end tag is preceded by the closing character “/”.

Such as<body>I am writing</body>
Copy the code

2. Single label

< tag name />Copy the code

A single label, also called an empty label, describes a function completely with a label symbol.

Such as<br />
Copy the code

HTML Tag relationship

The relationship between labels is divided into two types: 1. Nested relationship

<head>  <title> </title>  </head>
Copy the code

2. Parallelism

<head></head>
<body></body>
Copy the code

Suggestion: If the relationship between two labels is nested, the child element should be indented by a TAB key. If it’s side-by-side, align it up and down.

The document type

<! DOCTYPEhtml> 
Copy the code

What kind of phone do you use? What do you say?

Which version of HTML to use? We are using the HTML 5 version. There are many versions of HTML, so we should tell users and browsers which version we are using.

Note: Some of the older sites may still use older versions of the document type such as XHTML, but we are learning HTML5, and HTML5 document type compatibility is very good (backward compatibility principle), so you can feel comfortable using HTML5 document type.

Character set

Gb2312 Simple Chinese contains 6763 characters

BIG5 traditional Chinese for Hong Kong, Macao and Taiwan

GBK contains all Chinese characters is an extension of GB2312, adding support for traditional Chinese characters, compatible with GB2312

Utf-8 contains characters that all countries in the world need to use

Keep in mind that in the future we will all use the UTF-8 character set, so as to avoid garbled characters caused by inconsistent character sets.Copy the code

Semantics of HTML tags

Vernacular: the so-called semantic label is the meaning of the indicator sign.

Why semantic tags

  1. Easy to read and maintain code
  2. At the same time, the browser or web crawler can be very good parsing, so as to better analyze the content
  3. Use semantic tags for better SEARCH engine optimization

Core: appropriate place to give a most reasonable label.

Semantically sound: When we remove CSS, the structure of the page remains well organized and readable.

Vernacular, at a glance, you know what is the key, what is the structure, what is the content of each piece.

Rule to follow: First decide on semantic HTML, then choose appropriate CSS.

Common HTML tags

First of all, HTML and CSS are two completely different languages, we learn structure, just write HTML tags, just know the tags. Structure tags will no longer be styled.

There are a lot of HTML tags, so here we’re going to look at the most common ones, and then we’re going to look at some of the less common ones, and we’re going to look them up in the manual.

Typesetting label

Layout labels are used together with the CSS to display the structure of the web page. They are the most commonly used labels for web page layout.

Title tag (memorized)

Acronym: head. Title Title of the document

In order to make web pages more semantic, we often use title tags in the page, HTML provides six levels of title, namely

 <h1>,<h2>,<h3>,<h4>,<h5>and<h6>
Copy the code
Header tag semantics: Used as headings and in diminishing importanceCopy the code

The basic syntax is as follows:

<hn>Title text</hn>
Copy the code

Note: the H1 tag is important, so use it sparingly. Don’t throw an H1 at you. H1 is usually used for the logo or the most important title information on the page ==.

Paragraph tag (memorized)

There is no need to remember this word

In the web page to put the text orderly display, cannot leave the paragraph tag, just as we usually write an article, the whole web page can also be divided into a number of paragraphs, and the paragraph tag is

<p>The text content</p>
Copy the code

Is the most common tag in HTML documents, and by default, text is wrapped in a paragraph based on the size of the browser window.

Horizontal label (recognition)

Horizontal [ˌhɔrəˈzɑ NTL]

On web pages, it’s common to see horizontal lines separating paragraphs from each other to create a clear, hierarchical document. These horizontal lines can be done by inserting images or simply by using labels,


<hr />A single tagCopy the code

Displays a horizontal line with the default style in the web page.

Chu Qiaochuan small case

Code:

<! DOCTYPEhtml>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
</head>
<body>
 <h1>ChuQiaoChuan</h1>
 <div>Mainland China 67 episodes (TV) /58 Episodes (DVD)</div>
<p>Chuqiao legend is a female inspirational legend costume drama co-produced by Ciwen Media, Honey Tao Film and Keton Media. Directed by Wu Jinyuan, Jia Wen, Yang Tao, Chen LAN screenwriter, Zhao Liying, Lin Gengxin, Dou Xiao, Li Qin starring, Deng Lun, Jin Shijie invited to play, Wang Yanlin, Niu Junfeng, Huang Mengying, Tian Xiaojie, Sun Ning, Jin Han, Xing Zhaolin, Cao Xiyue, Zhu Shengyi, Ruan Shengwen, Li Ruojia, Miao Miao and other co-stars. [1] The play is adapted from xiaoxiang Donger's novel Imperial Concubine of 11 Agents. It tells a story about protection, betrayal, faith and love of Chu Qiao, a maverick female slave, in the troubled times of western Wei Dynasty, when she helps to establish a new regime.</p>

<p>
	<p>Links to domain pages</p>
<a href="test.html#next">Another page for episode 4</a>

</p>1 set<br />
 <a href="#two">2 sets</a><br />  
 <a href="#three">The third set</a><br />
 <a href="#four">4 sets</a><br />
 <a href="five">The fifth set</a><br />
<img src="images/1.jpg" height="500" width="400" alt="">

<h3>Episode 1 (Based on TV version)</h3>On the rickety paddy wagon, a young girl sleeps with her eyes closed. The dream is all blood and rain, trance, she only remember someone called her Chu Qiao, and someone called her Jing six. She had no idea where she had come from or where she was going. From the paddy wagon came low sobs, Chu Qiao from the dream back to god. All around is a strange, there is a little girl who calls herself curly head to hear Chuqiao's stomach cooing, he will hide the half of the cake to her. Chuqiao tell curly head, oneself call jing small six, curly head then call her small six sister. The slaves were taken to the paddock. The imperial city of the Western Wei dynasty, Yan Xun, yan Bei prince of the Western Wei Dynasty thirteen princes Yu Wang Yuan Song, Wei shuye, the elder son of the Wei valve, Zhao Xifeng and Yu Wen valve three house sun Yu Wenhuai rode out of the city to a paddock. The slaves were driven from their tents and stood in the middle of the paddock surrounded by armed officers and soldiers. The girls wore clothes with the names of several boys written on them. See this situation, standing on the high platform of the teenagers do not understand the intention of Yu Wenhuai. Yuwen huai complacent smile, tell the other several young, this is not an ordinary hunting. This time, there are not only wolves, but also these fresh girl slaves. They can shoot animals, or other people's slaves. After a joss stick, see who has the most slaves left, and then the winner. Yu King thought this kind of play was too cruel and objected. But Zhao Xifeng felt very interesting, encouraging everyone to get excited. Several people could not hold each other, and the words became heated. See Zhao Xifeng clamoring to put the Wolf, yu King will shirk yuwen Yue to start again. Yu Wenhuai but Yin Yin smile, only yu Wenyue afraid is a night. On the other side, yuwen castle Peak courtyard. A white yu Wenmen valve long room sun Yuwenyue, just pushed the door into the room, he saw a beauty lying on the bed. But he glanced faintly at the beauty in bed, and went to the desk and sat down. The beauty saw it and took the initiative to lure it. Yuwenyue is quiet, counterplot, attracted beauty to take the initiative to assassinate, just captured her. Solve the assassin, Yuwen Yue this just ordered people to prepare horses, to run to the paddock. As yuwenyue rushed to the paddock on the way, the paddock has been a scene of wailing. The gates on either side of the fence were opened, and a score of ferocious wolves rushed into the paddock, roaring at the girls with their jaws wide open. Chuqiao surveyed the surrounding terrain and shouted at the maidens to flee the empty paddock and take refuge in the vegetated hills. In a panic, the arrows on the high platform have been shot at the girls, and in a moment, several people around have fallen. Chuqiao pulled curly head, frequently dodged the high stage shot arrows and hungry Wolf chase, attracted the attention of the teenagers. Panic, a hungry Wolf blocked the way in front, Chuqiao let curly head hide first, he will go to the hungry Wolf away. Prince Yan Xun sees this and shoots the hungry Wolf with an arrow and a bow, saving Chu Qiao. Just escaped a robbery chu Qiao was surrounded by two hungry wolves. She was cornered, in order to survive, picked up the arrow on the ground, mercilessly inserted into the throat of the hungry Wolf. On the dunes in the distance, Yuwenyue, riding a horse, looked at the stubborn girl in the paddock and couldn't help admiring her in the bottom of my heart, a born warrior. Less and less girls in the paddock, Yu Wenhuai looked at the tenacious Chu Qiao, can not help but play heart. He mounted his horse and ordered his men into the paddock to hunt down the remaining slaves. Several other teenagers follow him, yan Xun only shoots the hungry wolves on the way, not the female slaves. Gradually, there were fewer female slaves in the paddock and fewer hungry wolves. There was only one group of men, running wildly through the wilderness, chasing the girls in the direction where they had fled, and the slave girls kept falling. Chuqiao pulled curly hair, running desperately on the sand dune, did not dare to slow down for a while, she knew that if she wanted to live, she could not stop. In the distance there was the end of the rattle of arrows, and everyone pulled up. Yuwen huai heart has unwilling, he still pulled the bow toward female slave shot in the past, run in the back of the curly head fell to the ground. Chuqiao turned back and hugged curly head tightly, as if to be weathered in general, motionless. The heart is unwilling to yuwenhuai, don't want to let the body write "Yue" word Chu Qiao survived, regardless of the agreement before, still shot an arrow toward Chu Qiao. One side of Yan Xun saw, take an arrow shot to Yu Wenhuai arrow, but still slightly off a few millimeter, only shot a few wisps of the tail of the feather. At the last minute, Yuwen Yue quietly blocked the arrow with a bolt, saved chu Qiao's life. And heartbroken Chu Qiao, naturally did not notice, she is how to survive in a few young debate. She only has hatred in her mind at the moment, so that when prince Yan Xun asks her name, she only gives a cold answer, I will tell you naturally when I don't have to look up to you any more. Luckily survived Chu Qiao, but because provoke yu Wen huai displeasure, was housekeeper Zhu Shun shut into yu Wen house firewood room. Lying on the ground of chu Qiao heart hate, she hate this world, the nobles are terrible than hungry wolves, life than dirt but also cheap world. In the dark wood room, covered with wounds chu Qiao secretly vowed that sooner or later, one day, he will let these people pay for their blood. A man carrying a food box came in, to chuqiao front, a face distressed to call Chuqiao small six, said he was five elder brother. Chu Qiao did not know him and slightly resisted his approach. The man took out a bowl of rice from the food box, rice on a piece of Chu Qiao favorite braised pork, Chu Qiao tearful took over, feel to eat their life the best delicious things. Yan Xun to find Yuwen Yue, ask him to help solve chun princess to do birthday dinner for him. Yuwenyue face cold, in a few words, yan Xun will solve the problem. In the woodshed, Chuqiao is still unconscious. In her sleep, she seemed to recall that she had fought with a man and had fallen into the water, shivering in the rushing river. Someone put the stove in her hand, Chu Qiao woke up, it was the sisters in care of her.<h3 id="two">2 sets</h3>Chuqiao injury has not recovered, was sent to work aunt Song. Elder sister juice xiang for Chu Qiao intercetion, but song Aunt scolded. Housekeeper Zhu Shun came to notice, two days after the master Yuwen Yue in the house for Yan Xun prince held birthday party, who dare to make a little mistake, they will kill her, they are the only answer. Chu Qiao was arranged by song Aunt to move flowers and plants, But Zhu Shun stopped juice hunan, said he did not embarrass Chu Qiao, let juice hunan repay him. Seeing him will be on juice hunan groping, Chu Qiao suddenly came to ask juice hunan orchid position, juice Hunan successfully avoid Zhu Shun's entanglement. Yuwenhuai told Zhu Shun to YuWenyue wine poison, Chu Qiao will all this in the eyes, but calmly looked at. Juice hunan was arranged to pour yuwen Yue wine, Yuwen Yue aware of the wrong, refused to drink. Yuwen Huai then laughed and said to imitate the ancients, when the master did not drink, he killed the beauties. Yuwenyue know cheating, still refused to drink. Juice xiang is holding a cup, beg bitterly. Chuqiao do not want to see their sister in vain to do the victim of internal fighting, waiting for the opportunity to knock over the glass, will attract attention to their own body. Chu Qiao then begged you childe to let go of his sister, said he was willing to be punished for his sister. Yuwen Huai saw, will let people killed Chu Qiao. Yan Xun said that since his birthday, he is not willing to see the fight, for Chu Qiao. Yuwen huai said yuwen house rules can not be bad, not light rao. Yan Xun suggests playing a game to let god decide chu Qiao's life and death. He took out the waist card between his waist, waist card one side dragon pattern, one side seal character, throw it on the ground, let Chu Qiao guess which side is up, if the guess is right, she will be spared the death penalty. Chu Qiao read the hint of Yan Xun, guess the dragon grain, narrowly escaped death, but it is a crime. Chu Qiao was hanging upside down in the tree is at night, Yuwenyue brought people to put her down, but satire her. In the help of the sisters out of the house chu Qiao, overheard zhu Shun and candle dialogue, that Lin Xi is in danger, and returned to the Yuwen house. But don't want to, just returned to yuwen house, saw Yuwen Yue personally will Lin Xi killed, a kick into the fire. Chu Joe wanted to rush into the fire to save Lin Xi out, but was Yuwenyue kicked up the stone hit the shin fell to the ground, was caught by guards on the spot. Heartbroken Chuqiao Yuwenyue accused of killing innocent, his brother is not fine. Yuwen Yue but way, their innocent and how. Injured Chu Qiao returned to the wood room, told the sisters the news of the death of five elder brothers. Sad small eight blame chuqiao is a Nemesis, ke died his family, juice hunan don't let small eight said Chuqiao, sisters for this quarrel. Thick sad mixed with full helpless, leaning on the heart of each jing sisters.<h3 id="three">The third set</h3>Castle Peak funeral hall solemn, Yuwen Yue a filial clothes, quiet face revealed some faint sadness. Yuwenyue just ordered the closure of the coffin, was broken into the yard of an unexpected guest block. Bearer is the three room yuwenhuai, he regardless of guards block, arrogance, threatened to open the coffin. Yuwenyue every attempt to block failed, two people in the funeral hall to move. Is difficult to solve between, Yu Wenhuai threw out the sword let a eunuch standing at the door of the hospital risk risk to avoid, then sharp voice sounded "protect! Who dares to make mischief here?" As soon as this was said, the yuwenyue in the courtyard was surprised to leave the weapon in his hand and greet the queen. Yuwen huai heart know yuwen Yue concubine is the rescue, but also helpless, had to stop. A graceful empress asked Yuwenhuai, why in castle peak courtyard trouble? Yuwenhuai but the wicked first complaint, only yuWenyue insisted on sealing coffin, also forced to start their own. Yuwenyue will return to the imperial concubine, grandfather is in the Western region strange poison and death, he is afraid of the poison again hurt, then burn debris and seal the coffin. Wood room, wake up chuqiao depressed, even juice hunan sister sent medicine soup is not willing to drink. Juice xiang know she is because of the death of pity remorse will comfort her, born in troubled times we are involuntarily, tell her not to blame yourself. Chuqiao eyes but resolute, she told juice hunan, he will not let the dead in vain, he will live well. Then he took up the medicine and drank it all. As the maidservants were working in the courtyard, a guard came out carrying a dead body. The maidgirls were talking about it. It was jinlan, a maidgirl who had been sent to the Kao. She was tortured to death because she was not liked by the master. Song Aunt came to choose sent to the elysium maid, Chu Qiao song Aunt named to be sent to elysium. Juice hunan in order to save the younger sister, then asked the Song aunt, replaced by their chu Qiao went to the Elysium pavilion. Bliss pavilion, with juice xiang was sent into the girl, not a person alive, juice xiang is no exception. Chu Qiao with small seven small eight hiding in the dark, see juice hunan was loaded in a broken car sent out, three people sad, but dare not cry voice, can only watch his sister's body was thrown away. Afterwards, Chu Qiao quietly buried the corpse of juice Xiang. Sisters three people took to get paper money, in the grave of Xi and juice hunan burning, but was punished song Aunt hit. Song Aunt want to take them to yuwen Huai credit, then with chu Qiao sisters three people argued. In the middle of the fight, Aunt Song slipped off the bridge and was pulled by Chu Qiao, but eventually because it was too heavy and fell into the water. Small seven small eight very afraid, Chu Qiao comfort them, if one day the truth, he will bear it, called the sisters do not worry. But they did not see, there is a shadow hiding in the dark, this happened in the night, all the eyes. Yuwenyue still a pair of indifferent expression, only said that people too smart is not good. Yan Xun ignore YuWenyue's indifference, only to talk to him about their yu Wenjia infighting, said he does not like these, he just want to do the eagle flying freely on the grassland. When asked what yuwen Yue wants to be, Yuwen Yue is just a slight meditation. Yan Xun ignored Yuwen Yue, he thought of Chu Qiao, from the Yuwen Yue table along a bottle of medicine, came to find Chu Qiao. But just hit a bodyguard to take Chu Qiao to be punished, Yan Xun easily for her solution. But Chu Qiao cold look but yan Xun is very puzzled, Chu Qiao told Yan Xun, his brother and sister new loss, he is precarious, naturally not happy.<h3 id="four">4 sets</h3>Yuwenyue choose bedroom maid news spread quickly, listening to small seven small eight voice, chuqiao heart sprouts out of survival. She suddenly realized that only by leaving Yuwenhuai's minions could she protect her sisters and avenge her brother and sister. He is like the weak grass in the corner, only with the help of the strength of the strong, to fight against the stone! Chu Qiao determined to participate in the selection, she regardless of other people's strange eyes, bravely walked into the Castle Peak courtyard. Unfortunately, she was only a slave with an iron bell, not eligible to participate in the selection. But Chu Qiao knew that he had no retreat, she must participate in this choice. She remained indomitable, stubbornly kneeling in the yard refused to get up. Yuwenyue heard, only way she is overrated, they let her kneel, did not care about her. Outside the sun as a head, Chu Qiao baked in the sun, but still adhere to. The passage of time one minute one second, outside is on the sky, Chuqiao still kneeling in the yard, Yuwen Yue silently in the dark looking at the stubborn Chuqiao, on a thoughtful. Guards want to persuade Chu Qiao back, but see Chu Qiao and no intention to quit, will she go. Yuwenyue came out to stop the guards, he looked at chu Qiao kneeling on the ground, asked her why to participate in the selection. Chu Qiao looked at him firmly and said he wanted to live. Yuwenyue does not believe chu Qiao intention, he continued to ask Chu Qiao, personally killed her brother, but she came to beg her to accept her maid, where is the dignity. Chu Qiao expressionless face, eyes are still firm, as a slave, life are not protected, where there is dignity. Yuwenyue took a look at Chu Qiao, asked her if she knew the maid is to be in the master bed between the bed. Chu Qiao firmly grasped his hand, humbly kowtowed, asked the son to leave the slave. Yuwenyue seems to be meditating for a while, then ordered to the bodyguard, allow Chu Joe to participate in the selection. At the beginning of the selection, many of the maidservants gathered together, it is inevitable to give birth to trouble. Chu Qiao is due to the childe exceptionally generous to be able to run, naturally attracted others to its dissatisfaction. Silver bell big servant girl brocade candle, don't like Chu Qiao private flying prince captive parrot, want to secretly catch bad Chu Qiao clothes, don't want to, but chu Qiao backhand took away the clothes, make gain and loss of manners. Yuwenyue will see all this in the eye, see chu Qiao agile, is a martial arts seedling. The first game is pu Chess, Chu Qiao is not too understand, then very dismal to lose a game. The second game, brewing, was still not Chuqiao's strong suit, but she knew she couldn't lose. Chu Qiao was watching the preparation of tea by the maids, and suddenly an idea struck her. She went to the well and drew fresh water, picked a leaf and, following the example of the other maids, made a cup of sweet tea. Chu Qiao won the second game. The third game, memorize Sanskrit Buddhist sutra, a column of incense time to remember, and then a column of incense time to write. Chu Qiao although can't hold a pen, more can't write, but she relies on the memory of superman, will be the Sutra word for word to write down. But Chu Joe because there is no signature, and yuwen Yue blame. Chu Qiao but way, the rules did not require signature, he just do in accordance with the rules, and there is no wrong. Yuwenyue request as long as Chu Qiao can sign his name on the scriptures, this game even if she wins. Chuqiao took the brass bell from her hair, dipped it in ink, and stamped it firmly on. Yuwenyue no longer speak, but he turned back later, in the mouth of a slight can not be observed smile. After the election of Chu Qiao was brought to see YuWen Yue, YuWen Yue asked her again, why to do their maid maid. Chu Qiao knelt back, he is to live. Yuwenyue do not believe Chu Qiao will forget his own hand killed her brother's hatred, and Chu Qiao said he had promised his sister, to take good care of the two sisters.<h3 id="five">The fifth set</h3>Chuqiao woke up, suddenly feel some strange side, that lying not far away is not cold face paralysis yuwenyue, scream without thinking and blurted out. Yuwenyue unhurried sit up, cold words laugh at her fussy, this bedroom opportunity is not what she wants. Chu Qiao fierce resistance, YuWenyue took this opportunity to teach her kung fu, there was physical contact between two people, YuWenyue will her waist up, rotating several circles. Yuwen Yue for the first time in the castle peak courtyard is a sensation. Jin Zhu went to deliver soup in the early morning. Hear the outside of the room, Yuwenyue deliberately and Chu Qiao close cuddle, gentle spoil to personally feed her porridge, candle out, YuWenyue immediately pushed chu Qiao, as if just gentle water is not him, cold let her tidy up by her tainted bed. Chu Joe glanced at the red bed, face dew disdain, clearly is he deliberately get up. Chu Qiao after the bedchamber or low status of the iron bell, than the jin candle such a silver bell of the big servant girl or a lot of difference. Brocade candle to Chu Qiao envy unceasingly, small seven, small eight listen not to go down, speak for Chu Qiao baobu. Candle gas and move hand, Chu Qiao with her. Bi Shui riverside, Willow yiyi, Chu Qiao sat on the trestle side, struggling to wash clothes. Yan Xun took a horse to the river to find her, laughing yuwen Yue chu Qiao name - star, just with Yuwen Yue yue word phase and, Yan Xun face wry, said Yuwen Yue jiaozi smile. Chuqiao too lazy to dispute with him, end basin will go. Yan Xun is stubborn, playing to depend on his love foal to her. Chu Qiao temper is very Yan Xun mind, he deliberately went to find Yuwen Yue to get her to go, otherwise it depends on the castle peak courtyard not to go. Female slaves live in the small courtyard, Chu Qiao's special treatment was headed by the candle part of the female slave jealousy, with her two sisters Xiao Qi, xiao Eight also be excluded, everywhere be embarrassed. Chuqiao for sister, make candle face anger, and she moved to hand, even at the time of stab, Yuwenyue timely, lest Chuqiao was hurt. The wicked Candle filed a complaint first, pretending to protect the rules of the Green Hill Court. Yuwenyue long body Yuli, calm face no wave can not see the anger, only said to bring chu Qiao back punishment. After they left, Jin Zhu's followers held their heads high and taunted Xiao Qi and Xiao Ba even more, as if Yuwen Yue's attitude had spoken for itself. And with YuWenyue Chuqiao, don't want to be punished in vain, she explained the situation to YuWenyue, that he just can't bear the weak bullied. Yuwenyue face cold, told her the strong king, as the weak is not qualified for justice. Chuqiao heart unwilling, ask him to show what is strong. Rockery water gurgling, through the water winding stones, Yuwen Yue chuqiao into the chamber of secrets. Yuwenyue let her throw a stone, candle fire shaking, disorderly arrows, Chu Qiao temporarily can not cope, but gradually skill is faster and faster, dodge more timely. Chu qiao spent the next three hours with arrows and stones. She keeps getting hit, but her eyes are getting tougher, and to avenge herself, she has to endure more than anyone else can</body>
</html>
Copy the code

Tag (tag test read it once, familiar with it)

Newline tag (memorized)

Break a line

In HTML, the text in a paragraph is arranged from left to right, up to the right end of the browser window, and then wrapped. If you want to force a line break for a piece of text, you need to use a line break tag

<br />
Copy the code

If you hit enter in Word, line feed won’t work.

Div span tag

Div and Span are the two main boxes in our web layout, CSS +div

Div is short for division division, partition means there are actually a lot of divs to combine web pages.

Span C. The scope of

Syntax format:

<div>This is the head</div>    <span>Today's price</span>
Copy the code

Text formatting tag (memorized)

In web pages, sometimes you need to set up bold, italic, or underline effects for text. In this case, you need to use text formatting tags in HTML to make text appear in a special way.

==b I s u strong em del ins ==

Tag attributes

Attributes are features such as the color of the phone and the size of the phone.

The color of the mobile phone is black and the size of the mobile phone is 8 inches

The length of the horizontal line is 200

The width of the image is 300 key-value pairs

When you use HTML to create a web page, if you want the HTML tag to provide more information, you can use the attributes of the HTML tag to set it. The basic syntax is as follows:

< tag name Attribute 1=" Attribute value 1" Attribute 2=" Attribute value 2"... > Content </ tag name >Copy the code

In the syntax above,

1. Tags can have multiple attributes and must be written in the start tag after the tag name.

2. Attributes are not in any order. Label names and attributes and attributes are separated by Spaces.

3. The attribute of any label has a default value. If the attribute is omitted, the default value is used.

The format of the key-value pair is key=”value”

Such as:

<hr width="400" />
Copy the code

The property is the width

Value is 400

Image tag IMG (emphasis)

Word abbreviation: image

The implementation of any element in AN HTML web page depends on HTML tags. Image tags are needed to display images in a web page. Image tags will be described in detail nextAnd the attributes associated with him. The basic syntax is as follows:

The SRC attribute in this syntax specifies the path and filename of the image file, which is required for the IMG tag.

<img src="Image URL" />
Copy the code

Link tag (emphasis)

Abbreviation: abbreviation of anchor [ˈæŋkə(r)] Basic explanation anchor, iron anchor

Creating a hyperlink in HTML is as simple as wrapping a tag around the object to be linked. The basic syntax is as follows:

<a href="Jump target" target="Target window popup mode">Text or image</a>
Copy the code

Href: The URL used to specify the target of the link. When the href attribute is applied to the tag, it acts as a hyperlink. Short for Hypertext Reference. It means hypertext reference

Target: specifies the opening mode of the linked page. The value can be _self or _blank. _self is the default value, and _blank is the opening mode in a new window.

Note:

  1. == For external links == You need to add http:// www.baidu.com

  2. < a href=”index.html”

  3. == If there is no target ==, the href value of the link tag is usually defined as “#” (href=”#”), indicating that the link is temporarily empty.

  4. == Hyperlinks can be created not only in text, but also in various webpage elements ==, such as images, tables, audio, video, etc.

Anchor location (difficult point)

By creating anchor links, users can quickly locate the target content. There are two steps to creating an anchor link:

1. Use "a href=" #id name >"</a>Create link text (clicked)<a href="#two">2. Use the corresponding ID name to mark the location of the target.<h3 id="two">2 sets</h3> 
Copy the code

Base tag Basic

Base can set the open state of the overall link

Base between writes

Add target=”_blank” to all connections by default

Comment tags

There is also a special kind of tag in HTML – the comment tag. If you need to add comment text to an HTML document that is easy to read and understand but does not need to be displayed on the page, you need to use comment tags. The basic syntax is as follows:

    <! -- Comment statement -->CTRL + / or CTRL + Shift + /Copy the code

The comment content is not displayed in the browser window, but is also downloaded to the user’s computer as part of the content of the HTML document and can be seen when viewing the source code.

Path (key points, difficult points)

In practice, a new folder is usually created for storing image files, and then the image is inserted, the way of “path” is used to specify the location of the image file.

Root Directory Current directory

Paths can be classified into relative paths and absolute paths

Relative paths

The directory path created based on the location of the page referencing the file. Therefore, when web pages saved in different directories reference the same file, they use different paths, so they are called relative paths.

  1. Image files and HTML files are in the same folder: just enter the name of the image file, such as .
  2. The image file is located in the next folder of the HTML file. Enter the folder name and file name separated by a slash (/), for example, .
  3. Image files are in the folder one level above the HTML file: Add “.. “before the file name. / “, for the upper two levels, use “.. /.. / “, and so on, such as .

An absolute path

Absolute path Directory path based on the root directory of the Web site. Absolute means that when all web pages refer to the same file, they use the same path

“D: \ web \ img \ logo.gif”, or the complete network address, such as “www.itcast.cn/images/logo…

List tag (Javaweb exam will do)

What is a list?

A container contains a form of text or chart called a list.

The best thing about lists is that they are neat, clean, and organized

Unordered list ul (emphasis)

Items in an unordered list are juxtaposed rather than ordered. The basic syntax is as follows:

<ul>
  <li>List item 1</li>
  <li>List item 2</li>
  <li>List item 3</li>.</ul>
Copy the code

For example, the following news is not in order, no queue, first come, first served, first published first displayed.

Watch your step:

1. <ul></ul> can only nest <li></li>. It is not allowed to directly input other tags or characters in <ul></ul> tags. 2. A container between <li> and </li> can contain all elements. 3. Unordered lists have their own style attribute, drop that style and let CSS do it later!Copy the code

Ordered List OL (Understand)

An ordered list is a list with an order, and its items are defined in a certain order. The basic syntax of an ordered list is as follows:

<ol>
  <li>List item 1</li>
  <li>List item 2</li>
  <li>List item 3</li>.</ol>
Copy the code

All features are basically consistent with UL.

Ol img SRC =”media/1.jpg” />

Custom lists (Understood)

Defining lists are often used to explain and describe terms or nouns without any bullet in front of the list item. The basic syntax is as follows:

<dl>
  <dt>Noun 1</dt>
  <dd>Explanation 1</dd>
  <dd>Explanation 2</dd>.<dt>Term 2</dt>
  <dd>Noun 2 Explanation 1</dd>
  <dd>Explanation 2</dd>.</dl>
Copy the code

Link trivia

<! DOCTYPEhtml>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<base  target="_blank" />
	<! Add target="_blank" -->
</head>
<body>Links:<a href="https://www.videos.com/">huohuo</a>
	<a href="http://www.baidu.com">baidu</a>
	<a href="http://www.baidu.com">sina</a>
	<a href="http://www.baidu.com">sohu</a>
	<a href="http://www.baidu.com" target="_self">Google</a>
</body>
</html>
Copy the code

Form Label (※)

concept

The purpose of the form is to collect user information.

In our web pages, we also need to interact with users and collect user data, and we also need forms.

In HTML, a complete form usually consists of three parts: form controls (also known as form elements), prompts, and form fields.

For example, when we register users, we include:

  1. Form controls:

Contains specific form function items, such as single-line text entry box, password entry box, check box, submit button, reset button, etc.

  1. Prompt message: A form usually also contains some descriptive text that prompts the user to fill in and perform actions.
  2. Form fields:

It acts as a container for all form controls and prompts, and defines the URL address of the application used to process the form data, as well as the method of submitting the data to the server. If you do not define a form field, the data in the form cannot be sent to the backend server.

Input control (emphasis)

Input Meaning of input

In the syntax above, the <input /> tag is a single tag, and the type attribute is its most basic attribute type, which has multiple values and is used to specify different control types. In addition to the type attribute, the <input /> tag can define many other attributes, and the common attributes are listed in the following table.

Type tells you what form radio belongs to and if it’s a group, we have to give them the same name name so we can pick one of them

Label Label (Understood)

The label tag defines the annotation (label) for the input element.

What it does: Binds a form element that gets input focus when the label label is clicked

How do you bind elements?

The for attribute specifies which form element label is bound to.

<label for="male">Male</label>
<input type="radio" name="sex" id="male" value="male">
Copy the code

Textarea control (text field)

The text field can only write one line of text

Textarea text field

The <textarea></textarea> tag is used if you need to enter a lot of information ==. The textarea control makes it easy to create a multi-line text input box with the following basic syntax:

<textarea cols="Number of characters per line" rows="Number of rows displayed">The text content</textarea>
Copy the code

Take the comment box for example

The drop-down menu

The basic syntax for defining a drop-down menu using the Select control is select

<select>
  <option>Option 1</option>
  <option>Option 2</option>
  <option>Option 3</option>.</select>
Copy the code

Note:

  1. should contain at least one pair of.
  2. When ==selected =” selected “is defined in option, the current item is the default ==.

Form fields

In HTML, the form tag is used to define the form field, that is, to create a form for the collection and delivery of user information, and all content in the form is submitted to the server. The basic syntax for creating a form is as follows:

<form action="Url" method="Method of Submission" name="Form name">Various form controls</form>
Copy the code

Common attributes:

  1. The Action attribute is used to specify the URL of the server program that receives and processes the form data.
  2. Method Sets the method for submitting form data. The value can be GET or POST.
  3. Name is used to specify the name of the form to distinguish multiple forms on the same page.

Note:

Each form should have its own form field.

Case by destiny

<! DOCTYPEhtml>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Marriage by Destiny</title>
</head>
<body>
	<table width="600" border="0" cellspacing="0" cellpadding="0" align=center>
		<caption><h4  style="color: pink; font-size: 25px;">You and I were meant to be</h4> </caption>
		<tr height="30"> 
			<td>Name:</td>
			<td><input type="text" value="Fang" style="color:#ccc;" /> </td>
		</tr>
		<tr height="30"> 
			<td>Location:</td>
			<td><input type="text" value="Cangzhou Qingxian" style="color:#ccc;" /> </td>
		</tr>
		<tr height="30"> 
			<td>Telephone No. :</td>
			<td><input type="text" value="13785662655" style="color:#ccc;" /> </td>
		</tr>

		<tr height="30"> 
			<td>User name:</td>
			<td><input type="text" value="XiZi" style="color:#ccc;" /> </td>
		</tr>
		<tr height="30"> 
			<td>password</td>
			<td><input type="password" value="" style="color:#ccc;" /> </td>
		</tr>

			<! -- Below is the age -->
		<tr height="30">
			<td>Date of birth</td>
			<td>
				<select name="" id="">
					 <option value="">Select the year</option>  <! -- option -->
					 <option value="">1990</option>  <! -- option -->
					 <option value="">1991</option>  <! -- option -->
					 <option value="">1992</option>  <! -- option -->
					 <option value="">1993</option>  <! -- option -->
					 <option value="">1994</option>  <! -- option -->
					 <option value="">1995</option>  <! -- option -->
					 <option value="">1996</option>  <! -- option -->
					 <option value="">1997</option>  <! -- option -->
				</select>
				<select name="" id="">
					 <option value="">Select month</option>  <! -- option -->
					 <option value="">In January,</option>  <! -- option -->
					 <option value="">In February,</option>  <! -- option -->
					 <option value="">In march,</option>  <! -- option -->
					 <option value="">In April,</option>  <! -- option -->
					 <option value="">In may,</option>  <! -- option -->
					 <option value="">In June,</option>  <! -- option -->
					 <option value="">In July,</option>  <! -- option -->
					 <option value="">In August,</option>  <! -- option -->
					 <option value="">In September,</option>  <! -- option -->
					 <option value="">In October,</option>  <! -- option -->
					 <option value="">In November,</option>  <! -- option -->
					 <option value="">In December,</option>  <! -- option -->
				</select>

			</td>
		</tr>
			<! -- Where do you come from?
		<tr height="30">
			<td>Native place</td>
			<td>
				<select name="" id="">
					 <option value="">Native place</option>  <! -- option -->
					 <option value="" selected="selected">cangzhou</option>  <! -- option -->
					 <option value="">Harbin</option>  <! -- option -->
					 <option value="">Qingdao</option>  <! -- option -->
					 <option value="">dalian</option>  <! -- option -->
				
				</select>
				
			</td>
		</tr>

		<tr height="30">
			<td>gender</td>
			<td style="color: blue;">
				<input type="radio"  name="sex"  checked="checked"/><input type="radio" name="sex"  /><input type="radio" name="sex"/>transvestite</td>
			
		</tr height="30">
		<tr>
			<td>Your Favorite type</td>
			<td>
				  <input type="checkbox" name="love">enchanting<input type="checkbox" name="love">temperament<input type="checkbox" name="love">Hippies in soft<input type="checkbox" name="love" checked="checked" />Call HuLuLu</td>
			
		</tr>

		<tr height="30">
			<td>Upload the picture</td>
			<td>
				<input type="file" >
				
			</td>
			
		</tr>
		<tr height="60">
			<td>Give me a message</td>
			<td>
				<textarea name="" id="" cols="50" rows="10" style="color: #ccc;">Rich text is not supported</textarea>
				
			</td>
			
		</tr>
		<tr>
			<td></td>
			<td>
				<input type="button" value="Registered">
				<input type="submit" value="Submit">
				<input type="reset" value="Reset">
			</td>
		</tr>	
	</table>
</body>
</html>
Copy the code

2. CSS knowledge – web beautician

CSS saved the chaos of HTML and saved us web developers even more. Make our webpage more colorful.

The greatest contribution of CSS is that it takes the styling out of HTML and allows it to focus on structural rendering. With CSS, you can go to sleep!

CSS first

Cascading Style Sheets ==CSS(Cascading Style Sheets

CSS, commonly referred to as CSS style sheets or cascading style sheets (cascading style sheets), is mainly used to set the text content (font, size, alignment, etc.), image shape (width and height, border style, margins, etc.), and layout of the layout of the HTML page.

Based on HTML, CSS provides rich functions such as font, color, background control and overall layout, and can be set to different styles for different browsers.

Introducing CSS stylesheets (write location) (Required)

Internal style sheet

Inline is to write the CSS code in the HEAD tag of an HTML document and define it with the style tag. The basic syntax format is as follows:

<head>
<style type="text/CSS">Selector {property1: attribute values1; attribute2: attribute values2; attribute3: attribute values3; }</style>
</head>
Copy the code

In syntax, the style tag usually comes after the title tag in the head tag, or it can be placed anywhere in an HTML document.

Type =”text/CSS” in HTML5 can be omitted, write is also more in accordance with the specification, so this can be omitted.

Inline style (inline style)

Inline style, also known as inline style, line style, inline style. The style attribute of the tag is used to set the style of the element. The basic syntax is as follows:

< p style=" margin-top: 1em; margin-bottom: 1em; Attribute 2: Attribute value 2; Attribute 3: Attribute value 3; > Content </ tag name >Copy the code

In syntax, style is an attribute of the tag. In fact, any HTML tag has the style attribute, which is used to set inline types. Attributes and values are written in the same way as CSS style rules. Inline types only apply to the tag and nested child tags.

External style sheets (external chain)

Chain – in is to put all the styles in one or more. The link tag is used to link the external style sheet file with CSS extension to the HTML document. The basic syntax format is as follows:

<head>
  <link href="CSS file path"  rel="stylesheet" />
</head>
Copy the code

Review: Link is a single tag

In this syntax, the link tag needs to be placed in the head header tag, and three attributes of the link tag must be specified as follows:

  1. Href: Defines the URL of the linked external stylesheet file, which can be relative or absolute.
  2. Type: Defines the type of the linked document. In this case, it must be text/CSS, indicating that the linked external file is a CSS style sheet.
  3. Rel: Defines the relationship between the current document and the linked document, in this case specifying “stylesheet” to indicate that the linked document is a stylesheet file.

Summary of three stylesheets (location)

The stylesheet advantages disadvantages usage Control range
Inline style sheets Easy to write, high weight No separation of style and structure is implemented less Control a label (less)
Internal style sheet Some structure and style are separated Not completely separated more Control a page (middle)
External style sheets Complete separation of structure and style Need to introduce Most, highly recommended Control the entire site (multiple)

CSS style rules

When using HTML, you need to follow certain specifications. CSS is the same, in order to skillfully use CSS to modify the web page, first need to understand the CSS style rules, the specific format is as follows:

In the style rule above:

1. The selector is used to specify the CSS style applied to the HTML object. The curly braces are the specific style applied to the object. 2. Attributes and attribute values are displayed in key-value pairs. 3. Properties are style properties set for a specified object, such as font size, text color, etc. 4. Attribute and attribute value are connected by colons (:). 5. Use English “; “between multiple” key-value pairs “. Make a distinction. Can use paragraph and table alignment demonstration.

Outside the chain case

Within the chain case

<! DOCTYPEhtml>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<style>
		h4 {
			color: deeppink;
		}
		p {
			color: # 036;
		}
		h3 {
			color: green;
		}
		div {
			color: orange;
		}
	
	</style>
	<link rel="stylesheet" href="css/style.css">
</head>
<body>
<h3>Yi jiangnan (1)</h3>

<div>Tang Bai Juyi</div>

<p>Jiangnan is good, the scenery was once well versed. (2) sunrise river bonus fire, spring to the river green as blue, (3) can not remember jiangnan.</p>

<h4>The authors introduce</h4>

<p>Bai Juyi (772-846), courtesy name Letian, was born in Taiyuan (now in Shanxi Province). Jin Shi of The Tang Dezong Dynasty, in the third year of yuan He (808), he paid homage to Zuo and collected relics, then he was demoted to Jiangzhou (today's Jiangxi) Sima, moved to Zhongzhou (today's Sichuan), and then to Suzhou (today's Jiangsu), Tongzhou (today's Shaanxi Dali). Late in Luoyang, since the number drunk Yin Sir, Xiangshan lay. His poems have clear political tendency, heavy allegory, still easy, for everyone in the Middle Tang Dynasty. He was also one of the best poets in the early times and had a great influence on the later generations.</p>

<h4>annotation</h4>
<p>(1) According to Yuefu Miscellaneous Records, this word is also known as Xie Qiuniang, written by Li Deyu of tang Dynasty for xie Qiuniang, the deceased concubine. Also known as "Hope jiangnan", "Dream Jiangnan" and so on. Points monotonous, double tone two body. Monotone 27 words, double depth 54 words, all flat rhyme. (2) Familiarity: familiarity. (3) Blue: blue grass, its leaves can be made into green dye.</p>
<h4>tasting</h4>

<p>The first sentence of this poem, "Jiangnan is good", captures all the beauty of the spring scenery in the south of the Yangtze River with a simple and round word "good", and the author's praise and yearning feelings are also included in it. At the same time, only because of "good" of already very, can "recall" of endless, therefore, this sentence has already dark tease conclusion sentence "can not recall jiangnan", and it is related to. The second sentence, "The scenery used to be familiar", points out that the "good" scenery of jiangnan is not a rumor, but the author's personal experience and personal feelings when he was out of Hangzhou. This not only implements the word "good", but also takes care of the word "memory", which can yet be regarded as a wonderful pen and ink to connect the pulse of a meaning. The third and fourth sentences vividly illustrate the "good" development of jiangnan, highlighting the bright and brilliant colors of jianghua and river red and green, giving people a strong impression of brilliance. Among them, there are not only mutual contrast between the same color, but also mutual contrast between different colors, which fully shows the author is good at coloring skills. At the end of the chapter, the whole poem "Can not remember the Jiangnan", which not only relies on the author born in Luoyang's infinite admiration and nostalgia for the spring scenery of Jiangnan, but also creates a long and profound lasting appeal, bringing readers into the realm of lingering feelings.</p>
</body>
</html>
Copy the code

Four basic selectors for CSS

Label selector (element selector)

Label selector refers to the use of HTML label name as a selector, according to the label name classification, for a certain type of label in the page to specify a unified CSS style. The basic syntax is as follows:

Tag name {attribute1: attribute values1; attribute2: attribute values2; attribute3: attribute values3; } or the element name {attribute1: attribute values1; attribute2: attribute values2; attribute3: attribute values3; }
Copy the code

The biggest advantage of tag selectors is that they can quickly style the same type of tags on a page, but this is also their disadvantage, they can’t design different styles.

The tag selector can select all of the tags of a particular type ==div span==

Class selectors

Class selectors use “. (English dot), followed by the class name. The basic syntax is as follows:

.class name {attribute1: attribute values1; attribute2: attribute values2; attribute3: attribute values3; }
Copy the code
Class = "class name";Copy the code

The biggest advantage of class selectors is that you can define separate or identical styles for element objects. You can select one or more labels

1. Long names or phrases can be named using a dash for the selector.2It is not recommended to name CSS selectors with the underscore "_".Copy the code
Press shift one less while typing;Copy the code

Browser compatibility issues (such as using selector naming for _tips, which is not valid in IE6) can distinguish JavaScript variable naming (JS variable names are “_”)

3Do not use pure numbers, Chinese and other names, try to use English letters to express.Copy the code

Class selector small case

<! DOCTYPEhtml>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<style>
	/*div {div tag selector change all div selections to red color: red; } * /
	/* class calls */
	.leixuanzeqi{
		color: blue;
	}
	</style>
</head>
<body>
	<div class="leixuanzeqi">I'm a class selector</div>
	<div>I'm a class selector</div>
	<div>I'm a class selector</div>
	<div>I'm a class selector</div>
	<div>I'm a class selector</div>
	<div class="leixuanzeqi">I'm a class selector</div>
</body>
</html>
Copy the code

Make a simple Google icon

<! DOCTYPEhtml>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<style> /* Don't forget it */
		span {  /* The label selector makes all spans 150 */
			font-size: 150px;
		}
		.g { 
			color: blue;
		}
		.o {
			color: red;
		}
		.o2 {
			color: orange;
		}
		.l {
			color: green;
		}
	/* Class selectors can select one or more labels */
	</style>
</head>
<body>
	<span class="g">G</span>
	<span class="o">o</span>
	<span class="o2">o</span>
	<span class="g">g</span>
	<span class="l">l</span>
	<span class="o">e</span>
	<div class="nav"></div>  <! -- Navigation our customary convention -->
	<div class="banner"></div>  <! -- Navigation our customary convention -->
</body>
</html>
Copy the code

Multiclass name selector

We can assign more than one class name to the tag to make more choices.

Note:

  1. The style display has nothing to do with the order of the class name in the HTML element, but with the order in which the CSS style is written.
  2. Each class name is separated by a space.

Multi-class name selectors are often used when the layout is complex.

<div class="pink fontWeight font20">Arthur</div>
<div class="font20">Liu bei</div>
<div class="font14 pink">Ann is the</div>
<div class="font14">The sable cicada</div>
Copy the code

case

<! DOCTYPEhtml>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Multiclass name selector</title>
	<style>
	 .red {
	 	color: red;
	 }
	 .font20 {
	 	font-size: 20px;
	 	color: blue;
	 }
	 .fontw {
	 	font-weight: 700;
	 }
	</style>
</head>
<body>
	<div class="font20 red fontw">Multiclass name selector</div>
	<p class="red fontw" >Multiclass name selector</p>
	<p>Multiclass name selector</p>
	<p class="red">Multiclass name selector</p>
	<div>Multiclass name selector</div>
</body>
</html>
Copy the code

The id selector

The id selector is identified by “#”, followed by the id name, and its basic syntax is as follows:

#idName {properties1: attribute values1; attribute2: attribute values2; attribute3: attribute values3; }
Copy the code

In this syntax, the ID name is the ID attribute value of an HTML element. Most HTML elements can define the ID attribute. The ID value of an element is unique and can only correspond to a specific element in the document.

The usage is basically the same as the class selector.

Just like an ID card, the name is the class name selector and the ID number is the ID selector

Id and class selectors are different

The W3C standard states that id objects with the same name are not allowed on the same page, but classes with the same name are allowed.

A class selector is like a person’s name, which can be used repeatedly, such as Zhang Wei, Wang Wei, Li Wei, Li Na

Id selector is like the id number of people, the whole Of China is unique, shall not be repeated. Can only be used once.

The biggest difference between id selectors and class selectors is the number of times == is used.

case

<! DOCTYPEhtml>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<style>
	#last {
		color: pink;
	}
	</style>
</head>
<body>
	<div>The id selector</div>
	<div>The id selector</div>
	<div>The id selector</div>
	<div id="last" class="red">The id selector</div>
</body>
</html>
Copy the code

Wildcard selector

Wildcard selectors, represented by *, are the broadest of all selectors, matching all elements on a page. The basic syntax is as follows:

* {properties1: attribute values1; attribute2: attribute values2; attribute3: attribute values3; }
Copy the code

For example, the following code uses a wildcard selector to define CSS styles that clear the default margins for all HTML tags.

* {
  margin: 0;                    /* Define the margin */
  padding: 0;                   /* Define the inner margin */
}
Copy the code

case

<! DOCTYPEhtml>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<style>* {*/** indicates that the meaning of all tags is used less */
		color: red;
	 }
	</style>
</head>
<body>
	<div>I am a label</div>
	<p>I am a paragraph</p>
	<span>I am a label</span>
	<table>I am form</table>
</body>
</html>
Copy the code

3. Knowledge of JavaScript

JavaScript is introduced

What is the JavaScript

JavaScript programming language flow control

Netscape originally named its scripting language LiveScript, which Netscape later renamed JavaScript after partnering with Sun. JavaScript was originally designed to be Inspired by Java, in part to “look like Java,” so there are syntactic similarities, and some names and naming conventions are borrowed from Java. The similarity between JavaScript and Java names was the result of an agreement Netscape struck with Sun Microsystems for marketing purposes at the time. The relationship between Java and JavaScript is like that between Zhang Yu and Zhang Yusheng, only the names are similar.

==Java server-side programming language ==

== The programming language in which JavaScript is run on the client (browser) ==

JavaScript is a kind of scripting language that runs on the client side. The interpreter of JavaScript is called JavaScript engine, which is part of the browser. It is widely used in the client side scripting language, first in HTML (an application under the Standard Common Markup Language) web page. Used to add dynamic functionality to HTML pages.

[img-fap5ubjr.1594811136860] (media/bulaideng.png)

The original purpose of JavaScript

Presentation: baixiu.uieee.com/admin/login… The original purpose was to handle form validation.

What JavaScript means now (Application Scenario)

JavaScript has evolved to do almost anything.

  1. Web page special effects
  2. Server-side development (Node.js)
  3. Command line tool (Node.js)
  4. Desktop Program (Electron)
  5. App(Cordova)
  6. Control Hardware – Internet of Things (Ruff)
  7. Game Development (Cocos2D-JS)

The difference between JavaScript and HTML and CSS

  1. HTML: Provides the structure and content of a web page
  2. CSS: Used to beautify web pages
  3. JavaScript: Can be used to control the content of a web page, adding a dynamic effect to a web page

The composition of JavaScript

Outside the chain picture archiving failure, the source station might be hotlinking prevention mechanism, proposed to directly upload picture preserved (img – esS9LcoN – 1623498246606) (.. / AppData/Roaming/Typora/Typora – user – images / 162341410559 4.png)]

function

What is a function

A relatively independent code block with a specific function is encapsulated to form an independent entity, that is, a function, given a name (function name), in the subsequent development can be repeatedly called

The function encapsulates a piece of code that can be reused in the future

Definition of a function

  • Function declaration
functionThe function name (){
  / / the function body
}
Copy the code
  • Functional expression
var fn = function() {
  / / the function body
}
Copy the code
  • Features:

    When a function is declared, the function body is not executed, only when the function is called. A function is usually used to do one thing. It needs to use a verb + a noun to say to do one thing

Function call

  • Syntax for calling a function:
The function name ();Copy the code
  • Features:

    The function body is executed only when called, which requires () to be called. Can be called multiple times (reuse)

Code examples:

// Declare the function
function sayHi() {
  console.log("Have you eaten?");
}
// Call the function
sayHi();

// Find the sum of all numbers between 1 and 100
function getSum() {
  var sum = 0;
  for (var  i = 0; i < 100; i++) {
    sum += i;
  }
  console.log(sum);
}
/ / call
getSum();
Copy the code

Parameters of a function

  • Why have parameters
function getSum() {
  var sum = 0;
  for (var i = 1; i <= 100; i++) {
    sum += i;
  }
  console.log();
}

// Although the above code can be called repeatedly, it only computes values between 1 and 100
// If I want to calculate the sum of all numbers between n and m, what should I do?
Copy the code
  • Grammar:
// The inside of a function is a closed environment in which values from the outside can be passed to the inside of the function as arguments
// Function declaration with arguments
functionThe function name (parameter1The parameter2, parameter...){
  / / the function body
}

// Function call with argumentsFunction name (argument1That argument2That argument3);
Copy the code
  • Parameters and arguments

    1. Formal parameters: When declaring a function, some values cannot be fixed for the purpose of making the function more flexible. We can set parameters to the function. This parameter, which has no value and only serves as a placeholder, is often called a formal parameter, also known as a parameter.
    2. Actual parameters: If a function is declared with a parameter, then the function is called with the corresponding parameter, we call the actual parameter, also called the argument.
var x = 5, y = 6;
fn(x,y); 
function fn(a, b) {
  console.log(a + b);
}
// the x,y arguments have specific values. When the function is executed, it copies x and y to a and B inside the function. The internal values of the function are the copied new values, and the external x and y cannot be modified
Copy the code

The return value of the function

When the function is finished, it is not always necessary to print the result. We expect the function to give me some feedback (such as the result of the calculation to be returned for subsequent operations), and then we can ask the function to return something. That’s the return value. The function returns a return value via return

Return value syntax:

// Declare a function with a return value
functionThe function name (parameter1The parameter2, parameter...){
  / / the function body
  returnThe return value. }// The return value can be received via a variable
varVariable = function name (argument1That argument2That argument3);
Copy the code

The result of the function call is the return value, so we can operate directly on the result of the function call.

Return value:

  • If a function does not display a return statement, the function has a default return value: undefined
  • If a function uses a return statement, the value following the return statement becomes the return value of the function
  • If a function uses a return statement, but there is no value after return, the function returns undefined
  • When a function uses a return statement, the function stops and exits immediately after the return statement is executed, meaning that all other code following the return statement is not executed.

It is recommended that the function either always return a value or never return a value at all.

ArgumentargumentargumentArgumentArgumentArgumentargumentargumentargumentarguments

In JavaScript, the Arguments object is a special object that is actually a built-in property of the current function. That is, all functions come with a built-in arguments object, which stores all arguments == passed. Arguments == is a pseudo-array, so arguments can be iterated over ==

  • case
Take the sum of any numberCopy the code
<! DOCTYPE html><html lang="en">
<head>
  <meta charset="UTF-8">
  <title>$forever 24K pure handsome $</title>
  <script>

    // Calculate the sum of two numbers
// function f1(x, y) {
// return x + y;
/ /}
// // calculate the sum of three numbers
// function f2(x, y, z) {
// return x + y + z;
/ /}
// // calculate the sum of four numbers
// function f3(x, y, z, k) {
// return x + y + z + k;
/ /}
// // calculate the sum of five numbers
// function f4(a, b, c, d, e) {
// return a + b + c + d + e;
/ /}
// // calculate the sum of six numbers
// function f5(a, b, c, d, e, f) {
// return a + b + c + d + e + f;
/ /}
    // Compute the sum of n numbers
    // Define a function. If you are not sure whether the user passed in arguments, or if you do not know how many arguments the user passed in, you cannot calculate, but if you know the number of arguments in the function, you also know the value of each argument. can

    / / define
// function f1() {
// // gets several arguments passed in when the function is called
// //console.log(arguments.length);
// // uses the Arguments object to get the value of each argument passed in
// console.log(arguments);
/ /}
//
/ / f1 (10,20,30,40,100,200); / / call



    function f1() {
      //arguments-----> array use ------ pseudo-array --
      var sum=0;
      for(var i=0; i<arguments.length; i++){ sum+=arguments[i];
      }
      return sum;
    }

    console.log(f1(10.20.30));
  </script>
</head>
<body>


</body>
</html>
Copy the code

Function other (if you have time to understand)

Anonymous functions

Anonymous functions: Functions that have no name

How to use anonymous functions:

Assign an anonymous function to a variable so that you can call an anonymous function from the variableCopy the code

On the role of self-executing functions (anonymous function self-calls) : to prevent global variable contamination.

Self-calling function

Anonymous functions cannot be executed by calling them directly, so they can be executed by calling them themselves

(function () {
  alert(123); }) ();Copy the code

A function is a data type

function fn() {}
console.log(typeof fn);
Copy the code
  • Function as argument

Because a function is a type, you can call a function as an argument to two functions

  • Function as the return value

Because a function is a type, it is possible to return a function as a return value from within the function, which is common later on.

function fn(b) {
  var a = 10;
  return function () {
    alert(a+b);
  }
}
fn(15) ();Copy the code

Code specification

1.Naming conventions2.Variable specificationvar name = 'zs';	
3.Annotation specifications// Here is a comment
4.The space specification5.Newline specificationvar arr = [1.2.3.4];
if (a > b) {

}
for(var i = 0; i < 10; i++) {

}
function fn() {}Copy the code

Windows object, Document object (most important)

Knowledge is too miscellaneous, here to see the teacher PPT on the line

JavaWeb knowledge

JDBC book does not see here, the rest of the book has, the rest of the knowledge point, do after class questions

Supplement: knowledge, the remaining Javaweb yangyongli.blog.csdn.net/article/det…


The official reference documentation: docs.oracle.com/javase/tuto… The following code example links: download.csdn.net/download/we…


1. Introduction to JDBC

1.1 Client Operation Methods of the MySQL Database:

Use third-party clients to access MySQL: SQLyog, Navicat, SQLWave, MyDB Studio, EMS SQL Manager for MySQL

Use the MySQL command line interface (CLI) and Java to access the MySQL database

1.1.1 What is JDBC

JDBC specification definition == interface ==, the specific implementation by the major database vendors to achieve.

JDBC is the standard specification for Java to access a database. How to operate a database really requires a specific implementation class, that is, == database driver ==. Each database vendor writes its own database driver according to its own database communication format. So we only need to be able to call the JDBC interface method, == database driver provided by the database vendor ==.

Benefits of using JDBC:

  1. Programmers who want to develop programs that access databases simply need to be able to call methods in the JDBC interface, regardless of how the class is implemented.
  2. Other JDBC-supported databases can be accessed using the same set of Java code with a few modifications

1.1.2 Packages used for JDBC Development:

Packages that will be used instructions
java.sql All interfaces and classes related to JDBC access to the database
javax.sql Database extension pack that provides additional database functionality. For example, connection pool
Database driver Provided by major database vendors, additional downloads are required to implement the JDBC interface class

1.2 JDBC core API

Interface or class role
DriverManager class 1. Manage and register database drivers 2. Obtain database connection objects
Connectioninterface A connection object that can be used to create Statement and PreparedStatement objects
Statement interface An SQL statement object used to send SQL statements to the database server.
PreparedStatemeninterface An SQL Statement object that is a subinterface to a Statement
ResultSet interface Used to encapsulate the result set of a database query and returned to the client Java program

1.3 Importing the Driver Jar Package

1.4 Loading and Registering the driver

Methods to load and register drivers describe
Class.forName(Database driven implementation class) Load and register the database Driver from the mysql vendor — “com.mysql.jdbc.driver”

Registration driver code:

public class Demo1  {
	public static void main(String[] args) throws ClassNotFoundException {
		// Throw an exception that the class cannot find, register the database driver
		Class.forName("com.mysql.jdbc.Driver"); }}Copy the code

Com.mysql.jdbc.driver source code:

// The Driver interface, which all database vendors must implement, represents a Driver class.
public class Driver implements java.sql.Driver { 
	public Driver(a) throws SQLException {}static { 
		try {
			DriverManager.registerDriver(new Driver());   
			// Register the database driver
		} 
		catch (SQLException var1) {
			throw new RuntimeException("Can't register driver!"); }}}Copy the code

Note: starting with JDBC3, the version that is currently in common use. Can be used directly without registering the driver. The sentence class.forname can be omitted.

2. The DriverManager class

2.1 DriverManager role:

1) Manage and register drivers 2) create database connections

2.2 Methods in class:

Static method in the DriverManager class describe
Connection getConnection (String url, String user, String password) Get the database connection object from the connection string, username, and password
Connection getConnection (String url, Properties info) Get the connection object from the connection string, property object
Use JDBC to connect to a database.
Four parameters for JDBC to connect to a database instructions
————————- ————————————————————
The user name User name for logging in
password Login password
Connection string URL Mysql > select * from ‘mysql’;JDBC: mysql: / / localhost: 3306 / database [?] parameter name = parameter values
The string name of the driver class com.mysql.jdbc.Driver
Mysql > connect to database
Protocol name: Sub-protocol :// Server name or IP address: port number/database name? Parameter = Parameter value
### 2.4.1MySQL

2.4.2MySQL:

Prerequisite: The server must be local and the port number is 3306

jdbc:mysql:/// Database name
Copy the code

2.4.3 Processing garbled characters

If the database is garbled, you can specify the following argument:? CharacterEncoding = UTF8, which means that the database processes the data in UTF-8 encoding.

jdbc:mysql://localhost:3306 characterEncoding=utf8
Copy the code

2.5 Case: Obtain the MySQL database connection object

2.5.1 Using the user name, password, and URL to obtain the connection object

package com.sqltest; 
import java.sql.Connection;
import java.sql.DriverManager; 
import java.sql.SQLException;

/** * get the connection object */
public class Demo2 {
    public static void main(String[] args) throws SQLException 
    { 
	    String url = "jdbc:mysql://localhost:3306/day24";
		//1) Use username, password, URL to get the connection object
        Connection connection = DriverManager.getConnection(url, "root"."root");
		//com.mysql.jdbc.JDBC4Connection@68de145System.out.println(connection); }}Copy the code

2.5.2 Use properties file and URL to get connection object

package com.sqltest;

import java.sql.Connection; 
import java.sql.DriverManager; 
import java.sql.SQLException;
import java.util.Properties;

public class Demo3 {
    public static void main(String[] args) throws SQLException {
		// Url connection string
        String url = "jdbc:mysql://localhost:3306/day24";
		// Attribute object
        Properties info = new Properties();
		// Put the username and password in the info object

        info.setProperty("user"."root"); 	
        info.setProperty("password"."root");
        Connection connection = DriverManager.getConnection(url, info);
		//com.mysql.jdbc.JDBC4Connection@68de145 System.out.println(connection);}}Copy the code

3. Connection:

3.1 Connection Function:

The Connection interface, whose concrete implementation class is implemented by the vendor of the database, represents a Connection object.

3.2 Connection method:

Methods in the Connection interface describe
Statement createStatement() Create an SQL statement object

4. The Statement interface

4.1JDBC Database Access Procedure

  1. Register and load drivers (can be omitted)
  2. Get connected
  3. Connection Obtains the Statement object
  4. Execute SQL statements using the Statement object
  5. Return result set
  6. Release resources

4.2 Statement Functions:

Represents a statement object that sends SQL statements to the server, executes static SQL statements and returns the results it generates.

4.3 Methods in Statement:

Method in the Statement interface describe
int executeUpdate(String sql) Used to send DML statements, add, delete, delete operations, insert, update, delete

SQL statement:

Return value: Returns the number of rows that affect the database
ResultSet executeQuery(String sql) Send DQL statements to perform query operations. select

Parameter: SQL statement

Return value: The result set of the query

4.4 Releasing Resources

  1. The following objects need to be released: ResultSet ResultSet, Statement Statement, and Connection
  2. Release principle: first open after closed, open after closed first. ResultSet  Statement  Connection
  3. Which code block to put in: finally block

4.5 Performing DDL Operations

4.5.1 Requirements: Use JDBC to create a student table in MySQL database

4.5.2 of code:


package com.itheima;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

/** * create a student table */
public class Demo4DDL {

    public static void main(String[] args) {
        //1. Create a connection
        Connection conn = null; Statement statement = null;
        try {
            conn = DriverManager.getConnection("jdbc:mysql:///day24"."root"."root");
            //2. Get the statement object from the connection object
            statement = conn.createStatement();
            //3. Use the statement object to send SQL statements to the server
/ / 4. Execute SQL
            statement.executeUpdate("create table student (id int PRIMARY key auto_increment, " + "name varchar(20) not null, gender boolean, birthday date)");
//5. Return the number of affected rows (DDL does not return a value)
		System.out.println("Table created successfully");
        } catch (SQLException e) {
            e.printStackTrace();
        }
//6. Release resources
        finally {
    // Check before closing
            if(statement ! =null) {
                try {
                    statement.close();
                } catch(SQLException e) { e.printStackTrace(); }}if(conn ! =null) { 
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
Copy the code

4.6 Performing DML Operations

Requirement: Add 4 records to student table, primary key is auto growth

Steps:

  1. Creating a connection object
  2. Create a Statement object
  3. Execute SQL statement: executeUpdate(SQL)
  4. Returns the number of affected rows
  5. Release resources

Code:

package com.sqltest;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;


/** * add 4 records to student table, primary key is auto growth */
public class Demo5DML {

    public static void main(String[] args) throws SQLException {
// 1) Create a connection object
        Connection connection = DriverManager.getConnection("jdbc:mysql:///day24"."root"."root");
// 2) Create a Statement object
        Statement statement = connection.createStatement();
// 3) Execute SQL statement:
		executeUpdate(sql) ;
		int count = 0;
// 4) Return the number of affected rows
        count += statement.executeUpdate(Insert into sc values(null, 1, '1993-03-24 ')");
        count += statement.executeUpdate(Insert into sc values(null, 0, '1995-03-24 ')");
        count += statement.executeUpdate(Insert into sc values(null, 1, '1903-03-24 ')");
        count += statement.executeUpdate(Insert into sc values(null, 'chang ', 0,' 1993-03-11 ')");
        System.out.println("Inserted." + count + "A record");
// 5) Release resourcesstatement.close(); connection.close(); }}Copy the code

4.7 Performing DQL Operations

4.7.1 the ResultSet interface:

Function: encapsulate the result set of database query, traverse the result set, take out each record.

Methods in the interface:

A method in the ResultSet interface describe
boolean next() 1) Move the cursor down 1 row

2) Return Boolean, true if there is a next record, false otherwise
The data typegetXxx() 1) By field name, the parameter is of type String. Returns different types

2) Pass the column number, the argument is an integer, starting at 1. Returns different types

4.7.2 Common Data Type Conversion table

SQL type Jdbc corresponding methods The return type
BIT(1) bit(n) getBoolean() boolean
TINYINT getByte() byte
SMALLINT getShort() short
INT getInt() int
BIGINT getLong() long
CHAR,VARCHAR getString() String
Text(Clob) Blob getClob()``getBlob() Clob Blob
DATE getDate() Java.sql.Date represents only dates
TIME getTime() Java.sql.Time indicates only the Time
TIMESTAMP getTimestamp() Java.sql.Timestamp has both date and time

Date, Time, Timestamp, java.util.Date, java.util

4.7.3 Requirements: Ensure that there are more than three records in the database, query all student information

Steps:

  1. Get the connection object
  2. Get the statement object
  3. Execute the SQL statement to obtain a ResultSet object
  4. Loop through to retrieve each record
  5. Output console
  6. Releasing resources results:

Code:

package com.sqltest;

import java.sql.*;

/** * query all student information */
public class Demo6DQL {

    public static void main(String[] args) throws SQLException {
//1) Get the connection object
	Connection connection =DriverManager.getConnection("jdbc:mysql://localhost:3306/day24"."root"."root");
//2) get the statement object
        Statement statement = connection.createStatement();
//3) Execute the SQL statement to obtain the ResultSet object
        ResultSet rs = statement.executeQuery("select * from student");
//4) Loop through to fetch each record
        while(rs.next()) {
            int id = rs.getInt("id");
            String name = rs.getString("name"); boolean gender = rs.getBoolean("gender"); Date birthday = rs.getDate("birthday");
    //5) Output console
            System.out.println("No. :" + id + Name: + name + ", gender: + gender + ", birthday:" + birthday);
        }
	    //6) Release resourcesrs.close(); statement.close(); connection.close(); }}Copy the code

4.7.4 Precautions for the ResultSet Interface:

  1. If the cursor is Before the first row, use rs.getxx () to get the column value: Before start of result set
  2. If the cursor is After the last line, use rs.getxx () to get the column value: After end of result set
  3. == Close the ResultSet, Statement, and Connection==

5. Database tool class JdbcUtils

When do you create your own utility classes?

If a feature is used frequently, we recommend making it a utility class that can be reused in different places.

5.1 requirements:

There is a lot of duplicate code in the code written above, which can be extracted from the common code.

5.2 Creating class JdbcUtil contains three methods:

  1. Several strings can be defined as constants: username, password, URL, driver class
  2. Get a connection to the database:getConnection()
  3. Close all open resources:

Close (Connection conn, Statement STMT), close(Connection conn, Statement STMT, ResultSet RS)

JdbcUtil. Java code:


package com.sqltest.utils; 
import java.sql.*;
/** * Tools to access the database */
public class JdbcUtils {

    // Several strings can be defined as constants: username, password, URL, driver class
    private static final String USER = "root"; 
    private static final String PWD = "root";
    private static final String URL = "jdbc:mysql://localhost:3306/day24";
    private static final String DRIVER= "com.mysql.jdbc.Driver";

    /** * Register driver */
    static {
        try {
            Class.forName(DRIVER);
        } catch(ClassNotFoundException e) { e.printStackTrace(); }}/** * get the database connection */
    public static Connection getConnection(a) throws SQLException {
        return DriverManager.getConnection(URL,USER,PWD);
    }

    /** * Close all open resources */
    public static void  close(Connection conn, Statement stmt) {
        if(stmt! =null) {
            try {
                stmt.close();
            } catch(SQLException e) { e.printStackTrace(); }}if(conn! =null) {
            try {
                conn.close();
            } catch(SQLException e) { e.printStackTrace(); }}}/** * Close all open resources */
    public static void close(Connection conn, Statement stmt, ResultSet rs) {
        if(rs! =null) {
            try {
                rs.close();
            } catch(SQLException e) { e.printStackTrace(); } } close(conn, stmt); }}Copy the code

5.3 Case: User Login

5.3.1 requirements:

  1. There is a list of users

  2. Add a few user records

    create table user (
    id int primary key auto_increment, 
    name varchar(20),
    password varchar(20))insert into user values (null.'jack'.'123'), (null.'rose'.'456');
    
    -- Login, SQL is case insensitive
    select * from user where name='JACK' and password='123';
    
    -- Login failed
    select * from user where name='JACK' and password='333';
    Copy the code
  3. The Statement string is used to log in to the system. The user enters the user name and password on the console.

5.3.2 steps:

  1. Get the user name and password entered from the console to query the database
  2. Write a login method

A. Use the tool class to get connections b. Create statement objects and generate SQL statements using concatenated strings C. Query the database. If there are records, the login is successful. Otherwise, the login fails

5.3.3 code


package com.sqltest;

import com.itheima.utils.JdbcUtils; 
import javax.xml.transform.Result;
import java.sql.Connection; 
import java.sql.ResultSet; 
import java.sql.SQLException; 
import java.sql.Statement; 
import java.util.Scanner;

public class Demo7Login {

    // The user name and password entered from the console
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Please enter user name:");
        String name = sc.nextLine();
        System.out.println("Please enter your password:");
        String password = sc.nextLine();
        login(name, password);

    }

    /** * The login method */
    public static void login(String name, String password) {
        //a) get the connection through the utility class
        Connection connection = null;
        Statement statement = null;
        ResultSet rs = null;
        try {
            connection = JdbcUtils.getConnection();
            //b) create statement object, use concatenation string to generate SQL statement
            statement = connection.createStatement();
            //c) Query the database. If there are records, the login is successful; otherwise, the login fails
            String sql = "select * from user where name='" + name + "' and password='" + password + "'";
            System.out.println(sql);
            rs = statement.executeQuery(sql);

            if (rs.next()) {
                System.out.println("Login successful, welcome to:" + name);
            }
            else {
                System.out.println("Login failed"); }}catch (SQLException e) {
            e.printStackTrace();
        } finally {
            //d) Release resourcesJdbcUtils.close(connection, statement, rs); }}}Copy the code