JAVAWEB-NOTE02

Cool breeze AAA 2022-02-13 07:37:26 阅读数:973

javaweb-note02 javaweb note

1. JavaScript

1.1 JavaScript brief introduction

1.1.1 What is? JavaScript( understand )

The full name is JavaScript, It's called JS ( Follow java Do not have what relation , Maybe the grammar is similar )

from NetScape( netscape ) The company offers , It's a scripting language specifically embedded in browsers

LiveScript----->( Change of name ) JavaScript

JS Run in browser **, Responsible for the animation effect in the web page **

Or is it Realize form verification and other functions can ( For example, whether the password is entered correctly )

js There is no prompt for mistakes .

Learning front-end can see :W3Cschoole This web site .

A back-end engineer must know js.

1.1.2 JS Features and advantages ( understand )

1、 characteristic :

(1)JS It's a door Literal translation Language ( Explain and execute , There is no compilation process )

java–> At the time of writing xx.java —> Translate it into xx.class --> function

js —> At the time of writing html, At the time of writing js file , Direct operation , No compilation process

(2)JS It's an object-based language (JS There is no concept of a class in , There is no compilation process )

JS Medium is There are objects ( Built-in objects 、 Custom object )

(3)JS It's a weak type of language (Java: Strong type ) ( Weak type : When defining a variable, you don't have to specify its type )

 stay java in : Once a variable is declared , It's a fixed data type , Can't be changed
String s = "abc";
int n = 100;
stay JS in : Variables are type insensitive , Can point to any data type
var s = 100;//number( value type )
s = "abc";//String( String type )
s = true;//boolean( Boolean type )
s = []; //object( object type )
s = function(){
} //function( object type )

2、 advantage :( understand )

(1)JS It has good interactivity ( Better user experience )

(2)JS With a certain degree of security ( Can only run inside the browser , Can't access resources outside the browser )

(3)JS Cross platform (JS browser ) , namely : Where there is a browser, you can run JS

( JS Language is cross platform , It's because there's a browser , But browsers don't cross platform

Java Language is cross platform , Because there are virtual machines , But virtual hosts don't cross platform . such as Linux and windows Of jvm The version is different )

1.1.3 stay HTML Writing JS The way ( Three )

1、 stay script The inside of the label can be written JS Code :

stay head perhaps body You can add a script label , stay script The inside of the label can be written directly JS Code ! The disadvantage is that it can only be used on the same web page . and css Only in head Inside the label .

<!-- The way 1: stay script Direct writing inside the label JS Code -->
<script> // Declare a variable str1, Assign a string value to str1 var str1 = " introduce JS The first way ..."; //document Is the object that represents the current entire web page , take str1 Output the content to the web page to display (document: file ) document.write( str1 ); </script>
// Be careful var No assignment is undefined type , It depends on the type of assignment you assign ( Undefined )

2、 adopt script The label introduces the external JS file

stay head or body The label inside , Can pass script The label introduces the external JS file . for example :

How to create a JS file :1.new–File, Change the suffix to .js 2 Ways of planting

​ 2.new—other—javeScript----javeScript SourceFile— establish .js Postfix file .

Be careful : If at the same time jquery Function class library and introduce their own js file , Need to put jquery On the front .

<!-- The way 2 adopt script Tags can introduce external JS file -->
<script src="./demo.js"></script>
src The root path
<!--./ Represents the directory where the current file is located , ./ It can be omitted ../ Represents the parent directory of the directory where the current file is located , ../ Don't omit You can also write absolute paths , The relative path is written because js The file is copied into the project . The advantage is that the project will be copied in the future js The file has also been copied , No need to change js File path .-->

Be careful :(1) In the introduction of js Of documents script Don't write inside the label JS Code , for example :

<script src="demo.js"> alert( 111 ); // The code here doesn't execute , So don't write  </script>

(2) Don't introduce JS Of documents script Label self closing , Because it may lead to file import failure , as follows :

The order in which the browser loads the web page : From top to bottom, from left to right

<script src="demo.js" />
.js file
// Declare a variable str2, And assign the string to str2
var str2 =" introduce JS The second way ";
document.write(str2); // take str2 The contents of the string are output to the string display

3, You can also write directly on the elements JS Code ** ( It's usually written in body Inside the label )

onclick: Click the mouse A method is written in the click event .

<!-- The way 3 Write directly on the element JS Code : onclick Attribute is used to bind a click event to the current element : Clicking on an element triggers an event , Execute the corresponding function (onclick: The click of a mouse ) alert() The method is a warning box , If a string is passed in , There are double quotation marks outside , There can only be single quotation marks inside . -->
<input type="button" value=" Am I ~" onclick="alert(' You dare to order it !!!')"/>
<input type="button" value=" Don't order me " onclick="console.log( new Date() )"/> //console.log() Output the incoming content to the browser console . F12 Develop this tool ---console

1.2 JavaScript grammar

1.2.1 Annotation format

JS Note symbols and Java The annotation symbol of is the same as , as follows :

// Single line comment content 
/* Multiline comment content */
js It's also case sensitive .
//js Strings can use either single or double quotation marks 

1.2.2 data type

1、 Basic data type (5 Kind of )

(1) value type (number) There is only one floating point type

stay JS in , All values are floating-point at the bottom , But in the process of processing and displaying Automatic and integer conversion .

var n=4;
for example :2.4+3.6=6// by 6 No 6.0
Special values :Infinity( infinity ) / -Infinity( Negative infinity ) / NaN( The digital )

(2) String type (string)

stay JS in , The string type belongs to the basic data type , String constants can Use single quotation marks or double quotation marks get up . for example :

var s1 = "Hello JS";
var s2 = 'Hello JS';

in addition ,JS There are corresponding wrapper objects for string types in (String), It will automatically convert to the wrapper object when needed .

var s1 = "Hello JS"; // Basic data type , string
console.log( typeof s1 ); //string typeof Returns the type of the expression 
var s2 = new String("Hello JS"); // Complex data type , object
console.log( typeof s2 ); //object Be careful o It's lowercase Return the type of data 
// Regardless of the basic data type s1, Or object type s2, Can be used as an object 
console.log( s1.valueOf() ); //s1 It's the basic data type , It turns into an object , call valueOf function 
console.log( s2.valueOf() );

String explanation

/*1. Use of quotation marks and escape characters .*/
//1). Normal string we use Single quotation marks , Or wrap it in quotes 
//2). Use of escape characters \
\` result : `
example : console.log("a\`");// Output results :a`
\n result : Line break
example : A little
\t result :tab tabs
example : A little
\u4e2d  The result is : in  (unicode character :\u####)
example :console.log("\u4e2d");// in 
\x41  The result is : in  (Ascll character )
example :console.log("\x41");// in 
/*2. String splicing .*/
1) Normal string
var name=" morning "+", Hello ";
console.log(name);// morning , Hello 
2) Template string tab above esc below
var name=` morning , Hello `;
console.log(name);// morning , Hello 
/*3. String length .*/
var str="adafaf";
console.log(str.length);//6
/*4.js String can be directly evaluated by subscript ,java Can't be java yes char Sure . The immutability of strings */
var str="adafaf";
console.log(str[0]);//a
Similarly, the bottom of the string is also final Embellished char An array of types , Once created, the length is fixed and cannot be changed .
/*5, toggle case Note that methods are not attributes */
var str="adafaf";
console.log(str.toUpperCase());// Convert to uppercase 
console.log(str.toLowerCase());// Convert to lowercase 
/*5, Get the subscript from the element */
var str="adafaf";
console.log(str.indexOf("d"));//1
/*6, Intercept the string according to the element subscript With head and no tail */
var str="adafaf";
console.log(str.substring(1,3));//da
console.log(str.substring(1));//dafaf From the subscript for 1 The last string is intercepted 

(3) Boolean type (boolean)

There are two Boolean values , Respectively true and false.

console.log(12*23>256 ?"YES":"NO");
var b1=true;

(4)undefined type ( understand )

undefined There is only one value of type , Namely undefined, Indicates that the variable is undefined ( But it's not that variables are not declared ).

A variable is declared , But there is no assignment to the variable , The default value of this variable is undefined.

/* 1.undefined type */ ( Undefined )
var x;
alert( x ); //undefined 
alert( y ); // Throw exceptions ( No statement )

(5)null type ( understand )

null There is only one value of type , Namely null, Indicates null value .

Can be the return value of a function , Indicates that the function returns an empty object .

Be careful :null and undefined Variables of type cannot call functions or properties , Would throw exceptions !

2、 Complex data type

Mainly refers to the object (JS Built in objects for 、 Custom objects 、 function 、 Array )

built-in : namely , You don't need your own new You can use it directly . //js In addition to 5 The two basic types are called objects .

1.2.3 Variable declarations

JS China is through var Keyword declaration variables , The declaration of a variable is indistinguishable , Can point to arbitrary data . for example :

Declaration does not distinguish between types , Distinguish types according to the values you assign .

var x = 100;// The number 
x = "abc";// character string 
x = true;//boolean
x = [];// Array 
x = function(){
}// function 
x = new Object(); // object 
x = {
}; // object , It's short for the above 

in addition ,JS There is no syntax error in declaring variables with the same name multiple times in , for example :

stay js A variable with the same name is declared multiple times in the , The second declaration will not take effect , It's using Override values .

Add a semicolon to every sentence , No addition js I'll break your sentence and add , It's impossible to be accurate .

commonly : Variable , Method , With () Add a semicolon to the end , With {} You don't need a semicolon at the end .

/* 2. Definition of variables */
var s = "Hello"; // var s; s="Hello";
var s = 123; // var s; s=123; Declare the variable a second time x No entry into force 
alert( s ); //123 Will overwrite the previous value 

JS It's strictly case sensitive !

js Every sentence ends with a semicolon , Not writing will help you add , But it's better to write it in case of mistakes .

1.2.4 js The variable scope of

stay js in ,var Defining variables is actually scoped .

//1. Suppose you declare... In a function , It cannot be used outside the function .( Not with : Sure " Closure " Solve )
function qj(){

var x=1;
x=x+1;
}
x=x+2;// Will report a mistake : Uncaught ReferenceError: x is not defined
//2. If 2 Two functions use the same variable name , Just inside the function , There is no conflict .
function qi(){

var x=1;
x= x=1;
}
function qi2(){

var x="A";
x= x=1;
}
//3. Internal functions can access members of external functions , Not the other way around .
function qj(){

var x=1;
function qj2(){

var y=x=1;//2
}
var z=y+1;//Uncaught ReferenceError: y is not defined
}
//4. Suppose the variables of internal function and external function , The nuptial !
function qi(){

var x=1;
function qj2(){

var x='X';
console.log('inner'+x);//outer1
}
console.log('outer'+x);//innerA
qj2();
}
qj();
Suppose that js Function , Functions look for variables from their own functions , Yes ‘ Inside ’ Look out for . Suppose there is a function variable with the same name outside , The internal function will mask the variables of the external function .
//5. Raise the scope of a variable 
function qj(){

var x="x"+y;
console.log(x);
var y="y";
}
The result is :x undefined, explain :js Execution engine , It's automatically raised y Statement of , But it doesn't raise variables y Assignment .( That is, the declaration of variables will be automatically put in front , Assign normal position )
//6. Specification of variable declaration 
therefore js The specification of variable declaration is : All variable definitions are placed at the head of the function , Don't put it about , Easy to maintain code .js Features that existed at the beginning of creation .
funxtion qj(){

var x=1;
y=x=1,
z,i,a;//underfined
// Then use it at will .
}
//7. Global function 
x=1;
function f(){

console.log(x);
}
f();
console.log(x);
//8. Global object Window( Also called browser object )
var x='xxx';
alert(x);//window Omission .
alert(window.x);// Default to all global variables , Will be automatically bound to window Under the object ;
//9.alert() The function itself is also a window Variable 
var x='xxx';
window.alert(x);
var old_alert=window.alert;
//ola_alert(x);
window.alert=function(){

}
// Find out alert It doesn't work 
window.alert(123);
// recovery 
window.alert=ols_alert;
window.alert(456);
 explain js There is actually only one global scope , Any variable ( Functions can also be treated as variables ), Assume that... Is not found within the scope of the function , It looks out , If it is not found in its global scope , Report errors :RefrenceError
//10. standard : Because all global variables will be bound to our window On . If different js file , The same global variables are used , Conflict ---> How to reduce conflict ???
// Define a unique global variable .
var KuangApp ={
};
// Define global variables 
KuangApp.name='kuangshen';
kuangApp.add=function(a,b){

return a+b;
}
namely : Put all your code in the unique space name you define , Reduce the problem of global naming conflicts .
jquery That's what the bottom layer does .
//11. How global variables are defined :
1) adopt var Keyword implementation , Declaration outside the method is global , Within the method is local .
var test = 5; // Global variables 
function a()
{

var cc=3; // local variable 
alert(test);
}
function b(){
alert(test);}
2) Not used var, Give the identifier directly test assignment , Both inside and outside the method are global variables
test = 5;// Global variables 
function a()
{

aa=3; // Global variables 
alert(test);
}
3) Use window Global object to declare , The attribute of a global object corresponds to a global variable
window.test;
window.test = 5;
//12. local variable let
function aaa(){

for(var i=o;i<100;i++){

console.log(i);
}
console.log(i+1);//101 problem ? i Out of this scope, it can also be used, which is obviously inappropriate .
}
solve :ES6 The new grammar uses let Instead of var Solve the problem of local variable conflict .
function aaa(){

for(let i=o;i<100;i++){

console.log(i);
}
console.log(i+1);//Uncaught ReferenceError: o is not defined
}
All suggestions are let Defining local variables , But many people still use var.
//13.const Constant .
stay ES6 The writing method of constants defined before : Variable names are all capitalized .
var AAA='ccc';
AAA='qqq';// You can still change this constant value .
console.log(AAA);
ES6 after
const AAA='ccc';
AAA='qqq';// Will report a mistake , Constant values cannot be modified .
console.log(AAA);

1.2.5 JS Operator

JS and Java The operators in are roughly the same , for example :

 Arithmetic operator : +,-,*,/,%,++,--
Assignment operator : =,+=,-=,*=,/=,%=
Comparison operator : ==,!=,>,>=,<,<=
An operator : & , |
Logical operators : && ,|| ( false && expression , true || expression )
Pre logical operators : ! (not)
Ternary operator : expression ? expression : expression
......
//js in == and === The difference between 
== // Different types , Same value , It will also be judged as true
=== // Absolutely equal to ( Same type, same value , The result is true) Recommended ===

1.2.6 js Common output methods

1、alert(" What to output ");
-> A dialog box pops up in the browser , And then show what you want to output
->alert All of them convert the content to be output into a string first, and then in the output
2、document.write(" What to output ");
-> Directly display the output content in the page
3、console.log(" What to output ");
-> Output content in the console

1.2.7 JS sentence

JS And Java The sentences in are also roughly the same

1、if Branching structure

if Branches are used to perform different actions based on different conditions . The syntax is as follows :

if ( Conditions 1){

When conditions 1 by true Code executed at
}else if ( Conditions 2){

When conditions 2 by true Code executed at
}else{

When conditions 1 and Conditions 2 Not for true Code executed at
}

2、switch sentence

Use switch Statement to select one of the blocks of code to execute . The syntax is as follows :

switch(n){

case 1:
Execute code block 1
break;
case 2:
Execute code block 2
break;
...
default:
And case 1 and case 2 Code that doesn't execute at the same time
}

Execution principle : First set the expression n( It's usually a variable ). Then the value of the expression will match each of the case Compare the values of . If there is a match , Then it is related to the case The associated block of code is executed . Please use break To prevent code from automatically moving to the next case function .

3.1、for Loop statement – Loop code block a certain number of times

for The syntax structure of the loop is as follows : js in No, enhance for loop

for ( sentence 1; sentence 2; sentence 3){

Code block executed
}

3.2 Array loop

//es5.1 characteristic .
var age=[21,23,12,77,34,67,11,45];
//1. Use js Provided forEach Function to loop . You can also use the arrow function to abbreviate this way , Omit function
age.forEach(function (value){

console.log(value);//21,23,12,77,34,67,11,45
})
//2. Use for Loop statement to loop 
for(var i=0;i<age.length;i++){

console.log(age[i]);// The result is the same 
}
//3.for...in( Not recommended )
//for(var index in object){}
for(var num in age){

if(age.hasOwnProperty(num)){

console.log(age[num]);
}
}

4、while loop – Loop the code block when the specified condition is true

JS in while Cycles are also divided into while and do/while loop , The following is while Cyclic grammatical structure :

while ( Conditions ){

Code to execute
}
do {

Code to execute
}while

while Loop will loop through a block of code when the specified condition is true .

Case study 1:if Branch case : Receive user input scores , Judge the grade of your grade

80~100( Include 80, Also include 100) good
60~80( Include 60, But does not include 80) secondary
0~60( Include 0, But does not include 60) fail,
Other values Incorrect input

The code implementation is as follows :

prompt( Parameters 1, Parameters 2 ) function : A message input box pops up on the page , Parameters received 1 It is the prompt content displayed in the pop-up box , User input content , Will be returned directly as the return value of the function .

Parameters 2, Is the default value in the input box , You can modify . You can also write only one parameter

<script>
/* Case study 1:if Branch case : Receive user input scores , Judge the grade of your grade 80~100( Include 80, Also include 100) good 60~80( Include 60, But does not include 80) secondary 0~60( Include 0, But does not include 60) fail, Other values Incorrect input --------------------------------------------- adopt prompt Function allows the user to enter content on the page , And return the user's input But the return value is of string type , When needed , It can automatically convert data types If nothing is output , What this accepts is 0 explain : This prompt The function is similar to alert, A box will pop up on the page , The content inside is the prompt content in the box , He has a return value of yes String The type pull-up window accepts the value entered in the pop-up window . If you enter a numeric type, it will be converted to the corresponding numeric string , Then the numerical ratio will be automatically converted into numerical value for comparison . If you don't enter anything , Will be converted to an empty string , The empty string will be converted to 0 Comparing . */
/* var score = prompt(" Please enter your score :"); console.log( typeof score ); document.write( score +"<br/>" ); if( score>=80 && score<=100 ){ document.write(" Your grades belong to : good !");// Output to a web page }else if( score>=60 && score<80 ){ document.write(" Your grades belong to : secondary !"); }else if( score>=0 && score<60){ document.write(" Your grades belong to : fail, !"); }else{ document.write(" Your score is illegal , Please re-enter !"); } */

Case study 2:switch Sentence case — Implement a simple calculator :

It can receive two values and an operator from the user (+、-、*、/), According to the different operation symbols , Perform different operations on two values .

The code implementation is as follows :

var str = prompt(" Please enter the value 1、 Operator 、 The number 2, Space between :");
document.write("<hr/>"+str); // "10 + 5"
// For the current str The string is cut according to the space , After cutting, all substrings will be returned as an array 
var strArr = str.split(" "); // ["10","+","5"]
var num1 = strArr[0]-0; // "10" Only in js use , - The yes operator can only be used for numeric operations , So it will automatically turn 
var opt = strArr[1]; // "+"
var num2 = parseFloat( strArr[2] ); // "5" Only parseInt and parseFloat. There will be no loss of accuracy .
switch( opt ){

case "+":
document.write(" The sum of the two values is :" + (num1 + num2) ); because + Is a splicer, so first convert the returned string to a numeric type
break;
case "-":
document.write(" The difference between the two values is :"+ (num1 - num2) );
break;
case "*":
document.write(" The product of two values is :"+ (num1 * num2) );
break;
case "/":
document.write(" The quotient of the two values is :"+ (num1 / num2) );
break;
default:
document.write(" The operator you entered is illegal , Please re-enter !");
} */

Case study 3:for Loop statement case

Traverse 1~100 Between all the integers , seek 1~100 The sum of all integers between , And output to the console ;

The code implementation is as follows :

/* Case study 3:for Loop statement case Traverse 1~100 Between all the integers , seek 1~100 The sum of all integers between , And output to the console ; */
var sum = 0;
for(var i=1;i<=100;i++){

// sum = sum+i;
sum += i;
}
document.write("1~100 The sum of all integers between is :"+sum);
document.write("<hr/>")

Case study 4:while Loop statement case

Traverse the elements in the following array , Output the element to the console .

var arr = [123, "abc", false, new Object() ]; //java Braces in .

The code implementation is as follows :

var arr = [ 123, "abc", false, new Object() ];*/
var arr = [ 123, "abc", false, new Object() ];
var index = 0; // As subscript of array 
var len = arr.length; // Get array length 
// The length of the declaration array is written out because , If it's written in it, it's called once per loop , A waste of time . It may take less time at a time , But if many people visit, it will save a lot of time .
while( index < len ){

document.write( arr[index] +" ");
index++;
}
document.write("<hr/>");

1.2.8 JS Array

Array Object is used to store multiple values in a single variable .

JS Array declaration method 1 :

var arr=( ); There is no such way of writing

var arr={ }; How objects are declared

var arr=[ ]; How arrays are declared

var arr=/xx/; If there is content in it, it is the declaration of regular expression

// Declare an empty array , The length is zero 
var arr1 = [];
// Declare an array , And set the initial value for the array 
var arr2 = ["Hello", 111, false, new Object() ];
arr[0]=1 // Through subscript value and assignment 

JS Array declaration method 2 :

// Declare an empty array , The length is zero 
var arr3 = new Array();
// Declare an array , And set the initial value for the array 
var arr4 = new Array("Hello", 111, false, new Object());

Details in arrays :

(1**)JS The array in can store any type of data **

(2)JS The length of the array in can be changed arbitrarily

var arr1 = [];
console.log(" The length of the array here is : "+arr1.length ); // 0
arr1.length = 5;
console.log(" The length of the array here is : "+arr1.length ); // 5
arr1[9] = "a";
console.log(" The length of the array here is : "+arr1.length ); // 10
arr1[99] = "b";
console.log(" The length of the array here is : "+arr1.length ); // 100

Array method

// The in the array can only be output directly 
var str=[1,2,3,4,5,6];
console.log(str);//[1, 2, 3, 4, 5, 6]
//1. length , Note that this length can be assigned 
console.log(str.length);//6
// Be careful : If arr.length assignment , The size of the array will change , If the assignment is too small , The elements will be lost . If the assignment is too much, use empty Express .
str.length=10;
console.log(str);//[1, 2, 3, 4, 5, 6, empty × 4]
str.length=2;
console.log(str);//[1, 2]
//2.indexof, Get subscript index through element 
str.indexof(2)
//3.slice() Intercept Array Part of , Returns a new array , Be similar to String Medium substring With head and no tail .
str.slice(2)
//4.push(),pop()
str.push("a","b") // Push into the end of the array .
str.pop() // An element at the end of the pop-up window . Not by value .
//5.unshift(),shift()
unshift: Press into the head
shift: Pop up an element of the head .
//6. Sort sort()
["B","C","A"]
arr.sort()
["A","B","C"]
//7. Element inversion reverse()
["A","B","C"]
arr.sort()
["C","B","A"]
//8.concat() Mosaic array 
["A","B","C"]
arr.concat([1,2,3])
["A","B","C",1,2,3]
["A","B","C"] // Output the original 
Be careful :concat() The array is not modified , It just returns a new array .
//9. Connector join
// Print a concatenated array , Concatenate with a specific string 
["C","B","A"]
arr.join('-')
"C-B-A"
//10. Multidimensional arrays 
arr=[[1,2],[3,4],["5","6"]];
arr[1][1]
4

1.2.9 JS function

A function is a functional block of code , It can be called repeatedly

Functions are blocks of code wrapped in curly braces , Key words used earlier function.

js Function, which is a weakly typed language, has no overload concept and the type of parameters . No matter the number ,js All method names in can be regarded as a variable name , So as long as the method name is the same ( It has nothing to do with whether there are parameters in it ) Rewriting will happen ( Cover ). js The coverage in is understood as the coverage of the whole method and the original method . So the distinction js Methods in can only be distinguished by method name .

JS The way to declare a function in is : The parameters inside do not write parameter types , Just need the name of some parameters

// Be careful js The function name inside cannot use keyword : If deleted, it cannot be used delete. Otherwise it doesn't work .


function  The name of the function ([ parameter list ]){

The body of the function
}
function fn1(name,age){

alert(name+", "+age);
return name;
}
call : fn1( " Liu peixia ", 35 );
// Once implemented to return Represents the end of the function , Return results !
// If not implemented return, Function execution will also return the result , The result is undefined;

perhaps : Note that the name of this method is written before .

var Variable name / Function name  = function([ parameter list ]){

The body of the function
}
for example :
var fn2 = function (name,addr){

alert(name+", "+addr);
}
Call function fn2( " Zhang Shenzheng ", " Shangqiu, Henan " );

Calling functions are the same :

// The name of the function ([ parameter list ]);
//js Parameter problem in :
js You can pass any parameter , You can also pass no parameters .
//1. Whether there is a problem with the parameters ? Assuming that there are no parameters, how to avoid .
var x='aa';
if(typeof x!=='number'){
 // If x If it is not a numeric type, an exception is thrown .
throws 'Not a Number';
}
//2. Parameter multiple problems ?arguments yes js Free keywords . It represents all the parameters passed in , Is an array .( namely , The parameters defined in the source code are also output )
var abs=function(x){

console.log("x=>"+x);
for(var i=0;i<arguments.length;i++){

console.log(arguments[i]);
}
if(x>0){
// Absolute value function .
return x;
}else{

return -x;
}
}
//3.arguments Contains all the parameters , Sometimes we want to use extra parameters for additional operations . You need to exclude the existing parameters .
The old way of writing it :
if(arguments.length>2){

for(var i=2;i<arguments.length;i++){

}
}
Let me write it the way I do it now ;
ES6 New features , Get all parameters except the defined parameters ...
function aaa(a,b,...rest){

console.log("a=>"+a);
console.log("b=>"+b);
console.log(rest);
}
// Be careful :rest It can only be written at the end , Must use ... identification .

**js Anonymous functions in :** An anonymous function is a function without an actual name , It can only be called once . Such as :

// Declare an anonymous function , And call ( Wrap the function in parentheses and add a parenthesis at the end. The call can pass parameters )
(function(name,addr){
console.log(name+":"+addr+"...");
})(" Lau Andy "," Hong Kong, China, ");

Expand :js You can pass a function as a parameter to another function .

// Make a statement fn function , And accept a " Function type " Parameters of .
function fn(myFunction){
console.log(“fn The function executes ...);
myFunction(" Zhang Fei "," hebei ");// Call the received function
}
// Make a statement fn2 function , And accept name and age
function fn2(name,age){
console.log(“fn2 The function executes ...);
console.log(name+":"+age);
}
// call fn function , And will fn2 As a parameter to fn function .
fn( fn2 );

1.2.10 js object

Objects are braces , Arrays are brackets .

Separate each attribute with a comma , The last one doesn't need to be added .

There are several key value pairs .

js All keys in are strings , The value can be any object .

//1. grammar : There are also several ways .
var Object name ={

Property name : Property value ,
Property name : Property value ,
Property name : Property value
}
var person={

name:"shuai",
age:3,
tages:['js','java','web','...']
}
//2. Using a non-existent object property will not report an error !
person.haha
undefined
//3. The value of the call object 
person.name // shuai
person.age //3
//4. Object Assignment 
person.name =" Hello ";
//5. Dynamic pruning properties ,java Can not be .
delete person.name
true
person // Output the value in the object 
//6. Dynamic add , Add values directly to the new attribute 
personson.haha="haha"
"haha"
person
//7. Determine whether the property value is in the object ! xxx in xxx!
'age' in person
true
// Inherit 
'toString' in person
true
//8. Determine whether an attribute is owned by the object itself hasownProperty
person.hasownProperty('toString')
false
person.hasownProperty('age')
false

1.2.11 js Methods in objects

The method is to put the function in the object , The only object is 2 Change things : Properties and methods .

var kuangshen={

name:' Wang ke ',
birth:2000,
// Method 
age:function (){
 // Notice that there is no method name 
// This year, - The year of birth 
var now =new Date().getFullYear();
return now-this.bitrh;
}
}
// attribute 
kuangshen.name
// Method , Be sure to bring ()
kuangshen.age()

this. What is the ? Take apart the code above and have a look

function getAge(){

var now=new Date().getFullYear();
return now-this.bitrh;
}
var kuangshen={

name:' Wang ke ',
birth:2000,
// Method 
age:getAge
}
//kuangshen.age() ok
//getAge() NaN window
this It's impossible to point to , It is the object that only wants to call him by default .

stay js Through apply control this The direction of

function getAge(){

var now=new Date().getFullYear();
return now-this.bitrh;
}
var kuangshen={

name:' Wang ke ',
birth:2000,
// Method 
age:getAge
}
getAge.apply(kuangshen,[]);//this Yes kuangshen, The parameter is empty. .

1.2.12 js Special objects inside

Standard object

typeof 123 //typeof Determine the type of parameter 
"number"
typeof '123'
"string"
typeof true
"boolean"
typeof NaN
"number"
typeof []
"object"
typeof {
}
"object"
typeof Math.abs
"functionr"
typeof underfined
"underfined"

Internal object

1.data object

//1.Date
var now=new Date();
console.log(now)//VM238:2 Fri May 21 2021 12:51:27 GMT+0800 ( China standard time )
now.getFullYear();// year 
now.getMonth();// month 
now.getDate();// Japan 
now.geyDay();// What day 
now.getHours();// when 
now.getMinutes();// branch 
now.getSeconds();// second 
// Time stamp means Greenwich mean time 1970 year 01 month 01 Japan 00 when 00 branch 00 second ( Beijing time. 1970 year 01 month 01 Japan 08 when 00 branch 00 second ) The total number of seconds since .
now.getTime();// Time stamp The whole world is united 1070 1.1 0:00:00 Number of milliseconds 
console.log(new Date(1621572687140));// Time stamp is converted to time ( The value in it is :now.getTime())

transformation

now =new Date(1621572687140)
Fri May 21 2021 12:51:27 GMT+0800 ( China standard time )
// Convert to local time , You can also use the method of Dongba District 
now.toLocaleString// Be careful , Call is a method , It's not an attribute 
ƒ toLocaleString() {
 [native code] }
now.toLocaleString()
"2021/5/21 Afternoon 12:51:27"
// Turn into World time 
now.toGMTString()
"Fri, 21 May 2021 04:51:27 GMT"

2.json object

json What is it? :

In the early , All data transmission is used to XML file !

JSON(JavaScript Object Notation) Is a lightweight data exchange format .

Concise and clear hierarchy bring JSON Become the ideal data exchange language .

Easy to read and write , At the same time, it is also easy for machine analysis and generation , And effectively Improve the efficiency of network transmission .

stay js Everything is an object , whatever js All supported types can be used json To express ;number,String…

Format :

​ Objects and map Use both {}

​ Array and list Use both []

​ All key value pairs are key:value

json String and js Transformation of objects .

var user={

name:"wangke",
age:3,
sex
}
// Object to json character string {"name":"qinjiang","age":3,"sex":" male "}
// Generally used to operate json Data in , need json character string 
var jsonUser =JSON.stringify(user);
//json String to object Parameter is json character string 
// It is generally used for data interaction between client and server , Use json character string .
var obg =JSON.parse('{"name":"qinjiang","age":3,"sex":" male "}');

A lot of people don't know ,json String and js The difference between objects .

var obj={
a:'hello',b:'hellob'};
var json='{'a':'hello','b':'hellob'}';

1.2.13 js The difference between variable function and attribute method

var age=20;// Variable 
function fb(){
 // function 
}
var aa={

age:30, // attribute 
fn:function(){
 // Method ( Assign it directly , The second way to declare a method .)
}
}
summary :
1. Variables and attributes work in the same way , They are all used to store data .
Variable : Declare and assign values separately When using, write the variable name directly Exist alone .
attribute : There is no need to declare in the object When using, it must be object . attribute .
2. Similarities between functions and methods They all realize some function Do something
Functions are declared separately And call  Function name () Existing alone
Method is inside the object When called object . Method ()

1.2.14 js Of Map and Set

Es6 New syntax
// demand : Now I want to check the students' grades , Student's name .
Map:
var names=["tom","jack","rose"];
var scores=[100,90,80];
This method requires multiple arrays to query , Reading is very slow .
// improvement :
var map=new map([['tom,100'],['jack',90],['haha,80']]);
var name=map.get('tom')// adopt key obtain value
map.set('admin',123456);// Add or modify 
map.delete("tom");// Delete 
Set: Disorder cannot be repeated
var set =new Set([3,1,1,1,23]);// duplicate removal 
set.add(2);// add to 
set.delete(1);// Delete 
console.log(set.has(3));// Does it include 

1.2.15 js Of iterator

// adopt for of Implementation iterator , for in no way 
//1. Array can be iterated 
var arr=[3,4,5];
for (var x of arr){

console.log(x);
}
//2. Can iterate Map aggregate 
var map=new Map([["tom",100],["jack",90],["haha",80]]);
for(let x of map){

console.log(x);
}
//3. Can iterate Set aggregate 
var set =new Set(5,6,7);
for(let x of map){

console.log(x);
}

1.2.16 Strictly check the mode description

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<!--
Premise is IDEA Need to set up support ES6 The grammar of
'use strict' Strictly check the pattern , The prevention of js Some of the problems caused by the randomness of , Must be on the first line ,
It is suggested to write all js Add this sentence to the first line of the code .
For local variables, it is recommended to use let To define
Constant is defined by const
For global variables var -->
<script>
'use strict';
// Default global variables :i=1;
let i = 1;
// stay ES6 in For local variables, it is recommended to use let
</script>
</body>
</html>
summary : like this i=1 This code js Can write , And can correctly output , But if you introduce a lot of js file ,
Inside js The definition should be called i The variable of , It will cover the front , Obviously not , solve : Add this
'use strict', And set up js Version is es6, Will help you automatically check , If you write this again, you will report an error and cannot output .

 Please add a picture description

1.2.17 object-oriented programming

Prototype object

js,java,c#… object-oriented ;js Some differences !

class : Templates , Prototype object

object : Specific examples

stay js This object needs to change its way of thinking .

Prototype : Es6 Previously inherited writing .

var Student={

name:"wangke",
age:3,
run:function(){

console.log(this.name+"run...");
}
};
var xiaoming={

name:"xiaoming"
};
// Prototype object 
xiaoming._proto_=Student;
var Bird={

fly:function(){

console.log(this.name+"fly...");
}
}
// Xiao Ming's prototype is Student
xiaoming._poroto=Bird
namely : Take Xiao Ming as a subclass and inherit the parent class Student. The subclass can use the method of the parent class .
function Student(name){

this.name=name;
}
// to student Add a new method 
Student.prototype.hello=function(){

alert('hello');
}

class object

class Inherit (ES6)

1. Define a class , attribute , Method

 //ES6 after =============
// Define a student's class 
class Student{

constructor(name){

this.name = name;
}
hello(){

alert('hello')
}
}
var xiaoming = new Student("xiaoming");
var xiaohong = new XiaoStudent("xiaohong",1);
xiaoming.hello()

2. Inherit

 //ES6 after =============
// Define a student's class 
class Student{

constructor(name){

this.name = name;
}
hello(){

alert('hello')
}
}
class XiaoStudent extends Student{

constructor(name,grade){

super(name);
this.grade = grade;
}
myGrade(){

alert(' I am a primary school student ')
}
}
var xiaoming = new Student("xiaoming");
var xiaohong = new XiaoStudent("xiaohong",1);

The essence : Look at the object prototype
 Insert picture description here

Prototype chain

_prop_:

 Insert picture description here

1.2.18 operation BOM object ( a key )

Browser Introduction :

​ js Relationship with browser ?

​ js It was born so that it can run in the browser !

BOM: Browser object model .

1.IE 6~11

2.Chrome

3.Safari

4.FireFox

5.Opera

Third party browser :

qq browser

360 browser .

window Introduce :( a key )


window For browser window .
window.alert(1) // Warning box 
undefined
window.innerHeight
700
window.innerWidth
150
window.outerHeight
819
window.outerWidth
1555
// You can change the value according to the browser window you open .

Navigator:

//Navigator, Encapsulates the browser information 
window.navigator.appName
"Netscape" // The name of the browser 
navigator.appVersion
"5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36"
navigator.userAgent
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36"
navigator.platform
"Win32"
// Large logarithms , We will not use Navigator object , Because it will be modified by Ren Wei ! It is not recommended to use these properties to judge and write code .

screen:

// Represents the size of the screen 
screen.width
1536 px
screen.height
864 px

location( a key )

//location Representing the current page URL Information 
host: "www.baidu.com"
hostname: "www.baidu.com"
protocol: "https:"
reload: ƒ reload()// Refresh web page 
location.assign('https://blog.kuangstudy.com/')

document( important )

//document Represents the current page ,HTML DOM Document tree 
//1. Get the page title 
document.title
" use Baidu Search , You will know "
document.title='aaa' //aaa
//2. Get the specific document tree node 
<dl id="app">
<dt>Java</dt>
<dd>JavaSE</dd>
<dd>JavaEE</dd>
</dl>
<script>
// The return value is an object 
var dl = document.getElementById('app');
</script>
//3. obtain cookie Baidu as an example 
document.cookie
"BIDUPSID=BCD0DD182F7217AAC52916C027F801D6; PSTM=1610891488; BD_UPN=12314753; MCITY=-268%3A; BAIDUID=65FFF5AC4BBD3B7839BB19908E91EDC1:FG=1; BAIDUID_BFESS=65FFF5AC4BBD3B7839BB19908E91EDC1:FG=1; BDORZ=B490B5EBF6F3CD402E515D22BCDA1598; Hm_lvt_aec699bb6442ba076c8981c6dc490771=1619429257,1621489701; BD_HOME=1; H_PS_PSSID=33838_34044_31253_33848_33773_33607_26350; delPer=0; BD_CK_SAM=1; ZD_ENTRY=baidu; COOKIE_SESSION=13091_0_9_9_60_62_0_0_0_9_59_0_13081_0_3_0_1621586860_0_1621586857%7C9%2325424_50_1617369622%7C9; PSINO=1; rsv_jmp_slow=1621587991745; H_PS_645EC=ed99IvVBlDpfu1heiqMVKMPw0wG7YGT4AILE9Vre3XX1%2By5mFgkBe0x%2FU6U; BDSVRTM=0; BA_HECTOR=2h8025048h80842g9h1gaf1k70r"
//4. hijacked cookie principle 
<script src="aa.js"></script>
<!-- Malicious people : Get your cookie Upload to his server -->
// The server side can be this cookie:httpOnly resistance .
//5.history Represents the browser record 
history.back()// back off 
history.forward();// Forward 

1.2.19 Comprehensive practice

( Do it yourself ) Declare a function fn, Implement in a function : Traverses two specified values ( for example 1 and 100) Integer between , It will be 3 The value of the multiple of is stored in an array , And return the array to .

1、 Statement fn function

// Make a statement fn function , receive 2 Parameters 
function fn(x,y){

// Declare an array , For storage is 3 The number of multiples of 
var arr = [];
// loop x To y Between all the integers 
for(var i=x,j=0;i<y;i++){

// Judge i( The integer currently traversing ) Is it 3 Multiple 
if(i%3==0){

arr[j] = i; // If it is , Will i Deposit in arr Array 
j++; // Self increasing 
}
}
return arr; // return arr Array 
}

2、 call fn function , obtain 1~100 Between 3 An array of multiples of

var arr = fn(1,100);

3、 Traversing elements in an array , Output on the web ( Tips : document.write(“ Output content ”) )

for(var i=0;i<arr.length;i++){

document.write(arr[i]+" ");
}

1.3 DOM Operation details


DOM: Document Object Model, Document object model , In fact, that is JS Specifically for visiting html Elements provide a set of API.

The core : A browser web page is a DOM A tree structure .

  1. obtain : obtain DOM node

  2. to update : to update DOM node

  3. Delete : Delete one DOM node

  4. add to : Add one DOM node

    To operate a DOM node , You have to get this first DOM node .

 Insert picture description here

1.3.1 obtain DOM node

All at once js Native code is relatively long , In the future jquery Abbreviation .

<body>
<div id="father">
<h1> Title 1 </h1>
<p id="p1">p1</p>
<p class="p2">p2</p>
</div>
<script>
// Corresponding css Selectors The return value is one js object 
var h1 = document.getElementsByTagName('h1');// Get from tag 
var p1 = document.getElementById('p1');// according to id obtain 
var p2 = document.getElementsByClassName('p2');// According to class 
var father = document.getElementById('father');
var childrens = father.children; // Get all the child nodes under the parent node 
// father.firstChild Get the first child node under the parent node 
// father.lastChild Get the last child node under the parent node 
</script>

1.3.2 to update DOM node

<body>
<div id="id1">
</div>
<script>
var id1 = document.getElementById('id1');// Get the node first 
id1.innerText = 'abc'
</script>
</body>

Action text

// Insert or modify the value of the text ( The original value is modified , Not inserted for )
id1.innerText='123'
// Bold and insert 123. 2 The difference between :innerHTML Can be parsed HTML Text label .
id1.innerHTML='<strong>123</strong>'

js Dynamic operation css

id1.style.color='red'; // Set the style to red 
id1.style.fonSize='20px'// Set font size 

1.3.3 Delete node

step : Get the parent node first , Delete yourself through the parent node :

<div id="father">
<h1> Title 1 </h1>
<p id="p1">p1</p>
<p id="p1">p1</p>
</div>
<script>
var self=document.getElementById('p1');
var father=self.parentElement;
father.removeChild(selef)
// Deletion is a dynamic process 
father.removeChild(father.children[0])
father.removeChild(father.children[0])
father.removeChild(father.children[0])
</script>

Be careful : Delete multiple nodes yes ,children It changes all the time , When deleting nodes, you must pay attention to .

1.3.4 Insert ( add to )DOM node

We got some DOM node , Suppose this DOM The node is empty , We go through innerHTML You can add an element , But this DOM The node already has elements , We can't do that ! Coverage will be generated .

step : Get the parent node first , Adding child nodes to parent nodes .

1. Add the existing node to the existing node ( Append to the last line by default )


<p id="js">JavaScript</p>
<div id="list">
<p id="se">JavaSE</p>
<p id="ee">JavaEE</p>
<p id="me">JavaME</p>
</div>
<script>
var js = document.getElementById('js');// Son 
var list = document.getElementById('list');// Father 
list.appendChild(js);// Append to the back ( Parameters are subclass objects )
</script>

 Insert picture description here

2. Create a new tag , Implement insert

<script>
var js = document.getElementById('js');// Existing nodes 
var list = document.getElementById('list');// Append to the back 
// Through a new label , Implement insert 
// How to write it 1:
var newP=document.createElement('p');// Create a p label 
newP.id='newP';// Add... To this tag id=newP Properties of 
newP.innerText='Hello,kuangshen';// Add text content to this tag .
list.appendChild(newP);// Append to the back 
// How to write it 2: Universal writing 
var myScript=document.createElement('script');
myScript.setAttribute('type','text/javascript')
// Create a style label 
var myStyle=document.createElement('style');// Create a style label 
myStyle.setAttribute('type','text/css');
myStyle.innerHTML='body{background-color:chartreuse;}';// Set label content 
document.getElementsByTageName('head')[0].appendChild(myStyle);
</script>

3. Append the existing node to the existing node

<p id="js">JavaScript</p>
<div id="list">
<p id="se">JavaSE</p>
<p id="ee">JavaEE</p>
<p id="me">JavaME</p>
</div>
<script>
var ee = document.getElementById('ee');
var js = document.getElementById('js');
var list = document.getElementById('list');
// Parent node ( The introduction can also include ) New node The target node 
list.insertBefore(js,ee);
</script>

1.3.5 Operation form

What is a form : form It's also a DOM Trees

1. The text box

2. A drop-down box

3. Radio buttons

4. Checkbox

The purpose of the form is : Submission of information

<form action="#">
<p>
<span> user name :</span> <input type="text" id="username" required>
</p>
<!-- The value of the multi check box , It's defined value -->
<p>
<span> Gender :</span>
<input type="radio" name="sex" value="man" id="boy"> male
<input type="radio" name="sex" value="women" id="girl"> Woman
</p>
<input type="submit">
</form>
<script>
var input_text = document.getElementById('username');
var boy_radio = document.getElementById('boy');
var girl_radio = document.getElementById('girl');
// Get the value of the input box 
input_text.value
// Change the value of the input box 
input_text.value = '123'
// For radio boxes , Multiple check boxes and so on ,boy_radio.value Only the current value can be obtained 
boy_radio.checked; // View the returned results , Is it true, If true, Is selected ~
girl_radio.checked = true; // assignment 
</script>

1.3.6 Submit Form ( Encryption processing md5)

<!--
Form binding submission event
onsubmit= Bind a function to submit detection , true, false
Return this result to the form , Use onsubmit receive !
onsubmit="return aaa()"
-->
<form action="https://www.baidu.com/" method="post" onsubmit="return aaa()">
<p>
<span> user name :</span> <input type="text" id="username" name="username">
</p>
<p>
<button type="submit"> Submit </button>
<span> password :</span> <input type="password" id="input-password">
</p>
<input type="hidden" id="md5-password" name="password">
<!-- The binding event onclick Clicked -->
</form>
<script>
function aaa() {

alert(1);
var uname = document.getElementById('username');
var pwd = document.getElementById('input-password');
var md5pwd = document.getElementById('md5-password');
// pwd.value = md5(pwd.value);
md5pwd.value = md5(pwd.value);
// You can verify and judge the form content ,true By submitting ,false, Block submission 
return true;
}
</script>

1.4 Case study

1.4.1 Case study : Light switch

Click on the light to turn on / Turn off the lights , The code implementation is as follows :

Be careful :js A label can be represented by an object in , We can express the attribute of the tag through the attribute of the object .

// Ideas : Execute by clicking on the event js Method , Get the tag in this function as an object , Get the corresponding properties through this object , Through if Judge to change the attribute value used to control the switching picture .
<!doctype html>
<html>
<head>
<meta charset="utf-8"/>
<title> Light switch case </title>
<style>
body{
padding:20px;font-size:20px;}
#div1{
width:30%;border:1px solid red;padding:5px;margin-bottom:20px;}
</style>
<!-- introduce jquery Of js library This place is not used jquery Commented out
<script src="js/jquery-1.8.3.min.js"></script> -->
<script>
/** practice : Click button , Turn the light on or off */
var flag = "off"; //flag Used to mark the status of the lamp ,off The indicator light is currently off ,on Indicates that the light is on 
function changeImg(){

//1. Get representation img Elemental js object // oImg ==> <img id="img1" src="imgs/off.gif"/>
var oImg = document.getElementById("img1");
//2. Judge the state of the light , Choose to turn the light on or off according to the status 
if( flag == "off" ){
 // Indicates that the light is off , It needs to be changed to open 
oImg.src = "imgs/on.gif"; // Turn on the lights. 
flag = "on"; // Because the light has been turned on , So update flag The status of is on
}else{
 // Indicates that the light is on , It needs to be changed to off state 
oImg.src = "imgs/off.gif"; // Turn off the lights 
flag = "off"; // Because the light has been turned off , So update flag The status of is off
}
}
</script>
</head>
<body>
<!-- onclick Used to bind click events for buttons , When the button is clicked , Will trigger a click event , perform changeImg function -->
<input type="button" value=" open / Turn off the lights "
onclick="changeImg()" /> <br/><br/>
<img id="img1" src="imgs/off.gif"/>
</body>
</html>

1.4.2 Case study : Add, delete and modify elements ( Elemental DOM operation )

Click the button in the web page to html Elements to operate


<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8"/>
<title> Check the addition, deletion and modification of elements </title>
<!-- Add style sheet -->
<style type="text/css">
div {
 border:#0099FF 2px solid;height:60px;width:350px;margin:20px 10px;padding:5px 7px;line-height:60px;font-size:26px;text-align:center;}
#div_1{
 background-color:#d400ff; }
#div_2{
 background-color:#FF3399; }
#div_3{
 background-color:#00FF00; }
#div_4{
 background-color:#FFFF66; }
#info{
 width:250px;height:90px;font-size:22px;padding:5px;resize:none;}
input{
font-size:18px;}
</style>
<!-- introduce jquery Of js library
<script src="js/jquery-1.8.3.min.js"></script> -->
<script type="text/javascript">
/** practice 1、 Additive elements : Add one div Element to body in */
function addNode(){

//1. Create a div Elements , And give div Add content , The parameter is the element name 
var oDiv = document.createElement("div"); //<div></div>
oDiv.innerHTML = "Hello, I'm new here div~~"; //<div>Hello, I'm new here div~~</div> To this div Add content to the label .
//2. Get... In the current web page body Elements (document Provides direct access to body Attribute of element )
var oBody = document.body; // If the location changes, how to find its parent class 
//3. Call the method through the parent element , Add child elements ( Because the element is only created and has no connection with the current web page , So it will not be displayed on the current web page , If you want to show it, you need to establish a connection . For example body Inside the label .)
oBody.appendChild( oDiv );
}
/** practice 2、 Remove elements : Delete id by div_2 The elements of */
//parentNode
function deleteNode(){

//1. Get the element to delete 
var oDiv2 = document.getElementById("div_2");
//2. Get the parent element of the element to be deleted ( parentNode Get the parent of the current element )
//var oBody = document.body; of no avail body It's because it's not necessarily body.
var oParent = oDiv2.parentNode;// This also gets the parent element .
//3. Call the method through the parent element , Delete child elements 
oParent.removeChild( oDiv2 );
}
/** practice 3、 Update element content : take div_3 The content of is updated to the current time */
function updateNode(){

//1. obtain id by div_3 The elements of 
var oDiv3 = document.getElementById("div_3");
//2. Gets a string representing the current time Local It's a foreign time format 
var dateStr = new Date().toLocaleString();
//3. take div_3 The content of the element is updated to the current time string 
oDiv3.innerHTML = dateStr;
}
// practice 4. Delete all div Elements 
function deleteAll(){

// Get all div Elements , Return all div Array of elements 
var divArr=document.getElementsByTagName("div");
// facilitate div The parent element of the element , And delete the current element through the parent element 
var len =divArr.length;// Get and record the length of the array , The advantage of this is , Array length is fixed , If you delete it again, the length will not change 
// facilitate div An array of elements 
for(var i=0;i<len;i++){

// Get the parent of the current element , And delete the current element through the parent element 
divArr[0].parentNode.removeChild( divArr[0] );
}
}
</script>
</head>
<body>
<input type="button" onclick="addNode()"
value=" Create a div Add to body in "/>
<input type="button" onclick="deleteNode()"
value=" Delete id by div_2 The elements of "/>
<input type="button" onclick="updateNode()"
value=" take div_3 The content of is updated to the current time "/><hr/>
<input type="button" onclick="deleteAll()"
value=" Delete all div Elements "/><hr/>
<div id="div_1">
div_1
</div>
<div id="div_2">
div_2
</div>
<div id="div_3">
div_3
</div>
<div id="div_4">
div_4
</div>
</body>
</html>

1.4.3 Case study : The skin of the web

3 individual .css file Skin changing css file Omit not write .


<html>
<head>
<meta charset="utf-8"/>
<title> The skin of the web </title>
<style type="text/css">
body{
font-size:18px;font-family:" Microsoft YaHei ";}
hr{
border:1px solid yellow;}
a{
font-size:17px;font-weight:500;}
a:hover {
color:#0099FF;}
h2,#change-font{
text-align:center;}
#newstext{
padding:10px;margin:0 auto;letter-spacing:2px;}
/* Pre order some selectors */
.min{

font-size:16px;
}
.middle{

font-size:18px;
}
.max{

font-size:20px;
}
.super-max{

font-size:24px;
}
</style>
<!-- Introducing external CSS file -->
<link rel="stylesheet" href="" id="link"/>
<!-- introduce jquery Of js library
<script src="js/jquery-1.8.3.min.js"></script> -->
<script type="text/javascript">
/** practice 1: Perform the following functions , Switch font size */
function resize(size){

// obtain id by newstext The elements of (div)
var oDiv = document.getElementById("newstext");
// Will receive class value , Assign value to the above obtained div Elements 
// because class yes js Reserved word in , So set... For the element class Attribute cannot be directly clicked class(.class), But through className
oDiv.className = size;
}
// Define an array , Store different skin (css Path to file )
var arr = ["css/red.css","css/green.css","css/blue.css","css/yellow.css"];
var index = 0;
/** practice 2: Perform the following functions , Switch different skins for the page */
function changeStyle(){

//1. obtain link label ( Return is a js object , This object represents link label )
var oLink = document.getElementById("link");
//2. modify link Labeled href Property value , Point to one css Path to file 
//oLink.href = arr[index];
oLink.setAttribute("href", arr[index]);
index++;
//3. Judge index Whether the value of is greater than or equal to the length of the array 
if( index == arr.length ){

index = 0;
}
}
</script>
</head>
<body>
<h2> Introduction to Dane times Technology Group </h2>
<div id="change-font">
<!-- When it comes to a Labeled href Property is assigned to "javascript:void(0)" when , Can prevent hyperlinks from jumping : Because hyperlinks have some styles by default , No more styling
The parameters of the method are The selector is class Value .
Execute the process : The browser loads the web page --- Click the hyperlink in the web page --- Execute the method inside to class The selector has changed to the corresponding parameter ---- The selector changes to the corresponding css The style, even the font size, has also changed .
-->
<a href="javascript:void(0)"
onclick="resize('min')"> Small font </a>
<a href="javascript:void(0)"
onclick="resize('middle')"> Chinese font </a>
<a href="javascript:void(0)"
onclick="resize('max')"> Big font </a>
<a href="javascript:void(0)"
onclick="resize('super-max')"> Large font </a>
<a href="javascript:void(0)"
onclick="changeStyle()"> Skin peeler </a>
</div>
<hr/>
<div id="newstext" class="middle">
<p>
Dane times Technology Group Co., Ltd , It's China's high-end IT Leading brands in training , Committed to cultivating Internet oriented 、 In telecommunications and finance Java、C++C#、.Net、 software test 、 The embedded 、PHP、android And other high-end software talents .
</p>
<p>
Dane was founded in 2002 year , focus IT Vocational education 17 year ,2014 In, it was listed on NASDAQ in the United States . at present , Has opened 24 Major course direction , In the country 70 Several cities have established 330 Home training center , True realization “ Study all the time , National employment ”. Employ famous teachers at director level with high salary to teach full-time , There are specialized skills , A great teacher is a great apprentice . The implementation of “ According to their aptitude , Graded training ” Teaching plan , Let every student become a talent , Make the strong stronger . use “ Study first , Post employment payments ” The pattern of , Helped 80 Ten thousand students were successfully employed .
</p>
<p>
Dane's excellent teaching effect and industry-leading business model have won wide praise and praise from all walks of life , Won awards from authoritative institutions from all walks of life : Dane has become the only company in the industry 2006200720082009 continuity 4 Selected by Deloitte in “ High tech growth in China 50 Strong company ”、“ High tech growth in the Asia Pacific region 500 Strong company ”, Won the first Chinese talents studying abroad to return home and start a business “ Take off ” prize 、 Designated by Zhongguancun Management Committee “ Software talent training demonstration base ”、 By 《 Computer world 》 Selected “ Outstanding employment service award ”、 By 《 China Computer News 》 Selected “ Most influential training institution Award ”、 Rated by Sohu as “ China's top ten education groups ”、 Rated by Tencent as “ The most influential in the eyes of Chinese college students IT brand ”.
Have the strength 、 Have credibility , To train , Just choose a listed company !
</p>
</div>
<hr/>
</body>
</html>

1.4.4 summary :JS Add, delete and modify elements

document.createElement( The element name ) – Creates an element with the specified name based on the element name , Returns a that represents the newly created element js object

parent.appendChild( child ) – Add child elements through parent elements , among parent Represents the parent element ,child Represents a child element

parent.removeChild( child )– Delete the child element through the parent element , among parent Represents the parent element ,child Represents a child element

element.innerHTML – obtain The current element Of html Content ( Everything from the start tag to the end tag ), You can also set the of the current element html Content ( If there is content inside the element , The original content will be covered )

<div id="div1">
This is a div Elements ...
<span> This is a span Elements </span>
</div>
// obtain div Elements
var oDiv1 = document.getElementById("div1");
oDiv1.innerHTML;// obtain div Content of element

2. jQuery

2.1 jQuery brief introduction

2.1.1 What is? jQuery( understand )

jQuery: JavaScript Query JS Inquire about

jQuery It's a lightweight door 、 Free and open source JS function library **( Namely JS A simple framework for )**

jQuery Can greatly simplify JS Code

jQuery The core idea of :“ Write less , But more ”

Be careful :alt +/ If prompted No Default Proposals: There is no default prompt

Official website :jquery.com


*** A lightweight :* It means that a technology or framework has a relatively low degree of intrusion into code or program .

Or the less dependent the code is on the technology , The lighter the technology is . The more dependent on this technology , The heavier the technology is . The lighter the technology, the better the weight . But now jquery It has become... Heavy .

jQuery In essence, it contains many functions JS file , If you want to be in a certain HTML Use this JS Functions in the file , You have to JS File import to HTML in ( Want to use jQuery, You have to introduce jQuery Function library file of , It's just one. JS file )


2.1.2 jQuery The advantages of ( understand )

(1) Can greatly simplify JS Code

(2) Can be like CSS Selectors get html Elements

css Get all the div, to div Add the style :

div{ css attribute ... }

jQuery Get all div, to div Add border style :

$=jquery It is equivalent to calling a function , Parameters are passed inside 8888888888

$("div").css("border", "2px solid red");
JS obtain id by div1 The elements of : document.getElementById("div1") The return value is an object .
jQuery obtain id by div1 The elements of : $("#div1") perhaps jquery("#div1")

(3) It can be modified by css Property controls the effect of the page

(4) Can be compatible with common browsers

such as : JS Medium innerText attribute 、removeNode() function 、replaceNode( ) function These functions are not available in some browsers .//IE It works , Firefox can't use

To solve these compatibility problems : The function is the same as above

jQuery The corresponding functions are provided in ( text function 、remove function 、replaceWith function )

Popular browsers : Google browser 、 Firefox 、 Apple chrome 、 Opan browser, etc

2.1.3 jQuery The formula

// Selectors event 
$(selector).action()

2.1.4 jQuery introduce

jQuery Function library file is a common JS file , introduce jQuery And introduction JS It's the same way to file .

Be careful : Usually put this jquery Put the files in the project instead of on disk , In the introduction of . Because the absolute path is written in the disk , It will be useless to copy the project path in the future without this file , Unless you copy files . And put it in the project and copy the project , Even the files inside have been copied , It's more convenient . There are... In this document note .

The second stage ----day06—day10------day06.07—jquery_example—js

The big one is before compression : When a study or project has not been released . The smaller ones are compressed : Project release , benefits : The user visits the page to load small js, Reduce the consumption of traffic .
 Insert picture description here
explain : js It's a catalog , This in the catalog js file jquery-1.8.3.js . This is the place where the path is written ./ It can be omitted . You can also write absolute paths ( The relative path is written because the file is copied into the project .)

<!-- In the use of jQuery Before , You have to introduce jQuery Function library file of -->
<script src="js/jquery-1.8.3.js"></script>
<script>
//jquery == $
jQuery(function(){

// After the browser loads the entire web page, it will execute 
document.write("jquery The introduction succeeded !");
});
</script>

In the introduction of jQuery Function library file , If the file import path is wrong , Will cause file import failure , Here's the picture :

 Insert picture description here

2.1.5 Document ready event function

<head>
<meta charset="UTF-8">
<!-- In the use of jQuery Before , You have to introduce jQuery Function library file of -->
<script src="js/jquery-1.8.3.js"></script>
<script> //1. obtain id by demo Of h1 Elements  var h1 = document.getElementById( "demo" ); //2. obtain h1 Content in the element ( innerHTML ) alert( h1.innerHTML ); </script>
</head>
<body>
<h1 id="demo">jQuery An example of the introduction of ...</h1>
</body>

Problem description : The code above is executed , Will report a mistake :

 Insert picture description here

Reason to describe : In the execution of the acquisition id by demo The element is , h1 The element has not been loaded by the browser yet , So you can't get it h1 Elements .

The browser executes from top to bottom .

Solution one : Need to move the code

take script Label moved to body Inside , That is to say h1 After element

In this way, when the browser loads , Will load first h1 Elements , Then execute the acquisition h1 The code for the element , Because it's getting h1 Before element ,h1 The element has been loaded by the browser , So we can get it later !

Code example :

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<!-- Path interpretation : Look for the html The current directory of the file , Find the file name step by step and add /, Compressed files are recommended jquery. After the project goes online , Because it takes less memory -->
<script src="./jquery_example/js/jquery-1.8.3.js"> </script> <!-- The suggestion is written in head Inside , The document is suggested to be written in the directory , When transferring items in the future , The file has also been copied -->
</head>
<body>
<h1 id="demo"> Hello, everyone. I'm slag Hui !</h1>
<script > // Case study : adopt js obtain id by demo Element content of  //1. obtain id by demo The elements of  var oH1 = document.getElementById("demo");// But this place didn't get h1 Elements , Because browsers execute in order , The following has not been implemented yet . terms of settlement , Put the load after the element  //2. obtain demo Element and output it to the console ,innerHTML Get the content of the tag . console.log(oH1.innerHTML); </script> -->
</body>
</html>

Solution two : No code is required

Usually used to get functions .

Put the code to get the element in the document ready event function , The document ready event function will load all the html After the element ( That is, after loading the last one html Element time ) Execute now .

Because all the elements in the current page are loaded ,h1 The element must have been loaded , At this point, you can get h1 The element is bound to get .

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="./jquery_example/js/jquery-1.8.3.js"></script>
<script > /* Or through the document ready event function : The browser will execute immediately after loading all the contents , This method is automatically called by the browser */ //js Provided document ready event function It can be understood as fixed writing  /* window.οnlοad= function(){ // Case study : adopt js obtain id by demo Element content of //1. obtain id by demo The elements of var oH1 = document.getElementById("demo");// But this place didn't get h1 Elements , Because browsers execute in order , The following has not been implemented yet . terms of settlement , Put the load after the element //2. obtain demo Element and output it to the console console.log(oH1.innerHTML); } */ //jQuery Provided document ready event function , No introduction jquery Just use js, Which one to use after introduction  // understand : $(); Equivalent to calling a function Write an anonymous function inside function(){} grammar : $(function(){
 Code .... }); Example : $(function(){
 // Case study : adopt js obtain id by demo Element content of  //1. obtain id by demo The elements of  var oH1 = document.getElementById("demo"); //2. obtain demo Element and output it to the console  console.log(oH1.innerHTML); }); </script>
</head>
<body>
<h1 id="demo"> Hello, everyone. I'm slag Hui !</h1>
</body>
</html>

Solution three :

Will get the code of the element Put it in a custom function , And bind the function to h1 Element click event , When we click h1 Element will execute the custom function , When the function is executed h1 Elements , You can get it at this time h1 Elements .

<head>
<meta charset="UTF-8">
<!-- In the use of jQuery Before , You have to introduce jQuery Function library file of -->
<script src="js/jquery-1.8.3.js"></script> //2 individual script A writer introduces jquery, One to write code
<script> function fn1(){
 //1. obtain id by demo Of h1 Elements  var h1 = document.getElementById( "demo" ); //2. obtain h1 Content in the element ( innerHTML ) alert( h1.innerHTML ); } </script>
</head>
<body>
<h1 id="demo" onclick="fn1()">jQuery An example of the introduction of ...</h1>
</body>

summary : When to use the document ready event function ?

If you get the element , Get the timing of code execution for the element , Even earlier than the element itself , If the element is not loaded, get it , It must be impossible to get .

You can put the code that gets the element in the document ready event function , After the browser loads the entire web page , The document ready event function is executed , At this point, all the elements are loaded , If you take any element, you can get !

jQuery Provided document ready event function ( Abbreviation form ):

<script> $(function(){
 // No method name  // Load the entire... In the browser html Execute immediately after the web page  }); </script>

The complete way to write it is :

<script> $(document).ready(function(){
 // Load the entire... In the browser html Execute immediately after the web page  }); </script>

JS The document ready event function is also provided for us , It's written as :

<script> window.onload = function(){
 // Load the entire... In the browser html Execute immediately after the web page  } </script>

2.2 jQuery Selectors ( a key )

Corresponding css Selectors

2.2.1 Basic selector

jquery Selector in :$() Write a string parameter inside , You can use both single and double quotation marks , The writing inside is similar js. The return value is one jquery object .

(1) Element name selector
$("div") -- Check all div Elements
$("span") --  Check all span Elements 
(2)class/ Class selectors
$(".s1") -- Select all class The value is s1 The elements of (class The value is s1 The element of can be any element )
$("span.s1") -- Select all class The value is s1 Of span Elements 
(3)id Selectors
$("#one") --  Choose id by one The elements of 
(4) Multi element selector
$("div,span,.s1,#one") -- Check all div Elements , And all span Elements , And all class The value is s1 The elements of , as well as id by one The elements of

2.2.2 Hierarchy selector

$("div span") -- Select all div All inside span Elements
$("#one span") -- Choose id by one All of the elements inside span Elements
$("#two+span") -- Choose id by two The next to the element of span Brother element
$("#two").next("span") -- Choose id by two The next to the element of span Brother element
$("#two").prev("span") -- Choose id by two The element of is immediately ahead of span Brother element
$("#two~span") -- Choose id by two All of the following elements of span Brother element
$("#two").nextAll("span") -- Choose id by two All of the following elements of span Brother element
$("#two").prevAll("span") -- Choose id by two All of the elements in front of span Brother element
$("#two").siblings("span") -- Choose id by two Before the element of 、 After all span Brother element

2.2.3 Basic filter selector

(1) Choose the first one div Elements
$("div:first")
$("div:eq(0)")
$("div").eq(0)
(2) Choose the last div Elements
$("div:last")
$("div:eq(-1)")
$("div").eq(-1)
(3) Select the first n+1 individual div Elements (n Starting from scratch )
$("div:eq(n)")
$("div").eq(n)

2.2.4 Other selectors

$(":input") – Match all form item elements ( It can be input、select、option、textarea Equal elements .)

( " : c h e c k b o x " ) − − horse with the Yes Of complex choose box , etc. price On (":checkbox") -- Match all check boxes , Equivalent to (":checkbox") horse with the Yes Of complex choose box , etc. price On (“input[type=‘checkbox’]”).

$(":checked") – You can match all selected radio or check boxes , And the selected option Options .

$(“input:checked”) – Indicates that all selected radio or check boxes are matched .

2.2.5 Practice of selector :

<!DOCTYPE>
<html>
<head>
<meta charset="utf-8"/>
<title> Selector practice </title>
<style type="text/css">
body{
 font-family:" Microsoft YaHei "; font-size:20px;padding-bottom:300px;}
input{
font-size:18px;margin-top:10px;}
div,span{
width:300px;border:1px solid #000;padding-left:10px;background:#bed4ef;;}
span{
display:block;}
body>div,body>span{
height:100px;margin:10px 0px 0px 20px;display:inline-block;vertical-align:middle;}
#one{
width:300px;height:185px;}
div>span,div>div{
width:250px;height:35px;margin:10px;}
</style>
<!-- introduce jquery Function library file -->
<script src="js/jquery-1.8.3.min.js"></script>
<script type="text/javascript">
/* Document ready event function ( That is, the last one is loaded in the browser html Execute immediately after the element ) */
$(function() {

/* ------- One 、 Basic selector exercise ------- */
/* 1、 Choose id by b1 The button , by b1 Button binding click event , Click on b1 Button : Change everything div The background color of the element is #FD5551 */
// explain : This is dynamic binding , For the elements b1 Bind click event , Just click this b1 The button will execute click The method inside function
$("#b1").click(function(){

// After the element selected by the selector is clicked , Execute current now function, Write it directly on the label , This is dynamic binding jquery The way .
// Check all div Elements , And give all div Set the background color (css function )
/* $("div").css("background","#FD5551"); // Element name does not have # Click event is a statement that will be executed after clicking // Set other css attribute There are several attribute settings that can be adjusted several times css Method The first one is : $("div").css("border","2px solid blue"); $("div").css("color","yellow"); */
// The second is to write it all at once {} It says in it key--vey structure 
$("div").css({

"background":"#FD5551",
"border":"2px solid blue",
"color":"yellow"
});
});
/* document.getElementById("b1").οnclick=function(){ This is a js The way Note that there is no # } */
/* 2、 Choose id by b2 The button , by b2 Button binding click event , Click on b2 Button : change id by one The background color of the element is #91BF2F */
$("#b2").click(function(){

$("#one").css("background","#91BF2F");
});
/* 3、 Choose id by b3 The button , by b3 Button binding click event , Click on b3 Button : change class by mini The background color of all elements of is #EE82EE */
$("#b3").click(function(){

$(".mini").css("background","#EE82EE");
});
/* --------- Two 、 Hierarchy selector ------- */
/* 4、 Choose id by b4 The button , by b4 Button binding click event , Click on b4 Button : change div All in span The background color of is #DC21D2 */
$("#b4").click(function(){

$("div span").css("background","#DC21D2"); // Choose div All in span Elements 
});
/* 5、 Choose id by b5 The button , by b5 Button binding click event , Click on b5 Button : change id by two Next adjacent to the element div Elements The background color of is #2CADAA */
$("#b5").click(function(){

// Choose id by two Next adjacent to the element of div Brother element ( Must be context )
//$("#two+div").css("background","#2CADAA"); // Choose div All in span Elements 
// Similar to its function is a set of functions 
$("#two").next("div").css("background","#2CADAA");
// Choose id by two The previous adjacent of the element of div Brother element 
$("#two").prev("div").css("background","#2CADAA"); //previous: The previous 
});
/* 6、 Choose id by b6 The button , by b6 Button binding click event , Click on b6 Button : change id by two After the element, all the div Brother element The background color of is #ECD822 */
$("#b6").click(function(){

//$("#two").nextAll(); // Choose id by two All sibling elements after the element of 
$("#two").nextAll("div").css("background","#ECD822");// Choose id by two All of the following elements of div Brother element 
$("#two").prevAll("div").css("background","#ECD822");// Choose id by two All the elements in front of div Brother element 
});
/* 7、 Choose id by b7 The button , by b7 Button binding click event , Click on b7 Button : change id by two The front of the element 、 After all div Brother element The background color of is #EE0077 */
$("#b7").click(function(){

$("#two").siblings("div").css("background"," #EE0077"); // Equivalent to ,nextAll + prevAll
});
/* --------- 3、 ... and 、 Basic filter selector ------- */
/* 8、 Choose id by b8 The button , by b8 Button binding click event , Click on b8 Button : Change the first and the last div The background color of the element is #0074E8 */
$("#b8").click(function(){
 // Bind click event 
// Select all div The first of div Elements 
// $("div").eq(0).css("background"," #0074E8");
// The first element is special , also 2 Methods 
// $("div:first").css("background"," green");
// Or 
$("div:eq(0)").css("background"," #0074E8");
// Choose div Last of div Elements 3 Species writing Similar to a clock -1 Always represent the last The subscript is from 0 Start .
// $("div:last").css("background"," red");
//$("div:eq(-1)").css("background"," #0074E8");
$("div").eq(-1).css("background"," #0074E8");
});
/* 9、 Choose id by b9 The button , by b9 Button binding click event , Click on b9 Button : Change the 4 individual div The background color of the element is #D917C6 */
$("#b9").click(function(){

$("div:eq(3)").css("background"," #D917C6");
});
});
</script>
</head>
<body>
Basic selector →:
<!-- Button ,id by b1 -->
<input type="button" id="b1" value="b1, Change everything div The background color of the element is #FA8072" />
<!-- Button ,id by b2 -->
<input type="button" id="b2" value="b2, change id by one The background color of the element is #9ACD32"/>
<!-- Button ,id by b3 -->
<input type="button" id="b3" value="b3, change class by mini The background color of all elements of is #EE82EE"/>
<hr/>
Hierarchy selector →:
<!-- Button ,id by b4 -->
<input type="button" id="b4" value="b4, change div All in span The background color of is #7CFC00"/>
<!-- Button ,id by b5 -->
<input type="button" id="b5" value="b5, change id by two Next adjacent to the element div Elements The background color of is #48D1CC"/>
<!-- Button ,id by b6 -->
<input type="button" id="b6" value="b6, change id by two After the element, all the div Brother element The background color of is #D2FA7E"/>
<!-- Button ,id by b7 -->
<input type="button" id="b7" value="b7, change id by two The front of the element 、 After all div Brother element The background color of is #FF69B4"/>
<hr/>
Basic filter selector →:
<!-- Button ,id by b8 -->
<input type="button" id="b8" value="b8, Change the first / the last one div The background color of the element is #1E90FF"/>
<!-- Button ,id by b9 -->
<input type="button" id="b9" value="b9, Change the 4 individual div The background color of the element is #EA3AD8"/>
<h3> Click the button to see the effect ...</h3>
<div id="one">
This is a div1
<div class="one01"> This is a div11</div>
<span class="mini"> This is a span,class by mini</span>
<span class="mini"> This is a span,class by mini</span>
</div>
<div> This is a div2
<input type="button" value=" Button 1"/>
<input type="button" value=" Button 2"/>
</div>
<div id="two"> This is a div3,id yes two
<span> This is a span</span>
</div>
<div> This is a div4</div>
<div> This is a div5</div>
<span class="mini"> This is a span,class by mini</span>
<div> This is a div6</div>
<span class="mini01"> This is a span,class by mini01</span>
<span class="mini"> This is a span,class by mini</span>
</body>
</html>

2.3 Comprehensive case

2.3.1 Create table elements

test :

<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8"/>
<title> Create a table </title>
<style type="text/css">
/* Define... For the table CSS style */
body{
padding-left:15px;font-size:20px;}
table{
 border:1px solid #0099FF; width:70%; border-collapse:collapse; }
table td{
 border:#0099FF 1px solid; padding:10px 20px 3px 1px; }
input[type='text']{
width:150px;height:20px;vertical-align:text-bottom;text-indent:5px;font-size:20px;}
input[type='button']{
font-size:20px;}
</style>
<!-- introduce jquery Function library file -->
<script src="js/jquery-1.8.3.min.js"></script>
<script type="text/javascript">
/** practice 1: Create a single row, single column table */
function createTable1(){

//1. Create a table Elements , Return to one jQuery object 
//$tab Before $ It's just here to identify that this is a jquery object , No other meaning 
var $tab = $("<table></table>");
//2. Create a tr Elements 
var $tr = $("<tr></tr>");
//3. Create a td Elements ( by td Set contents )
var $td = $("<td>Hello, I am a TD!</td>");
//4. take td Element added to tr Inside 
$tr.append( $td );
//5. take tr Element added to table Inside 
$tab.append( $tr )
//6. take table Add to body Element interior (body Already exists , Get it directly !)
$("body").append( $tab );
//$("body").append("<table><tr><td>Hello, I am a TD~~~</td></tr></table>");
}
/** practice 2: Create a single line 6 List of tables */
/** practice 2: establish 5 That's ok 6 List of tables */
function createTable2(){

//1. Create a table Elements , Return to one jQuery object 
//$tab Before $ It's just here to identify that this is a jquery object , No other meaning 
var $tab = $("<table></table>");
for(var j=0;j<5;j++){
 // Control the number of lines , Cycle a few times , Just create a few lines 
//2. Create a tr Elements 
var $tr = $("<tr></tr>");
for(var i=0;i<6;i++){
 // Control the number of columns , Cycle a few times , Just create a few columns 
//3. Create a td Elements ( by td Set contents )
var $td = $("<td>Hello, I am a TD!</td>");
//4. take td Element added to tr Inside 
$tr.append( $td );
}
//5. take tr Element added to table Inside 
$tab.append( $tr )
}
//6. take table Add to body Element interior (body Already exists , Get it directly !)
$("body").append( $tab );
}
/** practice 3: Create a table with specified rows and columns */
function createTable3(){

//(js How to get ) Get the number of lines entered by the user 、 And number of columns , value Used to set or get form item elements value value Get the value in the input box , This value Follow input Is there... On the label value Properties have nothing to do with , Because inside the browser, it will give the above... To the object represented by this element value attribute , He will assign the value of the input box to the... On this object value.
//var rows = document.getElementById("rows").value;
//var cols = document.getElementById("cols").value;
//(jquery How to get ) Get the number of lines entered by the user 、 And number of columns ,val() The function is used to set or get the name of the form item element value value 
var rows = $("#rows").val();
var cols = $("#cols").val();
//1. Create a table Elements , Return to one jQuery object 
//$tab Before $ It's just here to identify that this is a jquery object , No other meaning 
var $tab = $("<table></table>");
for(var j=0;j<rows;j++){
 // Control the number of lines , Cycle a few times , Just create a few lines 
//2. Create a tr Elements 
var $tr = $("<tr></tr>");
for(var i=0;i<cols;i++){
 // Control the number of columns , Cycle a few times , Just create a few columns 
//3. Create a td Elements ( by td Set contents )
var $td = $("<td>Hello, I am a TD!</td>");
//4. take td Element added to tr Inside 
$tr.append( $td );
}
//5. take tr Element added to table Inside 
$tab.append( $tr )
}
//6. take table Add to body Element interior (body Already exists , Get it directly !)
$("body").append( $tab );
}
</script>
</head>
<body>
<!-- practice 1: Click the following button to create a single row and single column table -->
<input type="button" value=" Create a single row, single column table " onclick="createTable1()" /><br/><br/>
<!-- practice 2: Click the button below to create 5 That's ok 6 Listbox -->
<input type="button" value=" Create a table (5 That's ok 6 Column )" onclick="createTable2()" /><br/><br/>
<!-- practice 3: Click the following button to create the specified row 、 Specify the table for the column -->
<input type="button" value=" Create a table ( Enter the number of rows and columns )" onclick="createTable3()" /><br/>
Row number :<input type="text" id="rows"/><br/>
Number of columns :<input type="text" id="cols"/><br/><br/>
<!--  Add the created table to body Inside ( Append to the end ) --><hr/>
</body>
</html>

2.3.2 Imitation QQ The friends list

<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8"/>
<title> Imitation QQ Friends group </title>
<style type="text/css">
table{
border:#09f 1px solid;width:100px;border-collapse:collapse;margin:15px 10px;margin:20px 20px;}
table td{
border:#06f 1px solid;background-color:#6f5f3e;text-align:center;padding:5px 0;}
table td div{
background-color:#ff9;text-align:left;line-height:28px;padding-left:14px;text-indent:padding-left:20px;}
table td span{
color:#fff;font-size:19px;width:100%;border:none;display:block;cursor:pointer;}
table td a:hover{
color:#0c0}
</style>
<!-- introduce jquery Of js library -->
<script src="js/jquery-1.8.3.min.js"></script>
<script type="text/javascript">
/** adopt jQuery Realize imitation QQ List friends list thisobj(js object ) Is the name of the currently clicked group ( That is, the clicked span Elements ) js Object cannot call jQuery Function of : js object -- Turn into -->jQuery object : $(js object ) -- return -> jQuery object */
function openDiv(thisobj){

/* Close the other three groups ( Hide... In the other three groups div) * Through the currently clicked span, Find the current span Of all the ancestral elements of tr Elements , Re pass * tr Find the other three tr Brother element , Through these three tr Element to find internal div Elements The hidden process uses 0.1 Seconds to complete this action . */
$(thisobj).parents("tr").siblings("tr").find("div").hide(100);
// Get the clicked group ( Clicked span) The adjacent div Elements 
$(thisobj).next("div").slideToggle(100); //100 millisecond 
}
</script>
</head>
<body>
<table>
<tr>
<td>
<span onclick="openDiv(this)"> King friend </span>
<div style="display:none">
Qin shi huang <br />
Liu bang <br />
Li Shimin <br />
Kangxi <br />
</div>
</td>
</tr>
<tr>
<td>
<span onclick="openDiv(this)"> Friends of the Three Kingdoms </span>
<div style="display:none">
Liu bei <br />
Guan yu <br />
Zhang Fei <br />
zhaoyun <br />
</div>
</td>
</tr>
<tr>
<td>
<span onclick="openDiv(this)"> Beautiful friends </span>
<div style="display:none">
Xi Shi <br />
The sable cicada <br />
Yang Guifei <br />
Wang Zhaojun <br />
</div>
</td>
</tr>
<tr>
<td>
<span onclick="openDiv(this)">IT Good friends </span>
<div style="display:none">
Wang Haitao <br />
Jack ma, <br />
Li Kaifu <br />
Mr Yu <br />
</div>
</td>
</tr>
</table>
</body>
</html>

2.3.3 Simulation of employee information management system

practice 1: Add employee information

<!DOCTYPE HTML>
<html>
<head>
<title> Simulation of employee information management system </title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<style type="text/css">
body{
font-family: " Microsoft YaHei "}
h2, h4{
 text-align: center; }
div#box1, div#box2 {
text-align:center;}
hr{
margin: 20px 0;}
table{
margin: 0 auto;width:70%;text-align: center;border-collapse:collapse;}
td, th{
padding: 7px; width:20%;}
th{
background-color: #DCDCDC;}
input[type='text']{
width:130px;}
</style>
<!-- introduce jquery Of js library -->
<script src="js/jquery-1.8.3.js"></script>
<script type="text/javascript">
/* --- Add a new employee --- */
function addEmp(){

//1. Get the employee information to be added (id,name,email,salary)
var id = $("#box1 input[name='id']").val();
var name = $("#box1 input[name='name']").val();
var email = $("#box1 input[name='email']").val();
var salary = $("#box1 input[name='salary']").val();
//2. Verify employee information 
//2.1. Can't add empty employee information , trim() Used to remove the space before and after the string 
if( id.trim()=="" || name.trim()=="" || email.trim()=="" || salary.trim()=="" ){

alert(" Can't add empty employee information !");
return;// End procedure , Stop adding !
}
//2.2. Added employees id Can't repeat 
/* obtain table All of them tr Elements , Go through each one tr Elements , Through the current tr Find the second inside td Cell contents ( This content is the current employee's id), Take the user's input id And the current employee's id Compare , If equal , Just stop Program , If it's not equal , Then execute the next cycle . Among them this Represents the of each traversal tr Elements */
var flag = "id non-existent "; // hypothesis id It doesn't exist !
$("table tr").each(function(){

// Through the current tr Find the second inside td Cell contents ( Is the current employee's id)
var tempId = $(this).find("td").eq(1).text();
// Take the user's input id And the current employee's id Compare 
if(id == tempId){

alert(" Added employees id Already exists , Add failure !");
flag = "id Already exists ";
}
});
if( flag == "id Already exists " ){

return;
}
//3. Take employee information as one line (tr) Add to table 
// Create a tr Elements 
var $tr = $("<tr></tr>");
// establish 5 individual td Elements , by td Element add content , And will td Add to tr in 
$tr.append("<td><input type='checkbox'/></td>");
$tr.append("<td>"+id+"</td>");
$tr.append("<td>"+name+"</td>");
$tr.append("<td>"+email+"</td>");
$tr.append("<td>"+salary+"</td>");
// take tr Element added to table in 
$("table").append( $tr );
}
/* --- Delete the selected employee --- $(":checked") -- Get the selected radio box 、 Check box 、option Options Get all checkboxes : $("input[type='checkbox']") Get all selected check boxes : $("input[type='checkbox']:checked") :not(seletor) -- Indicates that the division is selected selector Other elements $("tr:not(.header)") -- Check except class by header Outside of the tr Elements */
function delEmp(){

//1. Gets the location of the selected check box tr Elements , And will tr Elements are deleted directly 
//$("input[type='checkbox']:checked").parents("tr:not(.header)").remove();
$("input[type='checkbox']:checked").parent("td").parent("tr").remove();
}
/* Click Select all to set Select all or none of the employee's lines Realize the idea : After clicking the select all check box , If you select all check boxes [ Selected ], All check boxes are selected Click the select all check box , If you select all check boxes [ Deselected ], Uncheck all check boxes prop() function : $ele.prop(attrName) -- Get the value of an attribute of the current element ,attrName Is the attribute name $ele.prop(attrName,attrValue) -- Assign a value to an attribute of the current element , attrName It's the property name ,attrValue It's property value */
function checkAll(){

//1. Get the status value of the select all check box after clicking ( Selected or Deselected ), That is, get the check box checked The value of the property 
// checked The value of the property : true Represents a check box ( Including radio boxes ) Was chosen ,false Not selected 
var isCheck = $("#all").prop("checked");
//2. Set the status value of select all check boxes to all check boxes 
$("input[type='checkbox']").prop("checked", isCheck);
}
/* --- Modify designation id The employees' ( Do it yourself )--- */
function updEmp(){

//1. Get the modified employee information (id,name,email,salary)
//2. Check the data 
//2.1. The modified employee information cannot be blank 
//2.2. If the employee entered id There is , Then execute the modification , Otherwise prompt id non-existent , Modification failed !
}
</script>
</head>
<body>
<h2> Add new employees </h2>
<div id="box1">
<!-- $("#box1 input[name='id']") -->
ID<input type="text" name="id"/>
full name :<input type="text" name="name"/>
mailbox :<input type="text" name="email"/>
Wages :<input type="text" name="salary"/>
<input type="button" onclick="addEmp()" id="add" value=" Add new employees "/>
</div>
<hr/>
<table border="1">
<tr class="header">
<th>
<!-- Select all check boxes , Click the select all check box , Click event , perform checkAll function -->
<input type="checkbox" onclick="checkAll()" id="all"/>
</th>
<th>ID</th>
<th> full name </th>
<th> mailbox </th>
<th> Wages </th>
</tr>
<tr>
<td>
<input type="checkbox"/>
</td>
<td>1</td>
<td> Song Jiang </td>
<td>[email protected]163.com</td>
<td>12000</td>
</tr>
<tr>
<td>
<input type="checkbox"/>
</td>
<td>2</td>
<td> Wusong </td>
<td>[email protected]163.com</td>
<td>10500</td>
</tr>
<tr>
<td>
<input type="checkbox"/>
</td>
<td>3</td>
<td> Sun erniang </td>
<td>[email protected]163.com</td>
<td>11000</td>
</tr>
</table>
<h4><a href="javascript:void(0)" onclick="delEmp()" id="del"> Delete the selected employee </a></h2>
<hr/>
<div id="box2">
ID<input type="text" name="id"/>
full name :<input type="text" name="name"/>
mailbox :<input type="text" name="email"/>
Wages :<input type="text" name="salary"/>
<input type="button" onclick="updEmp()" id="upd" value=" according to ID Modify employee information "/>
</div>
</body>
</html>

2.4 jQuery summary

2.4.1 html Element operation ( establish , increase , Delete , Change )

Be careful : use jQuery The object calling method of cannot use js Methods provided .

1、 Create elements

$("<div></div>") -- Create a div Elements , Back to a jQuery object , Represents the created div Elements
$("<div>xxxx</div>") -- Create a content containing div Elements , Back to a jQuery object , Represents the created div Elements

2、 Add child elements

// Add... After creation 
$parent.append( $child ) -- The parent element calls the method to add the child element
// Add elements while creating directly 
$("body").append( "<div> I'm new here ...</div>" ); -- Go to body The element is appended with a div Subelement

3、 Remove elements

remove():
$("div").remove() -- Delete all div Elements , The bottom layer is still deleted one by one .
object .empty():
Empty all descendants of the element , Empty all descendants of the object , But keep the current object and its attribute nodes .
JS Delete all div Elements :
// Get all div Elements ( It's all back div Array of components )
var divArr = document.getElementsByTagName("div"); //div Array 
// Traverse div Array , Delete each one in turn div Elements 
var len = divArr.length;
for(var i=0;i<len;i++){

// Delete the current element through its parent element ( Always delete the first )
divArr[0].parentNode.removeChild( divArr[0] );
}

4、 Replacement elements

$("div").replaceWith("<p> I'm here to replace …</p>")

2.4.2 html Operation of the content and value of the element

<div>
This is a div11 Elements
<span> This is a span Elements </span>
This is a div1111 Elements
</div>
<input type="text" name="user"/>

1、html() function ( Be similar to js Medium innerHTML attribute )

Used to get or set the content of an element , For example div、span、p、h1~h6、table、tr、td、form Set the content with the elements . That is, the contents wrapped in the start and end labels , If multiple elements are matched through a selector , Only the contents of the first element can be obtained, or if multiple elements are matched through the selector , Then the content will be set for all elements . Because there is only one matching return value and no return value can be set, all contents can be set, even if there is a label ( This tag will be parsed into the corresponding format ).

// You can set labels + Text
$("div").html() -- Get all div The first of div The content of ( If there is the first div)
$("div").html("xxxx") -- For all div Set contents

2、text() function ( Be similar to js Medium innerText attribute ,innerText Not compatible in some browsers )

Used to get or set all text contents of the element , That is, get all the contents of the element ( Get text only , Don't get tags , If the label is included, it will be displayed as text and will not be parsed into the corresponding style .), If multiple elements are matched through a selector , You can return the text inside all elements ,text The function can also set the text content for the element ( Only text content can be set ).

 Only text content can be set
$("div").text() -- Get all div All the text content in
$("div").text("xxxx") -- For all div Set text content

3、val() function ( Be similar to js Medium value attribute )

Gets or sets the form of the form item element (input/select/option/textarea)

namely : That is, enter the value in the box .

//js by value attribute .
$("input").val() -- Get all input The first of the elements input Elemental value value
$("input").val( value ) -- For all the input Element settings value value , The value is written in parentheses .

2.4.3 Element attributes and css Attribute operation

<input type="text" name="username" id="inp"/>

1、prop() function Used to get or set the attribute value of an element

stay jQuery1.6 This function is available only after the version ( This can get inherent properties : The attributes that come with this tag ),1.6 Previous version jQuery have access to attr() function ( This attribute is a custom attribute or an inherent attribute )

$("input[type='checkbox']").prop("checked")
// obtain input Check box selection status , return true Indicates that the check box is selected , return false Indicates that the check box is unselected 
$("input[type='checkbox']").prop("checked", true)
// Set the matching check box element to the selected state 
$("#inp").prop("name"); // obtain id by inp Elemental name Property value , return useranme
$("#inp").prop("name","user"); // by id by inp The element settings of name Property value , name The property value becomes user

2、css() function – Used to get or set elements css Property value

$("#div1").css("width") -- obtain id by div1 Width of element
$("#div1").css("width","200px") -- Set up id by div1 The width of the element is 200px
$("#div1").css({

"width" : "200px",
"height" : "150px",
"border" : "5px solid red",
"background" : "pink"
}); // by id by div1 The width of the element is set to 200px、 The height is 150px、 Border and background color, etc 

2.4.4 Other functions

Traversal function

1、each() function

$(selector).each(function( index,element ){
})
// each() Functions can traverse $(selector) All elements selected by the selector ( That is, get one element from the elements selected by the selector at a time , And implement function function )
// function Medium index -- The subscript of the element that represents the traversal 
// function Medium element -- Represents the element that is currently traversing ( It can also be done through this obtain )

Example :

$("table tr").each(function(){

// Get the contents of the second cell from the current row ( The current line of id value )
var tempId = $(this).find("td").eq(1).html();
// Take the user's input id and In each line id Value comparison 
if( id == tempId ){

alert(" Add failure ,id Already exists !");
flag = true; //id There is , to update flag Value ,true It means that there is already !
}
});

Show hidden

2、show()/hide() function 8888888888

Why set the element to be hidden on the web page and not displayed , For better display in the future .

** such as :** Login box on Baidu , Click to display , Not clicking is usually hidden .

 Insert picture description here

show() – Set the element from hidden to displayed

$("div").show() -- Set all div The element is display

Equivalent to :

$("div").css("display", "block");

hide() – Set the element from show to hide

$("div").hide() -- Set all div Elements are hidden

Equivalent to :

$("div").css("display", "none")

Element display status

3、toggle()/slideToggle()

toggle() – Switch the display state of the element , If the element is displayed , Switch to hide , Otherwise, switch to display

slidToggle() – Switch the display state of the element , If the element is displayed , Switch to hide , Otherwise, switch to display , Switch to display as drop-down state , Hidden as a contraction state .

difference : The switching effect is different ,toggle() It's a point that slowly gets bigger and smaller and slidToggle() It's a line that slowly gets bigger and smaller .

Get the parent and child elements of the current element

4.parent()/parents()/find()

parent()-- Get the parent of the current element , Be similar to js Medium parentNode attribute .

parents()-- Get all ancestor elements of the current element .( That is, all the parent elements of the current element , It's usually body The elements in the tag .)

find() -- Gets the descendant element specified inside the current element . Such as :

$("div").find("span") -- Get all div Inside the element span Elements .
perhaps
$("div span") -- Get all div Inside the element span Elements .

2.4.5 Mouse events

//onClick: Mouse click event , Use more mouse clicks within the control range of an object 
//onblur: Event triggered when the current element loses focus [ Both mouse and keyboard can be triggered ]
//onfocus: Event triggered when an element gets focus 
//.......
<input type="text" name="name" id="nameId" onblur="doCheck()" onfocus="doClear()" onClick="onClick()">

2.5 The extended contents include


2.5.1 Binding click events for elements

Take the click event as an example , The way to bind a click event to an element is :

The way 1(js edition ): This is written in the button

<script>
function fn(){

alert("input The button is clicked ...");
}
</script>
<body>
<input onclick="fn()" type="button" value=" Am I ~!" />
</body>

The way 2(js edition ): Dynamic binding js edition

<script>
window.onload = function(){

// obtain id by btn The elements of 
var btn = document.getElementById("btn");
btn.onclick = function(){

alert("input The button is clicked ...");
}
// The above is written separately or directly Be careful js This way of writing does not #, Yes # yes jquery Writing 
document.getElementById("btn").onclick=function(){

alert("input The button clicked ..."); //alert It's a way , It's a string ( Single and double quotation marks are OK ), Click the button to execute the click event function, and a warning box will appear on the browser page , The content in the box is the transmitted string 
}
}
</script>
<body>
<input id="btn" type="button" value=" Am I ~!" />
</body>

** The way 3(jQuery edition ):** Dynamic binding jquery edition

<script>
$(function(){

// When you click btn Button , Trigger the click event to execute the function 
$("#btn").click( function(){

alert("input The button is clicked ...");
});
});
</script>
<body>
<input id="btn" type="button" value=" Am I ~!" />
</body>

2.5.2 js Objects and jQuery Conversion of objects to each other

namely : use $() hold js Objects wrapped There are no double quotes inside

jquery Object is a collection . js Object can only represent one element .

adopt JS The way to get the element , The return is JS object ,JS Object can only call JS Property or function of

adopt jQuery Selector gets element , The return is jQuery object ( The structure is like a collection ),jQuery Object can only call jQuery Property or function of .

If existing JS object , But we need to call jQuery Property or function of , Can be JS Conversion of objects jQuery object ;

If existing jQuery object , But we need to call JS Property or function of , Can be jQuery Conversion of objects JS object ;

 Insert picture description here

3 tomcat、HTTP

3.1 Server Overview


3.1.1 What is a server ?

The server : Divided into server hardware and Server software . On the hardware server ( Computer ) Server software installed on , Before you can provide external services .

such as : Let other computers access the current server , Provide services for other computers .

(1) Server hardware : It refers to having independent on the Internet IP Address computer , For example, our own computers can also be used as servers .

(2) Server software : It's a computer program , such as MySQL Server software ,tomcat Server software . There are many types of server software , such as :ftp The server , database server ,web Server software , Mail server, etc .

3.1.2 What is? Web The server ?

(1) web A server is a type of computer program that resides on the Internet . When the browser accesses the server , When requesting a file on the server , The server will process the request , And respond the requested file to the browser , Some information will be attached to tell the browser how to view the file ( That is, the type of file ), That is to accept the request of the client and respond according to the request .

(2) web The server can send messages to “ The requesting browser provides the document ” The program , For example, when visiting Baidu , In fact, I'm visiting Baidu's server .

explain :

Server side , It's for clients . The content of the service, such as providing resources to the client , Save client data . It is an important way to realize the characteristics of the game , It is also the most direct technology that can be expressed through the game .

client , Or client , Corresponding to the server , Procedures for providing local services to customers . Except for some applications that only run locally , It is usually installed on a common client computer , It needs to work with the server .

Generally speaking , The client is the computer we use ( Including the browser we use IE,Firefox); The server side is the server that stores web pages and database data .

If you play 《 World of warcraft 》, It's on the computer “ Warcraft program ” Is the client program , You connected “ The server ” It's a server-side program .

request , Respond to : such as 2 Dialogue between individuals , Let me say a word to you , Another person is replying .

 Insert picture description here

tomcat It's one individual web Server software , By apache A server software provided by the organization , characteristic : Small and flexible , Free and open source , Simple and easy to use .

3.2 tomcat download 、 install 、 start-up 、 To configure

3.2.1 download tomcat The server

Download address :http://tomcat.apache.org/

tomcat There are many versions , There is a decompressed version and Installed version , Share windows ( It's also divided into 32 Bit and 64 Bit Edition ) and linux edition , According to your own needs , Select the corresponding version to download .

first :windows Decompressed version of the system

the second :linux Or apple system

Third , The fourth one : Just go straight to the first one

The fifth one :windows Installation version of

 Insert picture description here

tomcat The server needs to run jdk Support for (tomcat By java Language development ), The version corresponds to :**

tomcat5 need jdk4 Above support
tomcat6 need jdk5 Above support
tomcat7 need jdk6 Above support
tomcat8 need jdk7 Above support

3.2.2 install 、 start-up tomcat The server

1、 install tomcat The server

After decompressing the green version, you can use ( principle : Do not include Chinese and spaces in the installation path )

 Insert picture description here

After decompression, you need to configure JAVA_HOME environment variable , This variable points to jdk Root directory , Appoint tomcat Which location to use when starting jdk.

2、 start-up tomcat The server


How to configure JAVA_HOME environment variable :

Variable name : JAVA_HOME

A variable's value : C:\Program Files\Java\jdk1.8.0_45

Be careful : The value of the variable points to JDK Root directory ( No bin Catalog ), Don't add a semicolon after the variable value ;

2、 start-up tomcat The server

** start-up 、 close tomcat The server :** Enter... On the web page ,localhost:8080 A cat appears after entering, indicating that the startup is successful ,

If Shows that this site cannot be accessed , Maybe the server is not open or the port is written incorrectly .

localhost:8080 Refers to accessing the current computer to listen 8080 Server for ,8080 Namely Tomcat.( Because there may be many servers on one host , Different server port numbers are different )

adopt [tomcat root directory ]/bin/startup.bat You can start tomcat The server ; If you flash, it means java_Home The environment variable is not configured , Or the configuration does not take effect .

adopt [tomcat root directory ]/bin/shutdown.bat It can be turned off tomcat The server ;

Access the test server :

stay tomcat After the server starts , The server will listen by default 8080 port , It can be accessed through the following address tomcat The home page of the server : (localhost It's the host name : Equivalent to the address of the bank , Port number :8080, It is equivalent to the window number for handling business .

localhost: Port name of this machine

http://localhost:8080 This address is equivalent to accessing the local tomact The server , Equivalent to visiting
webapps Catalog .

3.2.3 modify tomcat Default port

 Insert picture description here

tomcat When the server starts , The default listening port is 8080, It means , We are visiting tomcat Server time , You need to specify the host name (localhost) perhaps IP Address (127.0.0.1) etc. Add port after . This is very inconvenient .

Can be 8080 Port to 80 port , because 80 The port is very special , You can omit it ( Only 80 Ports can be omitted , Other ports must be added when they can be accessed )

Modification method : find [tomcat The installation directory ]/conf/server.xml File and open the file , In the file 69 Yes <Connector> On the label port Property to 80 that will do .

<Connector port="80" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443" />

After finishing , Save the file , Restart the server ( Only when the server starts , Will be reloaded server.xml file ) The server that starts again will listen to the new port .

 Insert picture description here

Expansion problem : Port occupation problem :

Start up tomcat Server time , You may encounter port occupancy problems , Here's the picture :
 Insert picture description here

 Insert picture description here

Cause analysis : Because a port can only be used by one process ( Program ) Occupied by

** Situation 1 :** Maybe it was before tomcat The server is not completely shut down , Still occupying 8080( or 80) port , Cause the server to start again , Boot failure .( That is, the server does not close the port before opening the server for the second time , Still occupying )

spot x Closing the window may not be completely closed ( Most of them are closed ), A server can only occupy one port .

Solution : function shutdown.bat file , take tomcat Close it again according to the normal process . Start the server again , If it works , It means that the problem has been solved , Otherwise, it depends on the situation .

** Situation two :** Maybe other programs take up 8080( or 80) port , Causes the server to fail to start .( less )

Solution : Open one cmd window , adopt netstat -ano Command to view the processes active in the current system , find 8080( or 80) The process number corresponding to the port (PID), End the process according to the process number !

netstat: command , The Internet .

netstat -ano
 agreement Local address External address state PID
TCP 0.0.0.0:8080 0.0.0.0:0 LISTENING 6520
TCP 0.0.0.0:135 0.0.0.0:0 LISTENING 448
...
//6520 Occupying 8080 port , Then release the port through the following command .
taskkill /f /pid 6520

3.3 tomcat Directory structure

tomcat Introduction to directory structure

 Insert picture description here

tomcat There are many subdirectories under the root directory of the server installation , The purpose of these directories is :

bin: To hold tomcat Batch files in the server ( namely : The file used to enter the command ) The catalog of (xx.bat/xx.sh)
conf: To hold tomcat Directory of configuration files in the server ( among server.xml File is tomcat A very important file in the server .) This server The document is equivalent to the engine of a car
lib: To hold tomcat The server runtime depends on jar package .
logs: To hold tomcat Log files generated by the server runtime ( start-up tomcat The server will print a lot of log information , The log information will also be saved as a file to logs Under the table of contents )
temp: To hold tomcat Server generated temporary files ,tomcat I'll clean it up myself , You can ignore the directory
webapps: yes localhost【 Virtual host 】 Default managed Directory , Will develop good 【web application 】 The program is placed in webapps Under the table of contents , You can access it through a browser localhost In the host Web The resource file has .
It can be simply understood as :webapps Directory is web resources (html、css、js、 picture 、jsp etc. ) Storage directory of , take web The resource files are placed in this directory , You can access it through a browser .
stay eclipse Right click in --open with---web Brower Open locally , No one else can access . Putting it in this directory is equivalent to publishing files to the server , And other people's browsers access the server , The server returns a file for access .
work: To hold tomcat Working files generated by the server (JSP Translated Servlet The documents will be placed in work Under the table of contents ;session The file generated after object serialization will also be placed in work Under the table of contents ;)

3.4 Virtual hosts and Web application

 Insert picture description here

summary : Site : Website

(1) The virtual host is tomcat A site configured in the server (tomact The server can be configured with multiple sites , Browser access cannot be distinguished, such as , Baidu , Sina Is it running on the same server , He doesn't care , He is concerned about whether he can return to a Baidu page when visiting ), stay tomcat By default, the server provides a localhost Virtual host , The publishing directory of this host is webapps Catalog :

This file is in : 148 That's ok

 Insert picture description here

 Insert picture description here

That means , take Web The application is placed in webapps Under the table of contents , It means that it has been released to localhost In virtual host .

(2)Web The application is One holds a lot of Web resources (html、css、js、jsp、servlet、 Pictures, etc ) The catalog of , take Web Publish application to virtual host , You can access it through a browser Web These resource files in the application .

** Be careful :webapps Cannot store resources directly , Instead, it is stored in a directory, that is web application , I'm putting the catalogue in webapps Next .

Such as :**

 Insert picture description here

explain : localhost:8080 ---- First visit tomoact The server ( Because the resources are published to the server, access the server first .)

abc----- During a visit to tomoact Under server web application .

regist.html---- visit web Specific under resource application web Resource file .

3.5 localhost and 127.010.1:

stay computer network in ,localhost( Meaning for “ Local host ”, finger “ This computer ”) It's a network interface for the loop (loopback) A standard of Host name , Corresponding IP Address by 127.0.0.1(IPv4) and [::1](IPv6).

localhost Refers to your computer itself .

stay windows System, it becomes 127.0.0.1 Another name for , stay Unix Under the system , Check the network card configuration and you will find that it is a local loopback , Use... To some extent localhost Than 127.0.0.1 Hurry up .

stay Hosts file in ,localhost Point to the IP yes 127.0.0.1 This relationship can be modified .

3.6 web application

3.6.1 web Directory structure of application

news( Catalog ,web application ) This directory is divided into 2 class .
|-- Other directories , Put it in news Resource files in the root directory or other directories , The browser has direct access to
|-- WEB-INF Catalog , The resource files in this directory are protected , Browsers can't directly access ( It's not that you can't access , You can't directly access ) , This directory generally contains 2 A catalog , And a file . ( This file is complicated , Before class, the materials are , adopt eclipse Automatically created when created )
|-- classes Catalog , Used to store compiled class file
|-- lib Catalog , To hold web What the application depends on jar package
|-- web.xml file , For storage and web Application related configuration ( To configure Servlet、 Configure the home page 、 To configure session And so on ) This file uses eclipse To build a web Project time , It will generate automatically .

among news It's just a directory , It's also a web Applications , It can contain many resource files .

3.6.2 Deploy web Apply to virtual host 888888888

Direct will Web Copy the application directory to the directory managed by the virtual host , It's released to the virtual host

for example : take news directories copying webapps Under the table of contents , because webapps Directory is localhost The directory managed by the host by default , So it's equivalent to news The application is published to 了 localhost In the host .( namely :localhost:8080 It's equivalent to writing webapps Catalog ) Publish the file to the server , The server will check at any time . Changes can be seen at any time on the console .( Send to server , Unpublish )

Directory structure : webapps Catalog — yes tomact Directory under the server , And this directory is localhost The directory managed by the virtual host by default .

web The application is webapp Directory below , It manages web Resource file .

Host name ----web application ----web Resource file .

 Insert picture description here

Through such as Next path rule You can access localhost Under the main engine news Resource file under application :

http://localhost: port /news/xxx

3.7 Extended content ( understand )

Bleep bleep video link :https://www.bilibili.com/video/BV1Hg4y1B7dr

visit tomcat Server home page :http://localhost

visit news/hello.html:http://localhost/news/hello.html

Can you visit news/hello.html Make your path shorter ( For example, you can access only through the host name news/hello.html This web page )

3.7.1 To configure WEB Home page of the app

If not hello.html Configure to current Web Home page of the app , During a visit to hello.html The path when is :

http://localhost/news/hello.html

If you will hello.html Configure to current Web Home page of the app , Revisit hello.html The path when is :

http://localhost/news

In the path on ,/hello.html This path can be added , You can omit it .

Be careful : After configuration, you can write or not write .

take hello.html Configure as the home page of the current application , The way is : find [ At present Web application ]/WEB-INF/web.xml File and open , stay web.xml Add the following configuration inside the root tag of the file Set up :

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1">
<welcome-file-list>
<welcome-file>/hello.html</welcome-file>
<welcome-file>/hello1.html</welcome-file>
<welcome-file>/hello2.html</welcome-file>
</welcome-file-list>
</web-app>

After the configuration , Need to restart the server , Configuration will take effect .

3.7.2 Configure the default ( default )WEB application

It's already up there news/hello.html Configure to news Home page of the app , visit hello.html The path is :http://localhost/news/

If Will not news The application is configured as the default Web application , During a visit to news Under the hello.html( Home page ) The access path is :

http://localhost/news/

If you will news The application configuration is the default ( default )Web application , During a visit to hello.html( Home page ) The path becomes :

Be careful : Configure as default The application name can no longer be written . And the configuration web After the application home page is configured , You can write or not write .

http://localhost/

How to integrate news Configure as default ( default )Web application ( default Web There can only be one application )?:

take Web Change the name of the app to an uppercase ROOT, At present Web application Is a default Web application , Visit this again Web When applying the resource file under , In the access path You don't have to write Web The name of the application .

3.7.3 hit war package

war Bao He jar The bags are all java A compressed package format in a program .

If you develop a Java Basic engineering , You can compile class File and related configuration files into a jar package .

If you develop a web engineering , You can put a web All files and directories in the project are typed into one war package , Doing so The advantages are :

(1) take web The application is made into a war package , Transmission is more convenient , And the file size will become smaller .
(2) take war The package is published to the server , The server can recognize war Packet format , Will automatically war Unpack and release the package !

hit war The way to package is :

Enter into web Application directory , take Web Select all subdirectories and files under the application directory , Right click to compress into a xxx.zip package , And then xxx.zip Change it to xxx.war that will do !! And then put this war bag webapps Under the table of contents .

It should be noted that , If you have the following questions , May lead to war Will not automatically decompress :

(1) Will be Web When the application is packed into a compressed package , It didn't make a xxx.zip, But use rar Format or other format , Will cause automatic decompression failure !
(2) It's a fight war The name of the bag and Published web Application names cannot conflict , Will cause automatic decompression failure !
(3) war The directory name and file name contained in the package are in Chinese , It will also cause automatic decompression failure !

3.8 HTTP Overview of the agreement

3.8.1 What is? HTTP agreement ?

 Insert picture description here

HTTP Agreement is Used to specify the communication mode between browser and server / The rules

It mainly specifies the format of the request information sent by the browser to the server

And specifies the format of the response information sent by the server to the browser ( such as 2 People in different countries speak different languages , Add a rule to communicate in the same language , This is it. HTTP agreement .)

HTTP The agreement at work Basic principles to be followed

(1) One request , Only one response 10 Requests ,10 Secondary response
(2) Requests can only be initiated by the browser , The server can only passively wait for requests , Respond to requests .

3.9 HTTP protocol

IE Browser plug-ins :HttpWatch, It can monitor the content of communication between browser and server .( such as : The public security bureau can monitor 2 Dialogue between individuals )

Today's browsers , For example, Google or Firefox will come with this feature , You don't need to install this plug-in .

Web pages on browsers F12 Open developer tools —Network( The Internet )— Enter the address in the address field to access ( OK key )----- You can see the request and the corresponding content .

 Insert picture description here

Click on this request response file But this format is messy , Request and response are mixed together. It seems inconvenient

 Insert picture description here

A plug-in needs to be installed — charge , Not sent to the notes .

 Insert picture description here

3.9.1 HTTP request

 Insert picture description here

1、 Request line

GET /news/hello.html HTTP/1.1

(1)GET: Means the way of request , stay HTTP A total of... Are defined in the agreement 7 There are two ways to submit , But we only use GET and POST.

(2)/news/hello.html: Request resource path , Indicates which one is requested by the browser Web Application and which one web Resource file .

(3)HTTP/1.1: Protocol and version of the request .

2、 Several request headers ( Ask the head of the newspaper )

The request header is Key-Value structure , for example :

 Insert picture description here

Host:localhost -- Notification server , Which virtual host does the browser want to request .
Accept:text/html, appliaction/xhtml+xml,... -- Notification server , The type of response data that the browser can receive . such as :html Format page . The browser is a html The web page of .
...

( There is a blank line between , Used to separate request headers from request entities )

3、 Request entity content

If the request method is GET Submit , The requesting entity has no content !

If the request method is POST Submit , And the request carries data , There will be content in the request entity !

3.9.2 HTTP Respond to

content type Indicates the content type of the response content: Content

 Insert picture description here

​ The content of the response entity : Garbled code is caused by plug-in problems , The response has been parsed , In fact, there is no garbled code problem .

​ The request sent by the browser is html file , The corresponding entity content of the server is a web page .

1、 Status line

HTTP/1.1 200 OK ok8.5 At the beginning, you can omit ,200 The corresponding is Ok, Others are not necessarily

(1)HTTP/1.1: Indicates the protocol and version followed by the response

(2)200: Status code , Three digit numbers , Represents the result of the server's processing of the request .

 200: Indicates that the request was successfully processed
302: Indicates request redirection ( That is, further requests are needed to obtain the corresponding resources ) Like borrowing money from someone , This man didn't , Tell another person , You borrow money from another person .
304/307: Indicates that the browser is notified to use the cached file
404: Indicates that the resource requested by the browser does not exist ( Browser problems , Request path error )
500: Indicates that the server threw an exception while processing the request . ( The server is just a running environment , What really handles the request is servlet Program , and servlet It's just one. java Program ,java The program must throw an exception )

(3)OK: Descriptive phrase ( You can ignore ), It also represents the result of the server processing the request , It is consistent with the result indicated by the status code .

200 Indicates that the request has been successful ,ok Have a show

 200:OK
404:Not Found
500: Internal Server Error
...

2、 Several response heads : It's also key-value Format

Content-Type: Represents the data type of the server response ,text/html, image/*...
Content-Length: Indicates the length of the server response data , for example : 384 / byte
Set-Cookie: and cookie A head related to technology , It will be mentioned later .
...

3、 Response entity content

The response entity is the content of the file requested by the browser . for example : The browser requests a from the server hello.html file , The server will find hello.html file , Send the contents of the file to the browser as a response entity .

3.9.3 Content supplement

1、 problem 1: When is the request method GET Submit ? When is it POST Submit ?

Only when using forms (form), And clearly pass on the form method Specify the submission method as POST when , The way of request is POST Submit , Other ways GET Submit (AJAX With the exception of , It can be specified at will )

reflection : Judge whether the following request method is GET still POST?

(1)<form action="#"></form> -- GET Submit
(2)<form action="#" method="GET"></form> -- GET Submit
(3)<form action="#" method="POST"></form> -- POST Submit
(4) Click the hyperlink to access the server , for example :
<a href="http://www.baidu.com"> use Baidu Search </a> -- GET Submit
(5) Write directly in the address bar of the browser URL Address access server -- GET Submit

2、 problem 2:GET Submit and POST What's the difference between submitting ?

The main difference lies in the different transmission process of request parameters

GET Submit :

URL Address : stay WWW On , Every information resource has a unified and unique address on the Internet , The address is URL(Uniform Resource Locator, Uniform resource locator ), It is WWW The unified resource positioning mark , It means network address . It can be considered that 4 Part of it is made up of : agreement 、 host 、 port 、 route

such as :http://localhost:8080/news/html http It's followed by // , The path resource is / Division .

The protocol information of the website , There are two kinds of web pages :http:// and https:// It doesn't make sense to display this part of the content during web browsing , because Chrome Would be https The web address of the agreement provides a more eye-catching status identification ( Located at the left end of the address bar ).
When copying addresses ,Chrome The agreement information will be automatically added in front of the text .

Request parameters : such as User name for submitting the form , password .

  • Spell the data through question marks Next to the address bar URL After the address , Relatively unsafe .
  • Splice the data in the address bar URL After the address , The amount of data is limited , Usually not more than 1KB perhaps 4KB.

POST Submit :

  • POST Submission is through Requesting entity to transfer data Submit to server , It won't appear on the address bar , So it's relatively safer .
  • POST Submitted for approval Request the entity to submit Hand in the data , The amount of data is theoretically unlimited .

3、 summary :

​ Most of us still use get Submit ,post It's too troublesome to submit and write forms , We generally don't need to submit data .

  • If it's just a jump ( Such as , Jump from Baidu to Taobao ), No data in request , Use as much as possible GET Submit .
  • If there is data in the request , But the amount of data is small , And the data has no privacy , Use it as much as possible GET Submit .
  • If there is data in the request , The amount of data is relatively large or the data is relatively private , It is recommended to use POST Submit .

3.10 take Tomcat Integrate to Eclipse in

The purpose of integration : take Tomcat Server consolidation to Eclipse In the tools , Can pass Eclipse start-up 、 close tomcat The server , what's more , Can be very convenient in Eclipse Created in the Web Project publishing to Tomcat Running on the server .

Behind the frame springboot There will be embedded Tmocat, There's no need to worry about it here .

Bleep bleep video link :https://www.bilibili.com/video/BV1wz411z73V

3.10.1 Mode one : stay window Configure in preferences Tomcat

1、 Click on Window --> Preferences( preferences ):

 Insert picture description here

2、 Click... In the preferences window Server --> Runtime Environments --> add:

​ server ( The server ) runtime: The elapsed time

 Insert picture description here

3、 Select in the pop-up window --> Apache --> Apache Tomcat v8.5, It should be noted that , You have to install it according to your own tomcat edition Make a selection , For example, I installed 8.5 Version of tomcat, So here we choose Apache Tomcat v8.5.

If not, no 8.5 explain eclipse Version of is low , Can upgrade eclipse Version or reduction Tomact edition .
 Insert picture description here

4、 Configure... In the following window tomcat The installation root directory of the server , You can copy the path directly into the second input box ; You can also click on the following Browse Button select... In the file manager tomcat Server installation root directory .

 Insert picture description here

Finally, click finish To complete Tomcat Integrate to Eclipse Configuration in .

Apply and close: Apply and close ( apply apply , application )

3.10.2 Mode two : Creating Web Project-time configuration Tomcat

1、 If you're creating Web Project time ,Target runtime The optional server is not configured in the option , You can click the option on the right to configure

Click to enter the next operation .

 Insert picture description here

2、 Select in the pop-up window --> Apache --> Apache Tomcat v8.5, It should be noted that , You have to install it according to your own tomcat Version selection , For example, I installed 8.5 Version of tomcat, So here we choose Apache Tomcat v8.5.

[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-TO5iotGa-1638456116106)(/image-20201013155050044.png)]

3、 Configure... In the following window tomcat The installation root directory of the server , You can copy the path directly into the second input box ; You can also click on the following Browse Button select... In the file manager tomcat Server installation root directory .

[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-dz7lXPCJ-1638456116107)(/image-20201013155107547.png)]

Finally, click finish To complete Tomcat Integrate to Eclipse Configuration in .

4、 After the last step , go back to Web View window created by the project , Check it again "Target runtime" Options , as follows :

[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-ILSnwYfH-1638456116107)(/image-20201013155119954.png)]

3.10.3 Integrate into Eclipse Medium tomcat from Eclipse Delete in

If you want to integrate into Eclipse Medium tomcat from Eclipse Delete : Click on Windows --> Preferences --> Server --> Runtime Environments, Select the server to delete , Click the delete button on the right to delete , Finally, click Apply and Close Save the settings ! edit: edit , You can change the location of the server .

 Insert picture description here

3.10.4 stay Eclipse Created in Server And removal Server

It explains how to Tomcat Integrate to Eclipse in , After integration , Need to be in Eclipse Create a Server( The server ) Before starting tomcat、 close tomcat Wait for the operation .

1、Eclipse Find Servers window :

 Insert picture description here

2、 If not, you can get to Window --> Show View --> Other Mid search "servers", Here's the picture :

[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-dVrcHROy-1638456116109)(/image-20201013155208878.png)]

[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-odffDYTE-1638456116109)(/image-20201013155220937.png)]

3、 stay Server Click in the window “No servers are available…” link :

[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-xMvx1M5q-1638456116110)(/image-20201013155233017.png)]

4、 In the pop-up window , Keep default configuration , Click directly to finish

If the default server in the pop-up window is not tomcat, It means that... Has not been before Tomcat Integrate to Eclipse in .

 Insert picture description here

5、 After completing the previous step ,Eclipses There will be one more on the left Servers project ,Servers The created... Will appear in the window Server( such as :Tmoact v8.5 Server at localhost [Stopped,Republish]), That is to say tomcat The server .

server The server and servers The project is used together , This project puts the configuration file of the server .

Be careful :① Situated Servers Project cannot be closed (close), You can't delete (delete)

If the server goes wrong in the future , Want to create a new server . 2 Delete all .

​ Select the server ----- Right click delete. servers---- Right click delete---- Check the box to completely delete... From the hard disk

 Insert picture description here

6、 After creating Server after , double-click tomcat, You can modify Tomcat Server configuration

(1) take Server Locations Switch the option in to the second option

(2) take Deploy Path The content in the input box on the right is changed to webapps.ctrl+s Save the configuration

[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-RhnM0HF0-1638456116111)(/image-20201013155313120.png)]vv

The above configuration is to ensure that Eclipse In the release Web Applied to the tomcat When the server , You can publish projects to tomcat Server's webapps Under the table of contents .

** If you don't configure , It can lead to tomcat Server webapps Under the Web App can't access .** Because after integration, through eclipse Start the server and it will change webapps Published catalog , This release directory is useless .

 Insert picture description here

7、 If you want to remove the added Server, You need to delete ① Situated Servers project ( Right click delete, To completely remove from the hard disk ), And delete ② Situated tomcat The server ( Right click delete)

 Insert picture description here

3.10.5 tomcat Right click option introduction

[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-7lGaItfW-1638456116113)(/image-20201013155353445.png)]

a) Start: Used to start tomcat The server , Such as If it has started , Is displayed ReStart, The function is to restart the server

b) Stop: Used to stop the server Or click the red button

c) Add and Remove: take Web Application deployment to tomcat Server , Or remove the deployed in the server Web application

It's fine too Right click on the files published to the server one by one remove remove .( Remove files published to files , commonly c ,d In combination with .)

d) Clean: The function is to publish to Eclipse Their own webapps Delete and redeploy the items in the directory

e) Clean Tomcat Work Directory: The function is to be in tomcat Stored during operation work Delete the files in the directory

3.10.6 tomcat Common causes of startup failure

problem 1:tomcat Server start failed -1

If you start the server , Server start failed , And the pop-up window displays the following exception information :

 Insert picture description here

According to the above description , It can be seen that it is 8005、8080、8009 Ports are occupied at the same time , There is only one possibility , It has been started before tomcat Or opened before tomcat Not completely closed .

Solution : To tomcat Installation directory found bin In the directory shutdown.bat file , Double click Run to shut down the server , Until then Eclipse Start the server !

problem 2:tomcat Server start failed -2

If you start the server , Server start failed , And the pop-up window displays the following exception information :

 Insert picture description here

resolvent :

(1) You can delete all the files in the server first Web Apply remove ( Right click on the server ,Add and Remove–>Remove All–>Finish

(2) Right click to execute the options in the server clean and Clean Tomcat Work Directory

(3) Start the server again , If no error is reported during startup , shows tomcat The server itself has no problem , Then publish the project to run to tomcat in , Start the server again , Watch for errors . If yes, it is the problem of the project itself .

(4) If you remove all Web application , start-up tomcat Server error , shows tomcat There's something wrong with it , Can be tomcat The server is reconfigured once to Eclipse in ( take tomcat and Server Item delete , Then click the link to recreate Server)

4 Servlet

4.1 Servlet summary

4.1.1 What is? Servlet?

servlet( Little service program )

Servlet By SUN A dynamic provided by the company Web Resource development technology (web: The Internet )

 static state Web resources : Different people , After visiting under different conditions, you will see the same effect , Such resources are called static resources Web resources (html、css、js etc. Development technology of static resources )( Not based on whether there is animation effect )
dynamic Web resources : Different effects can be seen under different access conditions , Such resources are called dynamic Web resources
(Servlet、jsp、.NET、PHP etc. Development technology of dynamic resources ) Like visiting different people's shopping carts Read dao NET

Servlet It's essentially a paragraph Java Program , And before Java Program ** The difference is ,**Servlet The program cannot run independently , No, main function , Need to put Servlet Put the program in the server ( such as tomcat The server ), Only when called by the server can .

Servlet: Server side Java Program .

Servlet It runs on the server side Java Program , What does it do ?

Its function is to process the requests received by the server ( That is, the server receives the request ,servlet Processing requests )

Servlet Life cycle of :

1、 Initialization phase ,Servlet The container creates a Servlet Instance and call 【init()】 Method ;

2、 Processing client request phase , Every time a client request is received , The server will generate a new thread to process ;

3、 Termination phase , call destroy Method termination .

jsp: Can you write a paragraph java Code HTML On the right is a database

 Insert picture description here

4.2 Development Servlet Program


4.2.1 Development Servlet Procedure steps

First step : Write a class , Achieve one Servlet Interface or inheritance Servlet Subclass of interface (GenericServlet/HttpServlet), And implement the methods

Servlet Interface
|-- GenericServlet class ( abstract class )
|-- HttpServlet class This is usually used

The second step : stay web Applied web.xml Configuration in file Servlet The path of external access of the program .

because servlet The compiled program is placed in class Under the table of contents , and class The directory is placed in web-inf Catalog , and web-INF The directory cannot be accessed directly. It needs to be in web.xml File configuration path . The default is /+ Class name .

Eclipse Creating a Servlet when , Will be in web.xml Generate... In file Servlet To configure , So we don't need to configure it manually .

4.2.2 Use Eclipse establish Web project

 Insert picture description here

 Insert picture description here

Above is Web Project in drawing view (Project) And package view (package) Lower structure , Package view is recommended !

Drawing views are confusing , You don't have to use the one above , Recommended package view , Structure is clearer .

wibdow–show view—other—package Explorer

1、 Create a Web engineering : In the left window , Click on Right mouse button —> New —>
Dynamic Web Project. Dynamic projects can have static resources or dynamic resources

namely : Static projects can develop static resources , Dynamic items can develop both static and dynamic items .
 Insert picture description here

2、 Then the following window will pop up :

[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-bbNriFT9-1638456116117)(/image-20201013155555860.png)]

Be careful :

Double-click to open web,xml file Click on source Enter editing status , There may be false positives .j

solve : Choose web.xml file – Right click Validate( check )

(1) 3.0 Version will not create web.xml file ,
And create Servlet When they were Not in web.xml Generate... In file Servlet Related configuration information , Remember to change to 2.5.

(2) Target runtime If there is no optional server in the options , Click on the right "New
Runtime…" To configure .

The detailed operation steps are shown in 《5.2 To configure Target runtime(Web Project operation environment )》

3、Eclipse Created in the Web Project directory structure :

 Insert picture description here

(1) day09: Project name / Project name
(2) src: Source directory , Created java Source file 、 The configuration file (properties、xml Documents, etc. ) Can be placed in src Source directory
(3) build/classes: The output directory of the compiled file , src The files in the source directory will be output to classes Under the table of contents .
Among them classes The directory will be placed in WEB-INF Under the table of contents , Publish to the server with the project
(4) WebContent: Namely Web Application directory , It can store html、css、js、jsp、 Pictures and compiled class file 、jar package 、web.xml Documents, etc. . Publish the project to the server in the future , It's really just the WebContent All of the content in is published to the server together .
(5) WebContent/WEB-INF/lib: It is used to store the... That the current project depends on jar package . For example, to visit mysql database , Import required mysql Drive pack , Direct will jar Package copy to lib Under the directory !( You don't have to do it anymore build path --> add to build path)

4.2.3 Use Eclipse establish Servlet

1、 Select... In the project src Catalog , Right mouse button —> New —> Servlet

because :servlet The essence is java Program , and java Files in src Under this source directory .

 Insert picture description here

2、 In the pop-up window , Fill in the contents according to the prompts :

 Insert picture description here

3、 Click on finish Can finish Servlet The creation process , Create good Servlet as follows :
 Insert picture description here

public class HelloServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException,IOException{
// Get a character output stream , Used to send data to the browser alt shift+l stay () Back , Shortcut key to accept the return value of the method
PrintWriter out = response.getWriter();
// Because the default code is iso8859-1, So the output of Chinese data will become a question mark
out.write( "Hello Servlet.."+new Date() );
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}

The first line is serialized id, There is no serialization here , But after deletion, a warning will be reported , So don't delete .

adopt Eclipse establish Servlet, Default inheritance HttpServlet. because HttpServlet It's also Servlet Subclass of interface , Give Way HelloServlet Inherit HttpServlet, It is equivalent to indirectly realizing Servlet Interface .

Inherit HttpServlet class , The default will override doGet Methods and doPost Method , The functions of the two methods are :

Browser send request , The server calls service Method , It's inherited HttpServlet Method ,service The internal will judge the request method , If it is get Submit and call get Method , If it is post Submit and call post Method .

Be careful :servlet Not necessarily get and post Method . But there must be service Method

*** doGet Method :** When the browser sends the request in GET When submitting , Will call doGet Method to process the request

*** doPost Method :** When the browser sends the request in POST When submitting , Will call doPost Method to process the request

Tips : If so GET Submit and POST When the submission processing code is the same , You can write the code in one of the methods ( For example, in doGet in ), And in another way ( for example doPost) Medium tune method . thus , Whether it's GET Submit or POST Submit , Final doGet Methods will be implemented , Will process the request !! This way you can write less code .

package com.tedu;
import java.io.IOException;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class HelloServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/* When the browser accesses the current Servlet, If the request method is GET Submit , Will execute doGet Method to process the request */
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// Processing requests
System.out.println("SecondServlet.doGet()...");
// Get the output stream that can respond to data to the browser
response.getWriter().write( "SecondServlet.."+ new Date() );
}
/* When the browser accesses the current Servlet, If the request method is POST Submit , Will execute doPost Method to process the request
* Why are you in doPost Call in doGet: If GET Submit and POST Submission is handled in the same way ( That is to deal with GET Request and POST Requested
* The code is exactly the same ), To avoid code redundancy , Can be in doPost Call in method doGet, Then put all the code that handles the request in
* doGet In the method , such , Whether it's GET Submit or POST Submit ,doGet The method will certainly execute ! */
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}

4.2.4 Servlet stay web.xml Configuration in

Through Eclipse establish Servlet when , Will be automatically web.xml In file Servlet Configuration of relevant information

( Be careful : If it's copying Servlet Class file , But the configuration information will not be copied , You need to manually add the configuration yourself , Otherwise, it will be copied Servlet Will not be accessible !) If F2 hold Servlet Class name change ,Web.xml The fully qualified class name in the file needs to be changed manually , The following access path can be changed or not . Changing the name of the following path can deceive others , But it's actually the path of the class name .

The path with package name appears in the browser , Description: there is no corresponding configuration information .

// At least this 8 That's ok
<servlet>
<servlet-name>HelloServlet</servlet-name> // this 2 Up and down name The name needs to be consistent . The name is the same , The same description is the same group .
<!-- The fully qualified class name of the class configured here , This is to enable the server to obtain the name of the full class in the future SecondServlet Class bytecode object , Then create an instance of this class through the bytecode object .-->
<servlet-class>com.tedu.HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloServlet</servlet-name>
<!-- The configuration here is the current Servlet Access path of , The browser can access the inside of the server through this path SecondServlet, The server calls this Servlet The default is : / + Class name -->
<url-pattern>/HelloServlet</url-pattern>
</servlet-mapping>

About the configuration information above :

a) Eclipse For every one created Servlet, Will be in web.xml Add two tags to the file :<servlet> and <servlet-mapping> label ( You can think of these two labels as labels of a group )

**b) **<servlet> and <servlet-mapping> There will be one in the label <servlet-name> label , The content of the label can be changed , But I want to change these two <servlet-name> The content of the label must also be consistent .

c) <servlet-class> Tags are used to configure Servlet The fully qualified class name of the class ( Package name + Class name )

We need to pay attention to : If you're creating Servlet It has been modified after Servlet The name of the class , This place also needs to be changed together , Otherwise it will appear "ClassNotFoundException" Class cannot find exception 404 , The following access path can be changed or not , Changing it is equivalent to camouflage the path , But in fact, it is the file path accessed .

**d) **<url-pattern> The tag is used to configure the path the browser uses to access the current Servlet( namely Servlet The path of external visit ), The default path is :/+ Class name

for example : For the above HelloServlet Configured <url-pattern> by **/HelloServlet**, So our access path in the browser is :

http:// Host name /web Project access path **/HelloServlet**

4.2.5 function Servlet Program 、 Access test

Summarize the operation mode :

test: Right click the method name —test util

java project — Right click —run as—java application

servlet---- Right click —run as — run on server

** If the library is deleted by mistake when creating the project : The program will definitely report an error . ** 88888888888888888888

If you delete Apache Tomact v8.5(tomact The running environment of the server ): Right click on the project ( Package view )—Bulid Path — AddLibraries–Server Runtime—next— Select the server —finish

 Insert picture description here

If deleted by mistake jdk(jdk The basic core class library ), Right click on the project ( Package view )—Bulid Path — AddLibraries—jre … ----Alternate JRE Or by default jre library .

 Insert picture description here

The one above is self-contained jdk It's better not to use it .

1、 visit Servlet Mode one :

If you run it for the first time , You need to create tomcat The server , That is to say Servers Click the link in the window to create a tomcat The server , And just create it once !

(1) Publish the project to the server : Right click on the server --> Click on "add and remove" Will the current web Publish the project to the server , And click Finish .

(2) start-up tomcat The server : Right click on the server Start You can start the server

(3) Access... Through a browser Servlet: Open the local browser , Access through the path , Can access Servlet Program

Be careful : such as : This day09 Instead, the project is It's inside WEB-INF Under the table of contents , and WEB_INF The resources in this directory cannot be accessed directly .

The path in this file cannot be accessed directly , Unlike html, picture ,js It can be accessed directly according to the path it stores .servlet Access has everything to do with where it is stored , To build a servlet Will be in xml One more line of configuration information in the file is the external access path , Class name by default , But there is no generation , This needs to be compiled by yourself . Fill in... In the browser The path in the tag , Case sensitive . Label content : Reference resources ( 4.24 Servlet stay web.xml Configuration in )

servlet The format of the external access path of the file is : Host name _ port + Project name _ Class name /

http://localhost: port / Project name /HelloServlet Class name

Browser access path : You can't look at the project on the left eclipse Structure , It's about publishing to tomact The directory of the server

2、 visit Servlet Mode two : You don't have to write your own path or publish it yourself . Top 3 Step .

stay eclipse In the project on the left servlet On the perhaps In this servlet Right click on the contents of the file ----run as …

(1) Running Servlet Right click on –-> “Run As” —> "1 Run on Server"

]

(2) In the pop-up window , Just click finish !!!

[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-n1oS2YZH-1638456116122)(/image-20201013155736233.png)]

(3) The operation results are as follows :

[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-sfBc5K94-1638456116122)(/image-20201013155747973.png)]

Or open the browser , Copy the path in the figure above :

http://localhost:8080/Hello/HelloServlet, Paste it into the browser's address bar , Return to visit :

 Insert picture description here

4.2.6 Eclipse How to publish a Web application

The first one is :

First step , Publish to server : Right click on the server ( That's it server)—Add and Remove.( The left side of the window shows the publishable Directory , Double click publish to the right , Double click on the right to remove the publication )—finish Under the server, you can expand to see the project .

You can also right-click on the item to remove .

The second step , Start the server :

 Insert picture description here

The third step , visit servlet: servlet The published directory is in web-inf Directory cannot be accessed directly , Used in web.xml The path of the configuration in the file . The default is / + Project name .

 Insert picture description here

The second kind : stay servlet Inside or in the leftmost project directory servlet file On ---- Right click —Run As—Run on Server

After clicking, a box will pop up — Choose a server ( Next, it will help you send the project to the server , After starting the server , Open the browser to access servlet)

namely : One step in this way is better than three steps in the first way , It's simpler .
 Insert picture description here

How the project is published to the server :

It can be understood as : Put the whole project webcontent Publish the directory to the server webapps Under the table of contents , In the webcontent Change to project name , Then I'm putting build Medium classes The directory is also placed in web-inf Under the table of contents .(class The directory stores the compiled class file )

The dynamic on the left web Project build It doesn't show this classes file , There are... In the workspace .

How to count quickly to find a workspace : Right click item -------show in —System Explorer— Will go directly to the directory of the workspace .

META_INF:META-INF A directory is actually a description of jar A directory of information in a file , We don't care

When passed eclipse take day09 Publish the project to the server , Is directly to the day09 Copy to the corresponding directory in the server ?

The release process is as follows ?

 Insert picture description here

4.2.7 Eclipse Default publish Web The location of the application

Tomcat By default, there is only one virtual host in the server , be called localhost host

and localhost Host release web The location of the application is webapps.

take day09 Publish to localhost In the host , What is it for? day09 The project is not in webapps Under the table of contents ?

--------------------------------------------------------------------------------------------------------

By default , Publish a Web Applied to the localhost In the host , Only need to Web Copy the application directory to webapps The release can be completed under the directory !

And will be Eclipse and Tomcat After integration ,2 Kind of , By default, the publishing path is changed to :

[ working space ]\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps

How to modify Eclipse Default publish Web Directory location of the application :

(1) Shut down the server , Remove all apps from the server

(2) Right click on the server --> clean

(3) double-click tomcat The server , Find... In the pop-up window Server location, Choose the second option

And put the... Below Deploy Path Change it to : webapps After finishing ,Ctrl+s Save the configuration !!

Reference resources : stay Eclipse Created in Server And removal Server There are... In the notes directory

4.3 Servlet Call the process ???


Access one of the servers through a browser Servlet Program , This Servlet How the program is executed ? How is it called ?

localhost/Hello/HelloServlet

Reference resources <<Servlet Call process diagram >> Now the notes \ The second stage \ Pre class materials + The notes (day06-day10)\day09.10-servlet The core \ picture

This servlet The examples are single ( namely servlet There is only one object in the server ), This object is the first access requested by the browser servlet when , The server found that there is no The instance will be created through reflection through the fully qualified class name of the class , Then use the method of this example, such as service Method to process the request .

 Insert picture description here

4.4 Extended content

4.4.1 add to Servlet Template

adopt Eclipse You can create a Servlet class , This is compared to the creation of... Through text editing tools such as Notepad Servlet, Can save configuration Servlet Time for , Improve our development efficiency .

But by Eclipse Generated Servlet Class contains many comments and default implementation code that we don't need , It takes a lot of time to delete these every time .

Next we can By adding template code , To generate Servlet The content of , In order to improve our development efficiency .

1、 So let's create one Servlet, Modify the content to the desired template format , And copy the contents , for example :

package ${
enclosing_package};
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/** * author: [email protected] * datetime: ${date} ${time} Will be replaced with the current date and time , Time and date when the class was created . */
public class ${
primary_type_name} extends HttpServlet {

// This business is useless , But without a warning in return .
private static final long serialVersionUID = 1L;
// When the browser accesses the current Servelet, If so, please request by GET Submit , Will execute doGet Method to process the request 
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

// Set the type of text And coding formats , Because it defaults to iso8859-1
response.setContentType("text/html;charset=utf-8");
// Get a character output stream , Used to send data to the browser 
PrintWriter out = response.getWriter();
}
/* When the browser accesses the current Servelet, If so, please request by POST Submit , Will execute doPost Method to process the request * Why are you in doPost Call in doPost: If GET Submit and Post Submission is handled in the same way ( That is to deal with GET Request and *Post The requested code is exactly the same ) To avoid code , Can be in dopost Call in method doGet, Then we'll deal with * The requested code is placed in doGet In the method , such , Whether it's GET Submit or POST Submit ,doGet The method will certainly execute . */
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

doGet(request, response);
}
}

2、 Click on the window --> Preferences
 Insert picture description here

3、 Click successively on the left side of the window that appears :Java --> Editor --> templates
–>( In the window on the right ) Click on New… :

 Insert picture description here

4、 Fill in the following in the new window that appears :

 Insert picture description here

5、 Replace package path and class name ( The function is to create Servlet Generated Servlet The package path and type of the current class are used in the template )

The cursor stays here : alt+ /

 Insert picture description here

The effect is as follows :

 Insert picture description here

 Insert picture description here

The effect is as follows :

 Insert picture description here

6、 Click on OK preservation , Create a new Servlet file , test

take Servlet Select all the contents in delete , And enter the "servlet", Press next “Alt+ /”
Prompt to generate what you want Servlet Template content !

 Insert picture description here

The effect is as follows :

 Insert picture description here

4.4.2 Servlet3.0 Characteristics of

Here's what we use Servlet2.5 edition , Actually JavaEE5.0 A sub specification of a specification , The minimum operating environment required is JDK5.0,tomcat5.0.

and Servlet3.0 The norm is JavaEE6.0 Sub specification of , The minimum required operating environment is JDK6.0,tomcat7.0. If you want to use Servlet3.0 standard , You need to create a dynamic Web You specify when you create a project . The specific usage is , stay Eclipse Create dynamic Web Engineering time , Specify the created “ dynamic Web Module version ” by 3.0 Or above , The Web The default in the project is no web.xml Of documents .**

[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-BQfAJPkB-1638456116132)(/image-20201013160058226.png)]

[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-IzBzIH14-1638456116132)(/image-20201013160107308.png)]

reflection : without web.xml file , So how to configure Servlet What about the access path of ?

By means of servlet Class with an annotation Servlet Access path . Here are a few Servlet3.0 An example of .

1、 stay 3.0 The dynamic of the above version Web Create a Servlet, as follows :

@WebServlet(value="/HelloServlet") value It can be omitted .
public class HelloServlet extends HttpServlet {

private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

PrintWriter out = response.getWriter();
out.write( "Hello Servlet3.0.."+new Date() );
}
}

among @WebServlet("/HelloServlet") The function of this annotation is to configure the current Servlet The access path of is /HelloServlet, perfect doGet The code in the method , Direct operation Servlet.

You can see the following effects in the browser :

 Insert picture description here

2、@WebServlet Multiple access paths can be configured in the annotation

stay @WebServlet The access path configured in the annotation , In fact, I omitted value attribute , The complete method is as follows :

@WebServlet(value="/HelloServlet"), It's just value It can be omitted

Because in the source code value Property is essentially an array of strings , So it can be value Property is assigned to an array direct quantity . for example :@WebServlet(value={})

take HelloServlet The annotation on the class is changed to the following form :

@WebServlet(value={
"/HelloServlet", "/hello01", "/hello02"})
public class HelloServlet extends HttpServlet {

private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

PrintWriter out = response.getWriter();
out.write( "Hello Servlet3.0.."+new Date() );
}
}

The effect of running in the browser is :

[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-lly8AIJX-1638456116133)(/image-20201013160131140.png)]

 Insert picture description here

3、 Can be value Property is replaced with urlPattern attribute , The effect is the same

@WebServlet(urlPatterns={
"/HelloServlet", "/hello01", "/hello02"})
public class HelloServlet extends HttpServlet {

private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

PrintWriter out = response.getWriter();
out.write( "Hello Servlet3.0.."+new Date() );
}
}

The effect of running in the browser is :
 Insert picture description here

4.5 request and response Introduce


request object response object

service(request ,response){

// adopt request Get information about the request

// adopt response Send response data to the browser

}

Be careful :servlet In class ,doget and dopost Methods can or can not , and service There must be methods , Don't write because of using the parent class service Method

request Represent HTTP The object that requests the information ,response Represent HTTP Objects that respond to information .

When the browser sends a request to access one of the servers Servlet when , The server will call Servlet Medium service Method to process the request . Calling service Method will be created before request and response object .

** among request Object encapsulates the request information sent by the browser to the server (** Request line 、 Request header 、 Request entity, etc ),response Object will encapsulate the response information that the server will send to the browser ( Status line 、 Response head 、 In response to the entity ), stay service After method execution , The server will response Data extraction from , according to HTTP The format of the protocol is sent to the browser .

( Do not send the response data directly Respond to the browser, but put it in response In the object , Because the format of sending the response directly is wrong , There may also be multiple requests .)

Every time the browser accesses the server , Server is calling service Method will be created before processing the request request and response object .( namely , Every time the server processes a request, it creates request and response object )

After the request is processed , At the end of the response , The server will destroy request and response object .

4.6 request object

4.6.1 Get request parameters

problem 1: What are request parameters ? Static resources such as :html You can also right-click the file —run as --run on server Publish to server access ,

It's on it servlet On the file — Right click .

The so-called request parameters , Is the data carried in the request sent by the browser to the server ( It doesn't distinguish between request methods ), for example : The user name submitted to the server through the form 、 Password etc. , Or data submitted with a question mark after a hyperlink , Are all request parameters . (get Submission can be done by using the form , and URL How to address ,post Submission can be made with form Forms, etc )

http://localhost/day10/TestParam?user=zhangsan&pwd=123&like= Basketball &like= football
Before the question mark is URL Address , After the question mark is the request parameter , The parameter name can be repeated . use & Connect

problem 2: How to get request parameters ?

(1)request.getParameter(String paramName) Parameter: Parameters
-- Get the corresponding parameter value according to the name of the request parameter , The return value is a string ;
-- If a parameter has more than one value , This method will only return the first value .
-- If you get a non-existent parameter , The return value is null
(2)request.getParameterValues(String paramName) values: value
-- Obtain an array of all parameter values corresponding to the name according to the name of the request parameter , The return value is an array of strings , It contains all the parameter values corresponding to the parameter name
-- If you get a non-existent parameter , The return value is null

Code example :

//1. Get the user name in the request parameter (user)
String user = request.getParameter("user");
System.out.println( "user="+user );
//2. Get the preferences in the request parameters (like)
String[] like = request.getParameterValues( "like" );
System.out.println( "like="+Arrays.toString( like ) );
// The address is printed directly , call Arrays Method to output the attribute value inside .

problem 3: How to solve the problem of Chinese garbled code when obtaining request parameters ?

servlet The problem of Chinese garbled code written in the document , This is the problem of garbled code in the request parameters .

When obtaining Chinese request parameters , There may be garbled problems ( And how to request 、tomcat Server version ), It can be divided into the following three situations :

(1) If the request is GET Submit , also tomcat yes 8.0 And later versions ,GET Chinese parameters submitted , There will be no garbled code when obtaining !(8.0 After the tomcat Include 8.0 In obtaining GET When submitting Chinese parameters , The problem of Chinese garbled code has been solved .)

Think about why post There will be garbled code when submitting ?

because post Submit and accept more than just a text ( The text can be used utf-8 Direct reception , It could be a file , picture , Audio to 2 I can't see .

(2) If the request is POST Submit , No matter what version it is tomcat The server , When getting Chinese parameters , There will be garbled code problems . because tomcat The bottom layer is receiving POST When submitting parameters for , By default iso8859-1 Coded reception , And there are no Chinese characters in this code , So when receiving Chinese parameters , There must be Chinese garbled code problem !

The solution is : The notification server is receiving POST When submitting parameters for , Use utf-8 Code to receive !

request.setCharacterEncoding("utf-8");

Be careful : This line of code will not affect GET Submit , Only right POST Submit valid !

This line of code should be executed before any code that gets parameters !

(3) If the request is GET Submit , also tomcat yes 7.0 And previous versions ,GET Chinese parameters submitted , There will be a garbled code problem when obtaining !

resolvent : stay [tomcat The installation directory ]/ conf/server.xml Of documents ( Modify the port )Connector On the label , Add one URIEncoding=“utf-8” attribute , as follows :

<Connector port="80" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443" URIEncoding="utf-8" />

At the same time [Eclipse]/Servers/[ At present tomcat The configuration directory corresponding to the server ]/server.xml In file , stay Connector On the label , Add one URIEncoding=“utf-8” attribute , ditto ! Because it may be used to install Tomact Self contained xml file , It is wrong to change one that is still possible , therefore 2 Make sure everything is correct .

4.6.2 Implement request forwarding

Request forwarding is a way to jump the internal resources of the server , That is, when the browser sends a request to access a resource in the server (A) when , The resource forwards the request to another resource (B) It is processed by resources B The process of responding , It's called request forwarding .

Request forwarding and redirection are both the jumping methods of resources , But the jump process is different .

 Insert picture description here

The characteristics of request forwarding :

(1) Forwarding is a request , One response
(2) Before and after the request is forwarded , The browser's address bar address doesn't change .( browser -- visit --> A -- forward --> B, The address bar address always points to A The address of ) It's like you borrow money from me , I don't have , I told Miss Liu , Miss Liu gave out the money . But you don't know , In your opinion, it's the money given to you by the browser. I thought it was the money I gave you . Server jump , The browser doesn't see , So the address won't change .
(3) Before and after request forwarding request Object is the same ( Before forwarding, at A Medium request And forward to B after ,B Medium request Objects and A Medium request Object is the same . Based on this , Can pass request from A Bring data to B)
(4) The two resources before and after request forwarding must belong to the same Web application , Otherwise, there will be no forwarding .(A-- forward -->B,A and B Must belong to the same Web application !) request: request

Request forwarding implementation : get Method, the requested object and the responded object .

//Dispatcher: dispatcher 
request.getRequestDispatcher(url Address / Forward to the address of the resource ).forward(req, res);

Code example :

/* Forward the request to BServlet * http://localhost:8080/day10/AServlet * http://localhost:8080/day10/BServlet * stay A It says in it B Relative path of , hold A Request forwarded to B * If and are forwarded to different web application :http://localhost:8080/day09/BServlet, Impossible to achieve . */
request.getRequestDispatcher("index.jsp").forward(request, response);

4.6.3 Use as a domain object

I didn't use the frame before servlet+jsp+javabin Development , Usually forward +request On the object map Set from servlet Send data to jsp.

After using the framework, when transmitting data from controller Send data to jsp Also use request On the object map+ Request forwarding .

This request Upper map Collections are often called domain objects .

Note that the scope of the domain object is a request ,2 It's impossible to request data transmission for one time .( Because request forwarding is a request , The domain object is the same , therefore , Only guarantee request Only the same data can be transmitted )

If it is 2 Requests ( Redirect ), And objects are destroyed after a request. Of course, the parameters carried in them are also destroyed . The new domain object created cannot carry data without this parameter .

So how to carry data in multiple requests ? use session

summary : request Domain objects are used in a request , and session Used in multiple requests .

request When forwarding , adopt request.setAttribute Methods and request.getAttribute Method to bring data to the destination **, It is through request Object map Set with data **, This request On the object map Assemble and request The scope of an object is called a domain object .

If an object has a range that can be accessed , Through the on this object map Collection can realize data sharing in the whole range . Such objects are called domain objects .// pageContext request session application (4 Domain objects , The first and the fourth don't work very well now ) Attribute: attribute

stay request Object provides a domain object (map) The method of storing data and the method of getting data :

request.setAttribute(String attrName, Object attrValue);
-- Go to request A domain attribute is stored in the domain , Property name (key) It can only be a string , Property value (value) It can be any type (object).
// Store data in request Of map aggregate (request Domain object ) in 
request.setAttribute( "name", " Nicholas Zhao si " );
request.getAttribute(String attrName);
-- According to the property name (key) Get the corresponding property value (value). Back to a Object type , Want to use string Type reception requires forced conversion .
// take request Of map aggregate (request Domain ) Take out the data in 
String name = (String)request.getAttribute( "name" );
System.out.println("name="+name);

request Three characteristics of domain objects :

** Life cycle :** Call on the server Servlet programmatic service Before method , Will create a representation of the request request object , After the request is processed , At the end of the response , Will destroy request object .

** Scope of action :** Within the scope of one request , Can get the same request object .

The main function : Used with request forwarding , from Servlet Bring data to JSP( Take the data to the destination )

​ Parameters attribute

Extended content : request Object's getParameter and getAttribute What's the difference ?

  • getParameter() Method is used to obtain ( Sent from the browser ) Request parameter , Request parameters cannot be set , Only the browser can send it to the server , On the server side, it passes through getParameter Method to get the parameters in the request ( only Yes get There is no way set Method )
  • getAttribute() The method is used to get from request When getting domain properties from the domain With , Domain attributes have to be stored in the domain first ( That is, you have to pass setAttribute Method to store data in request domain ), Re pass getAttribute() Method to get... From the domain .( This is pre-existing retrieval , The request parameter is )

4.7 response object

response Represent HTTP Objects that respond to information .

4.7.1 Send data to client

PrintWriter out = response.getWriter();

Because the server is passing response When sending data from the obtained stream **, By default iso8859-1 code **, And there are no Chinese characters in this code , So I'm passing through response When sending Chinese data from the obtained stream , There will be a mess .

The solution is : Before responding to data , Notification server usage utf-8 send data . response : Respond to

/* Notify the server when responding to data , Use utf-8 code * The browser can also be used to notify utf-8 Receiving data from the server */
response.setContentType( "text/html;charset=utf-8" );
PrintWriter out = response.getWriter();
out.write( " Hello " );

4.7.2 Implement redirection

On the browser —F12 Developer tools ----network() The Internet , How many requests can I see .

When the browser sends a request to the server to access a resource A, resources A In response, notify the browser that further requests are required to obtain the corresponding resources , The browser sends a request again to access the resources in the server B, Ultimately, resources B Respond to the resources the browser wants to get , This process is called redirection .

in other words : The browser sends a request to The server A, The server returns a request to the browser to notify the browser to access the server B. The browser then accesses the browser according to this response B. But there is no interval between them, and the speed is very fast , That is, it looks like the browser sends a request to the server , By the server B Respond to . In fact, it is sent to the server first A Of .

 Insert picture description here

Features of redirection :

(1) Redirection is two requests 、 Two responses
(2) Before and after redirection , The address bar of the browser will change .( Because both requests were initiated through the browser , The browser knows the jump process , So the address bar address changes )
Borrow money from me , I don't have , I tell you, Miss Liu has , You go to Mr. Liu to borrow money , Miss Liu is lending you money .
(3) Before and after redirection request The object is not the same ( Because redirection is two requests , The server creates two different request object ,request The object is not the same , It can't be redirected through request Take the data to the destination .)
(4) The two resources before and after redirection can come from different web The application can also be the same web application , It could even be from different servers .( There is no limit between the two resources that jump )

Implementation code :

response.sendRedirect( Is redirected to the resource URL Address );

 Insert picture description here

Code example :

 Written in doget In the method
/* test 1: Resource jump within the same application , from /day10/Hello01 Redirect to /day10/Hello02 * http://localhost:8080/day10/Hello01 * http://localhost:8080/day10/Hello02 */
response.sendRedirect("Hello02"); // Relative paths 
//response.sendRedirect("http://localhost:8080/day10/Hello02"); // Absolute path 
/* test 2: Different Web Application internal resource jump , from day10/Hello01 Redirect to /day09/HelloServlet * http://localhost:8080/day10/Hello01 * http://localhost:8080/day09/HelloServlet */
//response.sendRedirect( "../day09/HelloServlet" ); // Relative paths 
//response.sendRedirect( "http://localhost:8080/day09/HelloServlet" ); // Absolute path 
/* test 3: Jump of internal resources of different servers , from day10/Hello01 Redirect to Baidu /tmooc home page * http://localhost:8080/day10/Hello01 * http://www.baidu.com */ Do not write relative path if the host name is different , Use absolute path , The agreement should also be written correctly , Otherwise it will be regarded as a relative path
//response.sendRedirect( "http://www.baidu.com" ); // Absolute path 
out.write( "Hello01 Response succeeded ..." ); // Because there is no time interval between redirection and jump , So you can't see this response on the browser 

summary -1: Request forwarding (forward) Redirection (redirect) The difference between ?

(1) Request forwarding is a request , One response ; Redirection is two requests, two responses
(2) The address bar address will not change before and after the request is forwarded ; The address bar address will change before and after redirection
(3) Before and after request forwarding request Object is the same , Can cooperate with request The domain object takes the data to the destination ; And before and after redirection request The object is not the same , Can't combine request Domain objects have data before and after redirection .
(4) Request forwarding requires that two resources belong to the same Web application ; The two resources for redirection can be the same Web application , Or not the same Web application , It can even come from different hosts or servers .

summary -2: When to forward by request (forward)? When to use redirection (redirect)?

(1) If you want the address bar address not to change before and after the jump , You can only use forwarding ; If you want the address bar to change before and after the jump , You can only use redirection
(2) If you want to be around the jump , Can pass request Object to bring data to the destination , You can only use forwarding
(3) If it's just a jump , There are no other requirements , Forwarding is recommended at this time ( Forwarding is a request , One response , Can reduce the number of times to visit the server , Reduce server stress )

equest.getRequestDispatcher(url Address / Forward to the address of the resource ).forward(req, res);


** Code example :**
```java
/* Forward the request to BServlet
* http://localhost:8080/day10/AServlet
* http://localhost:8080/day10/BServlet
* stay A It says in it B Relative path of , hold A Request forwarded to B
* If and are forwarded to different web application :http://localhost:8080/day09/BServlet,
Impossible to achieve .
*/
request.getRequestDispatcher("index.jsp").forward(request, response);

4.7.3 Use as a domain object

I didn't use the frame before servlet+jsp+javabin Development , Usually forward +request On the object map Set from servlet Send data to jsp.

After using the framework, when transmitting data from controller Send data to jsp Also use request On the object map+ Request forwarding .

This request Upper map Collections are often called domain objects .

Note that the scope of the domain object is a request ,2 It's impossible to request data transmission for one time .( Because request forwarding is a request , The domain object is the same , therefore , Only guarantee request Only the same data can be transmitted )

If it is 2 Requests ( Redirect ), And objects are destroyed after a request. Of course, the parameters carried in them are also destroyed . The new domain object created cannot carry data without this parameter .

So how to carry data in multiple requests ? use session

summary : request Domain objects are used in a request , and session Used in multiple requests .

request When forwarding , adopt request.setAttribute Methods and request.getAttribute Method to bring data to the destination **, It is through request Object map Set with data **, This request On the object map Assemble and request The scope of an object is called a domain object .

If an object has a range that can be accessed , Through the on this object map Collection can realize data sharing in the whole range . Such objects are called domain objects .// pageContext request session application (4 Domain objects , The first and the fourth don't work very well now ) Attribute: attribute

stay request Object provides a domain object (map) The method of storing data and the method of getting data :

request.setAttribute(String attrName, Object attrValue);
-- Go to request A domain attribute is stored in the domain , Property name (key) It can only be a string , Property value (value) It can be any type (object).
// Store data in request Of map aggregate (request Domain object ) in 
request.setAttribute( "name", " Nicholas Zhao si " );
request.getAttribute(String attrName);
-- According to the property name (key) Get the corresponding property value (value). Back to a Object type , Want to use string Type reception requires forced conversion .
// take request Of map aggregate (request Domain ) Take out the data in 
String name = (String)request.getAttribute( "name" );
System.out.println("name="+name);

request Three characteristics of domain objects :

** Life cycle :** Call on the server Servlet programmatic service Before method , Will create a representation of the request request object , After the request is processed , At the end of the response , Will destroy request object .

** Scope of action :** Within the scope of one request , Can get the same request object .

The main function : Used with request forwarding , from Servlet Bring data to JSP( Take the data to the destination )

​ Parameters attribute

Extended content : request Object's getParameter and getAttribute What's the difference ?

  • getParameter() Method is used to obtain ( Sent from the browser ) Request parameter , Request parameters cannot be set , Only the browser can send it to the server , On the server side, it passes through getParameter Method to get the parameters in the request ( only Yes get There is no way set Method )
  • getAttribute() The method is used to get from request When getting domain properties from the domain With , Domain attributes have to be stored in the domain first ( That is, you have to pass setAttribute Method to store data in request domain ), Re pass getAttribute() Method to get... From the domain .( This is pre-existing retrieval , The request parameter is )

4.8 response object


response Represent HTTP Objects that respond to information .

4.8.1 Send data to client

PrintWriter out = response.getWriter();

Because the server is passing response When sending data from the obtained stream **, By default iso8859-1 code **, And there are no Chinese characters in this code , So I'm passing through response When sending Chinese data from the obtained stream , There will be a mess .

The solution is : Before responding to data , Notification server usage utf-8 send data . response : Respond to

/* Notify the server when responding to data , Use utf-8 code * The browser can also be used to notify utf-8 Receiving data from the server */
response.setContentType( "text/html;charset=utf-8" );
PrintWriter out = response.getWriter();
out.write( " Hello " );

4.8.2 Implement redirection

On the browser —F12 Developer tools ----network() The Internet , How many requests can I see .

When the browser sends a request to the server to access a resource A, resources A In response, notify the browser that further requests are required to obtain the corresponding resources , The browser sends a request again to access the resources in the server B, Ultimately, resources B Respond to the resources the browser wants to get , This process is called redirection .

in other words : The browser sends a request to The server A, The server returns a request to the browser to notify the browser to access the server B. The browser then accesses the browser according to this response B. But there is no interval between them, and the speed is very fast , That is, it looks like the browser sends a request to the server , By the server B Respond to . In fact, it is sent to the server first A Of .

[ Outside the chain picture transfer in …(img-GwtuKUJD-1638456116135)]

Features of redirection :

(1) Redirection is two requests 、 Two responses
(2) Before and after redirection , The address bar of the browser will change .( Because both requests were initiated through the browser , The browser knows the jump process , So the address bar address changes )
Borrow money from me , I don't have , I tell you, Miss Liu has , You go to Mr. Liu to borrow money , Miss Liu is lending you money .
(3) Before and after redirection request The object is not the same ( Because redirection is two requests , The server creates two different request object ,request The object is not the same , It can't be redirected through request Take the data to the destination .)
(4) The two resources before and after redirection can come from different web The application can also be the same web application , It could even be from different servers .( There is no limit between the two resources that jump )

Implementation code :

response.sendRedirect( Is redirected to the resource URL Address );

[ Outside the chain picture transfer in …(img-RXKXh5ar-1638456116135)]

Code example :

 Written in doget In the method
/* test 1: Resource jump within the same application , from /day10/Hello01 Redirect to /day10/Hello02 * http://localhost:8080/day10/Hello01 * http://localhost:8080/day10/Hello02 */
response.sendRedirect("Hello02"); // Relative paths 
//response.sendRedirect("http://localhost:8080/day10/Hello02"); // Absolute path 
/* test 2: Different Web Application internal resource jump , from day10/Hello01 Redirect to /day09/HelloServlet * http://localhost:8080/day10/Hello01 * http://localhost:8080/day09/HelloServlet */
//response.sendRedirect( "../day09/HelloServlet" ); // Relative paths 
//response.sendRedirect( "http://localhost:8080/day09/HelloServlet" ); // Absolute path 
/* test 3: Jump of internal resources of different servers , from day10/Hello01 Redirect to Baidu /tmooc home page * http://localhost:8080/day10/Hello01 * http://www.baidu.com */ Do not write relative path if the host name is different , Use absolute path , The agreement should also be written correctly , Otherwise it will be regarded as a relative path
//response.sendRedirect( "http://www.baidu.com" ); // Absolute path 
out.write( "Hello01 Response succeeded ..." ); // Because there is no time interval between redirection and jump , So you can't see this response on the browser 

summary -1: Request forwarding (forward) Redirection (redirect) The difference between ?

(1) Request forwarding is a request , One response ; Redirection is two requests, two responses
(2) The address bar address will not change before and after the request is forwarded ; The address bar address will change before and after redirection
(3) Before and after request forwarding request Object is the same , Can cooperate with request The domain object takes the data to the destination ; And before and after redirection request The object is not the same , Can't combine request Domain objects have data before and after redirection .
(4) Request forwarding requires that two resources belong to the same Web application ; The two resources for redirection can be the same Web application , Or not the same Web application , It can even come from different hosts or servers .

summary -2: When to forward by request (forward)? When to use redirection (redirect)?

(1) If you want the address bar address not to change before and after the jump , You can only use forwarding ; If you want the address bar to change before and after the jump , You can only use redirection
(2) If you want to be around the jump , Can pass request Object to bring data to the destination , You can only use forwarding
(3) If it's just a jump , There are no other requirements , Forwarding is recommended at this time ( Forwarding is a request , One response , Can reduce the number of times to visit the server , Reduce server stress )
copyright:author[Cool breeze AAA],Please bring the original link to reprint, thank you. https://en.javamana.com/2022/02/202202130736309311.html