JAVAWEB-NOTE03

Cool breeze AAA 2022-02-13 07:36:31 阅读数:631

javaweb-note03 javaweb note

1 JSP、EL、JSTL

1.1 JSP summary

1.1.1 What is? JSP

JSP and Servlet It's all by SUN Dynamic information provided by the company Web Resource development technology . ( It can be seen as being able to write java Code page )

JSP It looks like a HTML, But and HTML The difference is ,JSP You can write Java Code , Can pass Java The code shows dynamic data .

 static state Web resources : When anyone visits under any conditions , See the same effect , Such resources are called static resources Web resources .(html、css、js etc. )
dynamic Web resources : Different people , When accessing under different conditions , What you see are different effects , Such resources are called dynamic Web resources .(Servlet、jsp、php、.NET etc. )

JSP It's essentially a Servlet Program

reflection 1: Why study JSP?

  • Servlet Is a Java Program , Suitable for handling business logic , however Servlet Not suitable for outputting a to the browser html Webpage .

    Although he can also output html Webpage , But because directly in Servlet It's complicated to write in , use jsp It will generate itself, which is simpler . He finally passed servlet I'm thinking of outputting a web page from the browser , But this code is generated , And we write like a html Like writing a web page , To write a jsp. After writing, it will be translated into servlet,servlet I'll put the html Line by line output . Don't write it yourself out.write Method output . The line above is jsp Your unique content browser cannot parse .

    Business logic : For example, the next order , First, judge whether there will be goods in the warehouse . Enter a password , To determine the format .

  • html Can be returned as a page , however html It's a static Web resources , Can't show dynamic data .

  • and JSP It is also the development technology of the page , You can also return as a page , also JSP You can write Java Code , Can pass Java The code shows dynamic data .

  • therefore ,JSP The emergence of solved Servlet Not suitable for the problem of outputting pages , It also solved HTML The problem of not showing dynamic data !

  • Only jsp Do small and medium-sized projects , Will cause structural confusion , Later maintenance is troublesome . It has been abandoned

reflection 2: Why do you say JSP The essence is a Servlet? jsp In the first visit, it will be translated into servlet

The browser itself is a html Parser . 88888888888888(jsp It can be regarded as a html It can also be regarded as servlet)

The browser does not parse java Code , visit jsp He won't just put jsp Give it to the browser , because jsp You can write java Code , It can also include jsp An instruction or a specific element . therefore Browser access html Web pages and jsp The file process is different ?

html: Is sent by the server to the browser , Browser to parse .

jsp: Translation is performed on the server side , Finally, send a web page to the browser . What I visited was jsp The last thing sent to the browser is the web page .

stay JSP The first time I was interviewed , Will translate into a Servlet Program ,servlet The program will want the browser to output a web page . visit JSP What I saw later html Webpage , In fact, it is after translation Servlet Results of execution .( in other words , visit JSP After seeing the web page , yes JSP Translated Servlet Output to the browser .)

stay javaDevelop ----tomact-----work(jsp Translated catalogue )— …

1.1.2 JSP Execution process

Access... In the server JSP file , The execution process is :

 Insert picture description here

  1. When the browser requests one of the servers JSP file ( for example :localhost:8080/day11-jsp/test.jsp), The server will look for the file based on the path of the requested resource :

  2. If you find it ,JSP The translation engine will JSP Translate into a Servlet Program JSP----> Translate it into Servlet(xxx.java file )—> Translate it into servlet(xxx.class file ) , then Servlet The program is executed again , The result of the execution is to output a HTML Webpage !

    jsp The translated document is in tomact Of work Catalog

  3. If not found , The server will respond to a 404 page , The resource requested by the notification browser does not exist .

Access... In the server HTML file , The execution process is :

  1. When the browser requests one of the servers HTML When you file ( for example :localhost:8080/day11-jsp/test.html), The server will look for the file based on the path of the requested resource :
  2. If you find it , The server will html The contents of the file are sent to the browser as a response entity , The browser parses html And show it on the web .
  3. If not found , The server will respond to a 404 page , The resource requested by the notification browser does not exist .

1.1.3 modify JSP Default encoding

Eclipse Created in JSP The default is latin-1 clock , There is no Chinese data in this code table , If in JSP Write Chinese data in , There will be a garbled prompt .

establish jsp file : It can write java Code can also be written html Webpage , Under dynamic project WebCount Under the table of contents — Right click other—jsp File The suffix is .jsp

and servlet The essence is java Program , Written in src Source directory

take JSP The code used is modified to utf-8, Steps are as follows : Click on the window --> Preferences, The following window appears :

 Insert picture description here

1.2 JSP grammar

1.2.1 Template elements

Template elements are written in JSP Medium html Content

Or other than JSP Content other than unique content is called template element

Template elements in the translated Servlet in , By out.write Send it to the browser intact , The browser is responsible for parsing and displaying .

 Insert picture description here

The first line is declarative jsp Attribute information .

 Insert picture description here

1.2.2 JSP expression

Format :<%= Constant 、 Variable 、 expression %>

effect : Calculate the result of the expression , take Output the results to the browser , The browser is responsible for parsing and displaying .

<%= "Hello JSP..." %>
<% String name = " Brigitte Lin "; %> jsp Script snippet for
<%= name %>
<%= 100+123 %>
<%= Math.random() %> Pseudo random number : The random number calculated by the algorithm

Be careful :jsp Can be written in an expression that conforms to java Syntax code , But I can't write java sentence , You can't write semicolons inside ; .

1.2.3 JSP Script snippets

Format :<% A number of Java sentence %>

effect : After translation Servlet in , Put... In the script fragment Java Copy and paste the statement into Servlet Execute at the corresponding position of . for example :

stay JSP The code in is as follows :

<!-- Output on the page 5 That's ok "hello JSP"
out yes JSP Of 9 Big implicit is one of the objects ( yes JSP Built in objects , Don't declare , You don't have to accept , You can use it directly )
request/response/session/cookie/pageContext/out/page/application/exception
-->
<%
for(int i=0; i<5; i++){
out.write("Hello JSP...<br/>"); // Write data into the browser ,out
}
%> add <% The server will be treated as code , Writing on the outside will become ordinary text and output directly

stay Translated Servlet In the code, such as Next :

... Will translate <% Get rid of
for(int i=0; i<5; i++){

out.write("Hello JSP...<br/>");
}
...

in addition , In a script fragment Java Code can be incomplete , however stay JSP All the script fragments in add up , Must be complete and conform to Java grammar . for example , stay JSP The code in is as follows :

<% for(int i=0;i<5;i++){ %>
Hello JSP~~~<br/>
<% } %>

After translation Servlet in :

for(int i=0;i<5;i++){

out.write("\r\n");
out.write("\t\t\tHello JSP~~~<br/>\r\n");
out.write("\t");
}

1.2.4 JSP notes

Format :<%-- JSP The comment --%>

effect :(1) Add an explanation to the code (2) Comment out some code that doesn't need to be executed for the time being .

stay JSP When translating , Comments will not be translated , But directly discarded

Interview questions : Investigate JSP Medium JSP notes 、Java notes 、html notes

<%--
<% out.write( "aaaaa<br/>" ); %>
--%>
<% //out.write( "bbbbb<br/>" ); %> Be careful java The notes are written in the label
<!--
<% out.write( "ccccc<br/>" ); %>
-->
<%--
<% name = " Aaron Kwok "; %> This one uses html The comment will also show Guo Fucheng , use jsp notes
--%>
<%= name %>

problem :(1) Three lines of output above , During the visit , Which line will be displayed ? Not at all

First row is JSP The notes are annotated ,JSP The content of the note will not participate in the translation , And will not execute , It will not be sent to the browser , It doesn't show up in the browser .

The second line is Java The notes are annotated , The content placed in the script fragment will participate in translation , Will put one of them Java Copy the code to the translated Servlet in , But because the code is annotated , So it won't execute , It won't be sent to the browser , It doesn't show up in the browser .

The third line is html The notes are annotated ,html The note is in JSP There are template elements in , The comment itself is sent to the browser , Script fragments in comments participate in translation , Among them java Code will also execute , Will also put the content (ccccc) Send it to the browser , But because of the ccccc By html Note package , So it doesn't appear on the browser .

(2) Three lines of output above , Which line will be sent to the browser ?( Whether or not it shows )

The third line of content is sent to the browser , But it doesn't show , Because before and after html notes .

1.2.5 JSP Instructions

The format of the instruction :<%@ Instruction names Several attribute declarations ... %>

Role of instructions : Used to direct JSP How does the parsing engine put a JSP Translate into a Servlet Program .

1、page Instructions : For declaration JSP The basic attribute information of ( such as JSP Code used ,JSP The development language used )

Every jsp There must be page Instructions . Usually on the first line .page The case of writing more than one is There has to be import attribute , It's usually more than one in the guide .

No guide package page Instructions usually write only one .

<%@ page language="java"%>
-- language Property is used to specify the current JSP The development language used , At present, only java Language support
You can omit the default java.
<%@ page import="java.util.Date"%>
-- import Property is used to import packages , If you don't import the package , When using classes under other packages , You need to add a package path to the class name , for example :
java.util.Date date = new java.util.Date(); It's too much trouble to write like this
Package guide shortcut key : Immediately after the class name Such as :date after alt+/
<%@ page pageEncoding="UTF-8"%>
-- pageEncoding Property is used to specify the current JSP Code used ,Eclipse The tool will save according to this code JSP file .
Guarantee pageEncoding Property specifies the encoding and JSP The encoding used when saving the file is the same , You can avoid JSP There's a mess in the documents !

2、taglib Instructions : For introduction JSTL Tag library or other custom tag library

Explain later JSTL The label library will be explained !

1.3 JSP Labelling technology


stay JSP A large number of... Are written in the page java Code meeting Lead to JSP On the page html Code and java Code mixed up , Can cause jsp The confusion of page structure , This makes it difficult to maintain later , And the code is difficult to reuse .

So in JSP Of 2.0 In the version ,sun Put forward JSP Labelling technology , It is recommended to use labels instead of JSP On the page java Code , And recommend ,JSP2.0 Don't be in JSP Any line in the page java generation code .

1.3.1 EL expression

Be careful :jquery yes $()

Format :${ Constant / expression / Variable } ( Put it in EL Variables in must first be stored in the field , To get the value of the variable )

effect :(1) Evaluates the result of the expression placed in it , Output the result in the current position .

(2) The main role : Used to retrieve objects from a domain Get data in , Output the acquired data in the current location .

Domain object :pageContext、request、session、application

EL shortcoming : You can only get data from the domain , Can't save data . You can't traverse, you can only get data one by one

1、 Get a constant 、 expression 、 The value of the variable ( Variables have to be stored in the field first ) Can't write java sentence ( Whether there are variables in front to accept )

Note that the data stored in the field is arbitrary object Parameters of type (value)

${ "hello el" } There may be a mistake : It's true , After cutting and pasting, copy
hello el <br/>
${ 100+123 }
${ 12*12 > 143 ? "yes" : "no" } <br/>
<%
String name = " Jack ma, ";
request.setAttribute( "name123" , name );
%>
${ name123 }
<%= request.getAttribute("name123") %> attribute: Set properties
<%-- stay EL Write variables in expressions , The underlying layer looks for the property value of the name based on the variable name in four scopes
If you find the corresponding attribute value , Go straight back , Output to current position ; If you can't find it, look for it
Until we find four scopes , In the end, nothing will be output if it can not be found !
The order of searching for four scopes is : pageContext->request->session->application
--%>

2、 Gets elements in an array or collection in the scope

Servlet The code in :

// Declare an array , Add elements to the array , And put the array into the field 
String[] names = {
" Lau Andy ", " Aaron Kwok ", " Jacky Cheung ", " The dawn " };
request.setAttribute( "names", names );
// Forward the request to jsp, stay JSP Gets the elements in the array in the domain 
request.getRequestDispatcher( "/02-el.jsp" ).forward(request, response);

JSP The code in :

<%-- Get from Servlet Forward elements in the array in the brought domain --%>
${ names[0] } <%-- Lau Andy --%>
${ names[1] } <%-- Aaron Kwok --%>
${ names[2] } <%-- Jacky Cheung --%>
${ names[3] } <%-- The dawn --%>

3、 Get in scope map The elements in the collection

Servlet The code in :

// Make a statement map aggregate , Add an element to the collection , And will map Put... Into the collection 
Map map = new HashMap();
map.put( "name" , " Nicholas Zhao si " );
map.put( "age" , 28 );
map.put( "addr", " China " );
request.setAttribute( "map1", map );
// Forward the request to jsp, stay JSP Gets the elements in the array in the domain 
request.getRequestDispatcher( "/02-el.jsp" ).forward(request, response);

JSP The code in :

${ map1.name } <%-- Nicholas Zhao si --%>
${ map1.age } <%-- 28 --%>
${ map1.addr } <%-- China --%>

4、 Get in scope JavaBean Property value of object

Bean: Refers to reusable components
JavaBean: finger Java Reusable components in
Business Bean: Dedicated to processing business logic ( for example : When processing a registration request , Before saving the user's registration information to the database , The registered salary needs to be verified )
Entity Bean: Is designed to encapsulate data ( for example :User user = new User() ...)

Servlet The code in :

// Make a statement User object , Assign values to the properties of the object , And will User Objects are stored in the domain 
User u1 = new User();
u1.setName( " Lau Andy " );
u1.setAge( 18 );
u1.setAddr( " Hong Kong, China, " );
request.setAttribute( "user" , u1 );
// Forward the request to jsp, stay JSP Gets the elements in the array in the domain 
request.getRequestDispatcher( "/02-el.jsp" ).forward(request, response);

JSP The code in :

<%--
${ user.getName() }
${ user.getAge() }
${ user.getAddr() } --%>
<hr/>
<%-- user.name The underlying call is still getName() Method --%>
${ user.name }
<%-- user.age The underlying call is still getAge() Method --%>
${ user.age }
<%-- user.addr The underlying call is still getAddr() Method --%>
${ user.addr }
 Total test :
<%@page import="com.tedu.pojo.User"%>
<%@page import="java.util.HashMap"%>
<%@page import="java.util.Map"%>
<%@page import="java.util.ArrayList"%>
<%@page import="java.util.List"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>EL expression </title>
</head>
<body> // Be careful : This is just for testing purposes , Save the data first ( It's usually written in Servlet Inside or controller Inside ), Take it out again .( Send express to yourself )
<h3>(1) Get a constant 、 expression 、 The value of the variable ( Variables have to be stored in the field first )</h3>
<%
String name=" Jacky Cheung ";
// take name The value of the variable is stored in request domain
request.setAttribute("name123", name);
%>
${ "Hello EL" }
${ 100+123 }
${ Math.random() }
${ name123 } // Get data from the front data
${ 30*45>1300 ? "yes" : "No" }
<%-- If you go EL Write constants or expressions in ,EL You can output the value of a constant , Or calculate the result of the expression and then output
If you go EL Write variables in ,EL The bottom layer will be based on the name of this variable ( such as :name) As property name ,
Find the attribute value corresponding to the attribute name in the four scopes . When searching , According to the size of the domain , From childhood to
Look for... In large order , If found, it will return directly and output in the current position ( In time, there is , No longer looking for ),
If you can't find it, you don't output anything !
Domain range size : pageContext < request < session < application --%>
<h3>(2) Gets elements in an array or collection in the scope </h3>
<%
// Declare an array , Store the array in request domain
String[] names = {" Liu peixia "," Zhang Shenzheng "," Qi Lei "," Liu Yujiang "," Wang Haitao "," Dong Changchun "};
request.setAttribute( "namesArr", names );
// Make a statement List aggregate , Save the collection in request domain Guide pack : After the class name alt+/
List list = new ArrayList();
list.add( " Han Shaoyun " );
list.add( " Chen Zishu " );
request.setAttribute( "nameList", list );
%>
${ namesArr[0] }
${ namesArr[1] }
${ namesArr[2] }
${ namesArr[3] }
${ namesArr[4] }
${ namesArr[5] }
<hr/>
${ nameList[0] } aggregate
${ nameList[1] }
<h3>(3) Get in scope map The elements in the collection </h3>
<%
// Make a statement map aggregate , And will map Into the collection of fields
Map map = new HashMap();
map.put( "name" , " Avanti " );
map.put( "age" , 28 );
map.put( "addr", " tianjin " );
request.setAttribute( "map1" , map );
%>
${ map1.name }
${ map1.age }
${ map1.addr }
<hr/> perhaps use EL It's written inside ,key Can't write numbers , Ordinary can write . Such as map.put( 1, " tianjin " );
${ map1.1 } Obviously not .
${ map1["name"] }
${ map1["age"] }
${ map1["addr"] }
<h3>(4) Get in scope JavaBean Property value of object </h3>
<%
// Make a statement User example , take User Instance storage request domain
User u1 = new User();
u1.setName(" Jack ma, ");
u1.setAge(30);
u1.setAddr(" Hangzhou ");
request.setAttribute( "user", u1 );
%>
${ user.getName() }
${ user.getAge() }
${ user.getAddr() }
<hr/> Abbreviation form
${ user.name } <!-- The underlying call is still getName() Method -->
${ user.age } <!-- The underlying call is still getAge() Method -->
${ user.addr } <!-- The underlying call is still getAddr() Method -->
</body>
</html>
package com.tedu.pojo;
/** (4 Corresponding code )
* POJO: Simple Java object , For example, in order to encapsulate user information , Provided by the User class , It's just one. POJO class
* adopt POJO The object created by class is a POJO object ( User u = new User() )
* JavaBean:
* bean: Reusable components , JavaBean: Refers to using java Reusable components written in language (serice/dao)
* JavaBean It's also divided into : Business bean And entities bean
* Business bean: Designed to handle business logic
* Entity bean: Designed to encapsulate data (pojo) */
public class User {
private String name;
private int age;
private String addr;
public String getName() {
System.out.println("getName Method executed ......");
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getAddr() {
return addr;
}
public void setAddr(String addr) {
this.addr = addr;
}
}

1.3.2 JSTL Tag library

JSTL The tag library is for JavaWeb A set of standard and general label libraries provided by developers ;

JSTL Tag library and EL It can replace JSP Most of them Java Code ;

In the use of JSTL The tag library needs to be completed before :

Be careful :java Basic projects , There is no special deposit jar The package directory , We need to create . Right click yourself Build path----add path quote .

Dynamic Web Project WEB-INF Medium lib Catalog , It's for storing jar The package directory , You don't have to right-click to reference ( He will be introduced automatically ).

stay JSTL The label of the library JSP Introduction in JSTL(taglib Instructions ). Because it will follow webcont Publish to server . You can't create yourself like before lib Right click the directory … Because it will not be published on the server .

  • Import JSTL Development package for stay lib Under the table of contents ctrl+v copied appear Web App Libraries

 Insert picture description here

  • In the use of JSTL The label of the library JSP Introduction in JSTL(taglib Instructions ) ( stay day11jsp There are )
  • c Just a prefix , Not necessarily c . It's just that in the future c, The label below should also write c.
  • Only after importing and warehousing can , Using shortcut keys alt+/ Such as :<C: alt+/

 Insert picture description here


The commonly used labels are as follows :

1、<c:set></c:set> – Used to add attributes to a domain , Or modify the existing property value in the field

c:set Tag attribute summary :

(1)var -- Specifies the name of the property stored in the scope
(2)value -- Specifies the value of the property stored in the scope
(3)scope -- Specifies which scope to store the attribute in , The default value is page, Express pageContext Domain
Value for : a)page Express pageContext Domain b)request Express request Domain
c)session Express session Domain d)application Express ServletContext Domain

Code example :

Be careful : If the domain name is the same var The value of is the same , hinder value It's going to cover the front value value .

because The structure in the domain is key—value structure .

and EL The expression takes data from the field according to 4 The range of fields is from small to large .

<%-- request.setAttribute("name", " Zhang San "); --%>
<c:set var="name" value=" Zhang San "/>
${ name }
<c:set scope="request" var="name" value=" Zhang Sanfeng "/>
${ requestScope.name }
<%--${ name } No default is specified. Search from the smallest domain with the name name The attribute value , Go straight back when you find it ( Even if there is one in the back, I won't look for it anymore )
${ requestScope.name } Means to specify from request Search for a field with the name name The attribute value --%>

2、<c:if></c:if> – Simple in construction if…else… Structural statements

c:if Tag attribute summary :

test attribute -- Specify a Boolean expression , When the result of the expression is true when , Will execute ( Output )c:if Content in Tags , If the expression results in false, Will not output c:if Content in Tags There's nothing in it else sentence

Code example : Put a score into the field , Judge the grade according to the grade

<c:set scope="request" var="score" value="-44"/>
<c:if test="${ score>=80 && score<=100 }">
Your grades belong to : good !
</c:if>
<c:if test="${ score>=60 && score<80 }">
Your grades belong to : secondary !
</c:if>
<c:if test="${ score>=0 && score<60 }">
Your grades belong to : fail, !
</c:if>
<c:if test="${ score<0 || score>100 }">
Your score is illegal , Please re-enter !
</c:if>

3、<c:forEach></c:forEach> – Loop through elements in a collection or array, or perform a specified number of cycles .

(1) Traverse the domain Array or collection The elements in

<%
String[] name = {" Wang Haitao "," Liu peixia "," Chen Zishu "," Qi Lei "};
request.setAttribute( "names", name );
%>
<c:forEach items="${ names }" var="name" varStatus="vs">
${ vs.count }, ${ vs.first }, ${ vs.last }, ${ name } <br/>
perhaps : ${name} Double quotes and ${} There should be no spaces between them , Because space plus array will become a string
<!-- This place uses ${name} Because of receiving name I'll put name Save in scope -->
</c:forEach>

(2) Traverse the domain map The elements in the collection

<%
// Make a statement map Assemble and map Into the collection of fields
Map<Object,Object> map = new HashMap<Object,Object>();
map.put( "name" , " Nicholas . Zhao si " );
map.put( "age" , 35 );
map.put( "addr" , " China " );
request.setAttribute( "map1", map );
%>
<c:forEach items="${ map1 }" var="entry">
${ entry } <br/> perhaps Get... Alone
${ entry.key } : ${ entry.getValue() } It can be abbreviated :get Get rid of ,() Get rid of , The initial letter is lowercase, but the bottom tone is still getValue()
</c:forEach>

(3) Traverse 0~100 Integer between , It will be 3 The value of the multiple of is output to the browser

 <%-- for(int i=1; i<100; i++){} --%>
<!-- take 1~100 Between 3 Numerical output of multiples of -->
<c:forEach begin="1" end="100" var="i" step="1">
${ i%3==0 ? i : "" }
</c:forEach>
<hr/> perhaps
<c:forEach begin="1" end="100" var="i" step="1">
<c:if test="${ i%3==0 }"> ${ i } </c:if>
</c:forEach>

c:forEach Tag attribute summary :

(1)items: Specify the collection or array to traverse , If it is to get the array or collection to be traversed from the field , You can configure the EL To get
(2)var: Specifies each element used to receive traversal , At the same time, the received elements will be stored in pageContext Therefore, in the field, the circular label Sign internal , Can pass el Get the element currently being traversed
(3)begin: Specifies where the loop starts
(4)end: Specify where the loop ends
(5)step: Specifies the step size of the loop , The default value is 1
(6)varStatus: Object used to represent state information of loop traversal , This object has the following properties :
first attribute : Indicates whether the current traversal is the first time , if , Then return to true, Otherwise return to false;
last attribute : Indicates whether the current traversal is the last time , if , Then return to true;
count attribute : Record the current traversal is the number of times

Code example :

...

1.4 How to hide temporarily unused items

Hide items : Right click —close projects— stay package Under View , Upper right corner Filters----Closed projects–ok

And on again — Upper right corner ---- Cancel it Closed projects— Double click on the item

2 Maven

Today's learning goal :

  1. Understand what is Maven And Maven The role of
  2. master Maven Install and integrate into Eclipse in
  3. Master how to use Maven structure Java The project and Web project
  4. Master the use of Eclipse Import existing Maven project
  5. understand Maven Three types of warehouses ( Local repository 、 Remote warehouse ( Private clothes )、 The central warehouse ( ceremonial dress worn by post-Song government officials ))
  6. understand Maven How to manage dependencies ( Management jar package )

2.1 Maven Introduce


2.1.1 Maven What is it? ?

 Insert picture description here

Maven: Translated into " Experts "、“ adept ”, yes Apache Under a pure Java An open source project developed by .

Maven It's an item Project management tools , Use Maven Can manage enterprise level Java Project development and dependency management .

jar Packages can be called dependencies , Why? ?

because , For example, a project needs to rely on jar Package to execute , So the jar Packages are called dependencies .

Yes 2 Method of use :

1. Don't eclipse Integrate , By command , Need configuration Maven-Home environment variable , This method requires a lot of commands .( Not recommended )

  1. hold Maven and eclipse Make an integration , After integration, you can use eclipse Create a Maven project , adopt Maven Compile the project , Run pack , Testing, etc. .

Use Maven Development , It can simplify project configuration , Unified project structure . All in all ,Maven It can make the work of developers easier .


What is dependency management ? Understand dependency management , First of all, we should know what dependency is ?

One Java Projects often rely on some third-party jar package . such as JDBC The program depends on the database driver package , Or in use c3p0 When connecting to the pool , To rely on c3p0 Of jar Bag, etc . Then we call these Java The project relies on third parties jar package .

And the so-called dependency management , In fact, it is all the dependencies in the project jar Standardized management of packages .

2.1.2 Why use Maven?

Traditional projects ( engineering ) The management of the project on which jar The package is completely managed manually , And manual management jar Packages can cause many problems .

1、 Don't use Maven, Manage... In a traditional way jar The disadvantages of the package :

(1) Some frameworks will be used in some large projects , such as SSM perhaps SSH frame , And the framework contains jar There are so many bags ( Even rely on other third parties jar package ), If these jar We manually go online to find , There are some jar The bag is not easy to find , More trouble .

(2) The traditional way will jar Package added to project , such as Java In the project jar The package is placed in the project root directory or in the self built lib Under the table of contents ;JavaWeb The project will jar bag :/WEB-INF/lib Under the table of contents , This will cause the volume of the project file to soar ( for example , Some project code itself may be only a few megabytes , To join jar After package , The volume of the project may reach tens or even hundreds of megabytes ).

(3) In traditional Java In the project, all jar The package is uniformly copied in the same directory , May exist jar Package file name conflict !

(4) During project integration , There may be jar The problem of package version conflict .

(5) In tradition java Through compilation in the project ( Compile manually or in eclipse Save auto compile )、 test ( The manual in main Function test 、junit unit testing )、 Packaged deployment ( Manual play war package / Manual release )、 function ( Manual start tomcat function ), Final access program .

2、 Use Maven To manage jar Package advantages :

(1)Maven The team maintained a very comprehensive Maven Warehouse ( The central warehouse ), It contains almost all jar package , Use Maven The created project can be automatically to Maven Download... In the warehouse jar package , Convenient and error free .

in addition , stay Maven In the built project , If you want to use some frameworks , We just need to introduce the core of the framework jar package , Other third parties on which the framework depends jar package ,Maven Will also download .

(2) stay Maven In the built project , The project will not depend on jar Copy the package to each project , It's going to be jar The package is uniformly placed in the warehouse for management , In the project, you only need to introduce jar The location of the package ( coordinate ) that will do . This achieved jar Packet reuse .

(3)Maven Use coordinates to manage... In the warehouse jar package , The directory structure is 【 Corporate name + project / The product name + Version number 】, It can be located to a specific... According to the coordinates jar package . Even if you use the same name in different companies jar package , The coordinates are different ( The directory structure is different ), File names will not conflict .

(4)Maven In the built project , adopt pom The file is dependent on in the project jar Package and version shall be managed uniformly , Avoid version conflicts .

(5) stay Maven In the project , You can compile the project with one command or one click (mvn complie)、 test (mvn test)、 Packaged deployment (mvn deploy)、 function (mvn install) etc. .

And publish to tomcat Running on the server : mvn tomcat7:run. If you want to implement all the above processes , Just remember one command :mvn install

All in all , Use Maven Following the standard development is conducive to improving the development efficiency of large teams , Reduce the maintenance cost of the project , Big companies give priority to Maven To build the project .

2.2 Maven install


2.2.1 download 、 install Maven

-bin .tar.gz: Apple Linux -bin .zip: window

src.tar.gz src.zip Is its source file

 Insert picture description here

1、 Official download address :http://maven.apache.org/download.cgi

 Insert picture description here

2、 Download the green version , After decompressing, you can use .

 Insert picture description here

principle : There should be no Chinese and spaces in the installation path !!

3、 To download an older version Maven, You can visit :

https://archive.apache.org/dist/maven/maven-3/

 Insert picture description here

 Insert picture description here

2.3 Maven Related configuration of


In development, it is more through Eclipse+Maven To build Maven project , So here we need to put Maven Configuration to Eclipse Development tools .

After the will be installed Maven Tool configuration Eclipse Before... In development tools , You need to do some related configuration .

2.3.1 Configure local warehouse location

Local repository : In fact, it is a directory on the local hard disk , In this directory ** contain maven All required in the project jar Packages and plug-ins .** When needed jar When the package is not in the local warehouse , Downloaded from the Internet jar The package will also be stored in the local warehouse .

therefore ** The local warehouse is actually a place to store jar The package directory ,** We can specify Maven The location of the warehouse .

This directory does not need to be created , Only the directory you specify will be automatically created when configuring .

If you don't specify ,maven The default location of the local warehouse is c disc , stay :

​ Administrator

C:/Users/{ The current user }/.m2/repository, for example : This file is hidden deeply, so we can change its directory path , It's easier to find .

 Insert picture description here

You can keep the default , Of course, you can also change the location of the local warehouse to another drive letter path .

Modification method : find [MAVEN_HOME]/conf/ The configuration file in the directory settings.xml, modify maven The path to the warehouse . (Maven The core configuration file of the software , For example, configure local warehouse , Remote warehouse ,jdk edition

Editor open , The browser is open and cannot be edited . As long as there is d Disk, it will automatically help you create these two directories , We don't need to create it manually .

 Insert picture description here

After configuring the directory , Later through maven Download the jar The package will be saved in the configuration directory .

The above contents can be summarized as :

  1. What is a local warehouse ?
  2. Where is the default location of the local warehouse ?
  3. What is the difference between configuring and not configuring a local warehouse ?

2.3.2 Configure remote ( Mirror image ) Warehouse ( Private clothes )

When maven The project needs to rely on jar Packet time , If not in the local warehouse , Will go to the remote warehouse to download jar package .

If the remote warehouse is not configured , The central warehouse is connected by default , Because the central warehouse is for global users , So I'm downloading jar Packet time , It may be slow , It will be less efficient .

Can be in settings.xml Configure the connection to the remote warehouse in the file ( If it's in Dane's classroom , It's connected to the intranet ) Or connect to Alibaba cloud remote warehouse ( Need to have an Internet ).

1、 If you are connected to the intranet , You can connect to the remote warehouse in Dane ( If you don't configure , Default connection to central warehouse , No extranet , Can't connect to the central warehouse , It can lead to jar The package could not be downloaded ).

What needs to be done is , stay settings.xml In the document <settings> Label under <mirrors> Add the following configuration inside the tag , Configure Dane remote warehouse :

<mirror> 147 That's ok
<id>nexus-tedu</id>
<name>Nexus tedu</name>
<mirrorOf>central</mirrorOf>
<url>http://maven.tedu.cn/nexus/content/groups/public/</url>
</mirror>

2、 If at home 、 The company is connected to the Internet , Is unable to connect to the remote warehouse in Darnay , You can choose not to configure anything , Default connection to central warehouse , Or you can configure the connection to Alibaba cloud remote warehouse ( Do not use mobile hotspot network connection ,jar The bag is incomplete ), The configuration is as follows :

Configure Alibaba cloud remote warehouse :

<mirror>
<id>nexus-aliyun</id>
<name>Nexus aliyun</name>
<mirrorOf>central</mirrorOf>
<url>http://maven.aliyun.com/nexus/content/groups/public/</url>
</mirror>

Be careful : xml The document has strict requirements for Syntax , Release the configured comment label before and after .

After the configuration is completed, save .

Remote warehouse configuration summary :

  1. When needed jar When the package is not in the local warehouse , Will download... From the Internet . Configuring a remote warehouse is actually configuring , Go to which location on the network to download jar Package to local .

  2. If in the company , And the company has set up a mirror server , It is recommended to use the company's image server to download jar package , It will be faster .( If in Dane , Using the intranet , You can only configure the remote warehouse in Darnay . otherwise , You can't connect to the central warehouse without an external network , download jar The package will fail !)

  3. If at home , Using the Internet , The remote warehouse can not be configured , The default connection is central warehouse download jar package , Or configure Alibaba cloud's remote warehouse . Connect to alicloud server to download jar package .( Be careful , If alicloud image server is configured , Do not use mobile hotspot networks !

2.3.3 To configure JDK edition

adopt Maven Project created ,JDK The default version is JDK1.5, You need to manually change to a higher version every time .

Be careful : This jdk The version is the same as yours eclipse Of jdk The version doesn't matter .

This can be modified maven Of settings.xml file , Achieve the effect of once and for all .

The configuration mode is : open {maven root directory }/conf/settings.xml File and edit , stay settings.xml Inside the document <profiles> Add the following configuration inside the tag :

<profile> 220 That's ok
<id>development</id>
<activation>
<jdk>1.8</jdk>
<activeByDefault>true</activeByDefault>
</activation>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<maven.compiler.compilerVersion>1.8</maven.compiler.compilerVersion>
</properties>
</profile>

2.3.4 take Maven Configuration to Eclipse in

take Maven Tool configuration to Eclipse in , You can go through Eclipse And self installed Maven establish Maven Project .

1、window Right click –> Preferences:

 Insert picture description here

**2、 Click on Maven Options , Check... In the options on the right “Download Artifact Sources”:** Because sometimes it may depend on the source code .

 Insert picture description here

3、 Click on add Install your own Maven added : eclipse Built in Mavan Not all functions , no need !

 Insert picture description here

4、 Add your own installed Maven:

The root directory of the installation route If you are wrong, you will automatically prompt directory: Catalog

The name of the installation , You can just use this directory name

 Insert picture description here

 Insert picture description here

Be sure to pay attention to : Self installed Maven Don't put it on the table ( Easy to lose , And there are often spaces in the path ),maven Do not include Chinese and spaces in the installation path !!

 Insert picture description here

5、 Default maven Switch to your own configuration maven: It's just installation

 Insert picture description here

6、 Set up maven Of settings The location of the file :

The recommended use points to setting Installation root of , No matter what you use in the future, there will be no problem .

this 2 Configuration is good , The local warehouse location will be automatically displayed .

 Insert picture description here

**7、 Test whether the configuration is successful :**window—> show view —> other Mid search "maven", Click the option in the box below

 Insert picture description here

In the pop-up window , View your configured local warehouse and remote warehouse images :

Below is the central warehouse , After configuring the remote warehouse, the priority is higher than the central warehouse .

 Insert picture description here

2.4 Maven Project construction


adopt Maven structure Java The project is divided into two ways :

(1) Create... In a simple way : establish Maven Simple Java Project and create Maven Simple Web engineering

(2) Use template to create : Create a template to use Java Project and create projects using templates Web engineering ( 2 The results are the same , The final project is the same

Using Maven There are two ways to build a project , The first is : Create a simple project **(Create a simple
project)**, That is, check the front box when creating .

 Insert picture description here

( Uncheck the front box , That is, create a skeleton ( It's actually a template ) establish Maven engineering )

another , When creating a simple project , It is also divided into creating Java engineering and JavaWeb engineering . The following are demonstrations .

2.4.1 Create a simple project —Java engineering

1、 Right click in the blank space New —> Maven Project:

 Insert picture description here

2、 In the pop-up window , Check the front box , Create a simple project ( That is, do not use the skeleton ), Go to the next step .

 Insert picture description here

3、 In the pop-up window , Fill in the content (Package choice jar, creating java engineering ), Click Finish .

 Insert picture description here

In the above contents , There are four required items :

(1)Group Id – The name of the group , Usually fill in Corporate name ( such as com.tedu) Or organization name (org.apache…)

(2)Artifact Id – Project name or module name

(3)Version – Version of the project , The default created project is 0.0.1-SNAPSHOT snapshot , It's also called the informal version , The official version is RELEASE)

(4)Package – Type of project :jar It means to create Java engineering ,war It means to create web engineering ,pom Indicates that the parent project is created ( Of course, there are sub projects ) Or polymerization Engineering ,pom At present, we will not discuss .

The parent project can be configured , It's easier for subprojects to inherit these configurations . There is no need to separate the configurations .

After filling in , Click Finish to complete the creation of a simple Java engineering

Progress( Progress ) : Click the green progress bar in the lower right corner of the lower right corner to show The green progress bar under this window indicates that you are downloading jar What is a bag .

4、 Switch drawing view to package view :window --> show view, Search in the pop-up window for :

 Insert picture description here

2.4.2 Create a simple project —Web engineering

1、 Right click in the blank space New —> Maven Project:

 Insert picture description here

2、 In the pop-up window , Check the front box , Create a simple project ( That is, do not use the skeleton ), Go to the next step .

 Insert picture description here

3、 In the pop-up window , Fill in the content (Package choice war, creating web engineering ), Click Finish .

 Insert picture description here

4、 After creation pom.xml The document will report an error , Say we can't find it web.xml file , for example :

establish Web Errors will be reported under the project . Note that in the package view

 Insert picture description here

Manually add ( Copy ) that will do , for example :

Because of the lack of web.xml file , It's in webcount In the catalog web-INF Under the table of contents , This is a previously created web The directory where the file needs to be published ,Maven Medium webapp amount to Former webcontent Catalog : Right click on the project java EE Tools ---- Generate Deployment Descriptor Stub Automatic generation .( In the package view )

use maven establish java The project and web Project distinction ?

1. use Maven Created web The project is better than the one created java There are more project structures main Below webapp Catalog , Including the contents .

2.pom How files are packaged , If you don't write the packing method ( The default is jar package ) Or write is jar The package is java Project .

If the packaging method is war The package is web project .

 Insert picture description here

5、 establish Servlet Program , Test run environment . It's in src/main/java Create under directory java file (servlet The essence is java file ) At the same time web.xml Generate the least in the file 8 Line configuration .

 Insert picture description here
 Insert picture description here
 Insert picture description here

The above error is due to the lack of Servlet Of jar The bag may not be finished , take tomcat Add the running environment !

!! The lack of Servlet Running environment solutions :

In the package view ---- Right click —build path—add libraries----server runtime ( Server running environment ) perhaps jre system library(jre System class library )

Right click on the project , choice “Properties” —> “Targeted Runtimes”:

 Insert picture description here

perhaps , In the project pom.xml Add... Under the root tab in the file Servlet Of jar Coordinates of the package , introduce Servlet Of jar package , as follows :

<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jsp-api</artifactId>
<version>2.0</version>
<scope>provided</scope>
</dependency>
</dependencies>

Add and save pom file . If the report is wrong , Right click on the project and select “Maven” —> “UpdateProject…” Just update the project !

( If there is no other jar package :“Maven” —> UpdateProject It will be downloaded jar package , But it may not take effect .

Replace your local warehouse with the local warehouse distributed locally , Need to close first ecliose, Because no matter what may be taking up the file, it can't be deleted . And then in pom.xml File wrap ctrl+s stay **“Maven”** —> UpdateProject)

6、 Realization Servlet Program day13 156

 Insert picture description here

**7、 Test access :** Open the browser to access the address :http://localhost/MavenSimpleProJavaweb/HelloServlet

 Insert picture description here

The correct display indicates that there is no problem with the operating environment ,

2.4.3 Maven Directory structure of

Use Maven The project we created is called Maven engineering ,Maven The project has a certain directory specification , There are strict requirements for directory structure , One Maven The project shall have the following directory structure :

View the location of the workspace of the directory : Right click the selected item —show in—System Explorer

java The project and web The project structure is almost the same , difference Different names , stay web Project src There's more webapp The directory is equivalent to the previous ordinary creation webcontent Directory to store web Type of resource .

 Insert picture description here

Below src The catalogue follows the above src It's the same directory , But the content displayed is different ( like , The effect of looking at a person from the front is different from that of looking at a person from the side )

maven Project does not lib Catalog , It's through pom The file introduced .

Let's say Maven Of Web Project as an example , Introduce Maven The directory structure in the project :

Maven Project name (Web project )
|-- src/main/java( Source directory ): For storing programs / What the project needs java The source code file
|-- src/main/resources( Source directory ): For storing programs / Configuration files required for the project
|-- src/test/java( Source directory ): For storing test programs java Source file
|-- src/test/resources( Source directory ): It is used to store the configuration files required by the test program
|-- src/main/webapp:(Web Root of application , Function like WebContent)
|-- WEB-INF:( Protected Directory )
|-- web.xml:(Web The core configuration file of the application )
|-- target/classes( Class directory ): The resources in the source directory are compiled , Will be output to the class directory .
|-- pom.xml:Maven Very important documents in the project , Future projects require any jar Package or plug-in , Both can pass pom File to import these jar Package or plug-in .

Note that the compiled output file locations of different projects are different .

java Basic engineering : The compiled class File output to bin Under the table of contents .

web project : Inside java File output to builid Inside classes Catalog , After the release of web-inf Under the table of contents .

Maven Project java The source file will be output to target Inside classes Catalog . Put it on the server after publishing web-inf Catalog .

2.5 Import existing Maven project


Now pass the following through SSM Framework implementation << Yonghe King store management system >>(Maven) Import the project into our Eclipse In the development environment .

The first sql Statement is written to the database . Here is to use import, You can choose Copy projects into workspase Will be copied into the workspace , Even if it is deleted in the future, there is still one in the workspace .

Change the code of the current project — Selected items – Right click —Properties—resource—other

When importing a project, we usually use “File” --> “Import…” To import the project , But this can cause environmental problems and so on , for example : If the environment of the project itself is inconsistent with the development environment we currently use , There will be problems . You can import in the following way . ( If you don't make a mistake, you can also use this way , Forget Baidu )

Here are the steps to import : This import is under construction Maven project , Then copy the file in .

1、 Create a new Maven engineering (JavaWeb engineering )

Make sure it's configured Maven After the environment , stay Eclipse Create a new Maven engineering (Javaweb engineering ), The name of the new project and the imported project can be the same or different , for example :

 Insert picture description here

2、 decompression yonghe-ssm.zip Compressed package

To be issued yonghe-ssm Unzip the project , The structure after decompression is as follows :

 Insert picture description here

open yonghe-ssm Catalog :

 Insert picture description here

3、 The... In the unzipped directory src Directory select and copy .

 Insert picture description here

4、 Click on the newly created Maven Right click the project to paste , Will duplicate src Paste the directory into the new project

 Insert picture description here

5、 Open... In the extracted directory pom.xml file , Copy the content :

 Insert picture description here

If the copied item or pom The file still reports an error , Can be updated Maven engineering

** to update Maven engineering :** Right click on the project and select “Maven” —> “Update
Project…”
, Click... Directly in the pop-up window OK that will do !

6、 perform SQL Script files , Import data

open cmd, Connect mysql database , perform yonghedb.sql Medium SQL sentence , Create database 、 Table and insert record .

7、 Deploy the project to the server and start the server , Access test

After completing the above operation correctly , Open your browser and visit the following address :http://localhost/yonghe-ssm/index
, You can see the following interface :

stay src/main/resources----jdbc.properties You can change the password , user name

web-INF The files in the directory cannot be accessed directly , We can use the right button to run on the project run —as— But this path is incomplete , appear 404, Add one index

 Insert picture description here

You can also change the code of the current project .

On the project — Right click —properties— The following pop-up window appears –other–utf-8—apply and close

 Insert picture description here

2.6 Maven Dependency management for


2.6.1 rely on (jar package ) management

Dependency management is jar Package management , Then through the Maven How the created project is managed jar Bag ?

1、 stay Maven How to introduce jar package ?

stay Maven In the project created , If you need to quote jar package , Only need in the project pom.xml Add... To the file jar Coordinates of the package (GroupID + ArtifactID + Version) Can be jar The package is introduced into the project , You can then use the introduced... In your project jar It's packed .

for example , Now we are pom.xml In file , add to servlet Of jar The coordinates of the package are as follows :

It can be found in the local warehouse according to the location of the coordinates jar package .

<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope> provided Express jar The scope of the package : The compiler needs , It will not be published to the server at run time , Because the server has this jar package , Publishing may conflict in the past .
</dependency>
</dependencies>

stay pom.xml In file , add to mysql The coordinates of the drive package are as follows :

 <dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.32</version>
</dependency>
</dependencies>

After importing, there are several directories on the left :

 Insert picture description here

2、 Introduced in the project jar Where are the bags stored ?

So here comes the question , stay pom Added to the file servlet Of jar Package coordinates , What's added is just a jar The coordinates of the package , And this jar Where is the bag stored ?

understand Maven management jar Rules after package , We can find jar The storage location of the bag is Local repository ( The warehouse defaults to :C:\Users\{ The current user }\.m2\repository) Of /javax/servlet/servlet-api/2.5/ Under the table of contents , for example :

 Insert picture description here

summary :

  • stay Maven in , be-all jar All packages are stored in the directory of the local warehouse , If needed in a project jar package , Directly in the project pom.xml In the file through coordinates (GroupID + ArtifactID + Version) Bring in... At the specified location jar Bag can .
  • In this way, all used in the project jar Packages are grouped in one directory ( Local repository ) Unified management in , If necessary, it can be directly introduced through coordinates , Instead of making a copy of every project , Reduced project volume , It also saves disk space .
  • In the future, if others need to import your project , Just put the project ( Including, of course pom.xml file ) Pass the whole code to the other party , There is no need to jar Send the package to the other party , The other party is configuring Maven After the environment ,Maven Will be automatically based on pom.xml The coordinates configured in the file , introduce ( Or download and then import ) Corresponding jar package .

3、 If you introduce jar The package is not in the local warehouse ?

  • If it is just configured Maven Environmental Science , Not much in the local warehouse jar package , At this time in pom The file is imported by coordinates jar package , This is not available in the local warehouse jar package , What will happen at this time ?

  • If the local warehouse does not have the required jar package , Then it will go to the remote warehouse ( Also called private server ) Or go to the central warehouse ( Also called public service ) Download . Let's introduce Maven These three warehouses .

2.6.2 Maven Three warehouses

In the local warehouse mentioned above 、 Remote warehouse 、 The central warehouse is used to Maven To better manage jar One way to package . Let's learn about Maven Of Three warehouses , And the potential connection between the three warehouses .

adopt maven Projects built , Will pass the... In the project pom.xml File download from remote warehouse , And save it to the local warehouse

 Insert picture description here

Local repository : The default local warehouse location is :c:/${user.dir}/.m2/repository, among ${user.dir} Express windows Under the user directory . The role of the local warehouse is , Used to hold ( Storage ) Downloaded from a private server or from a central warehouse jar package ( Or plug-in ). When needed in the project jar Packages and plug-ins , Priority is given to searching from local warehouse .

If the required... Is not available in the local warehouse jar package , You can download it from the private server or the central warehouse and then save it to the local warehouse .

Remote warehouse : Remote warehouse is also called private server (Nexus), Private servers are generally built and maintained by the company ( You can build it yourself ). For example, Dane has set up its own private server (http://maven.tedu.cn/nexus/content/groups/public/), And alicloud private server (http://maven.aliyun.com/nexus/content/groups/public/).

If used in the project jar There are no packages or plug-ins in the local repository , You can download from the private server , If there is in the private server, it will directly jar Save the package to the local warehouse ; And if you don't have what you need jar package , Just go to the central warehouse ( ceremonial dress worn by post-Song government officials ) Download what you need jar package , After downloading, first save a copy on the private server , Finally, save it to the local warehouse .

The central warehouse : The central warehouse is also called public service , stay maven A warehouse address is built into the software (http://repo1.maven.org/maven2) It's the central warehouse , It serves the entire Internet , from Maven The team builds and maintains , It stores a very complete jar package , It contains the of most popular open source projects in the world jar package .

So we are using Maven Built Java project , Used in the project jar Where will the bag come from ? for example , adopt Maven Build projects successively A And projects B, All projects need to rely on third parties jar package :

  • If the project A You need to rely on a third party jar package , Only need to be under the project pom Introduce in the file jar Wrapped in Local repository The coordinates in... Can be used . If the local warehouse does not have what is needed jar package , Will connect to the private server ( It needs to be configured in advance ) Download required jar Package to local warehouse for project use .

  • If you don't have what you need on your private server jar package , Then it will connect to the central warehouse to download the required jar Save package to private server , then jar Download the package from the private server to the local warehouse , For project use .

  • If no private server is configured , Connect to the central warehouse by default to download the required jar Package to local warehouse for project use

  • When the project B You also need to rely on third parties jar Packet time , First go to the local warehouse to find the required jar package , If so, reference it directly without downloading it again , If there are still some jar The package does not exist in the local warehouse , Same as above , That is, connect to the private server to download jar Package to local warehouse . If there is no need in the private server jar package , Then connect to the central warehouse to download jar Package to private service , Then download from the private server jar Package to local warehouse , For project use .

jar Package execution process ?

Maven Can scan pom file , according to pom The coordinates of the documents go to the local warehouse one by one to find the corresponding jar package , If you can find a direct introduction , If you can't find it Maven According to the image warehouse you configured, you will download it from the remote warehouse jar package . If the remote warehouse does not have a corresponding jar The package is first downloaded from the central warehouse to the remote warehouse, and then downloaded to the local warehouse . If not configured, directly connect to the central warehouse .

2.6.3 Add dependency : Mode one

Use maven The index function of the plug-in can be added quickly jar package

This way requires This... Is already included in the local warehouse jar package , Otherwise we can't find !!!

1、 If the local warehouse has what we need jar package , Can be in the project of pom.xml Right click in the blank space of the file –> Maven --> Add Dependency Add the required dependencies in the pop-up window (jar package ), Pictured :

 Insert picture description here

**2、** Add dependency example : add to spring Of jar Package coordinates into the project

(1) In the project pom.xml Right click in file -> Maven -> Add Dependency, Enter... In the pop-up window
“spring”: Search the local warehouse for jar package .

 Insert picture description here

Select the jar package ( The coordinates will be filled in automatically ), Click on OK You can add **( The premise is that the local warehouse has a corresponding jar package **)

 Insert picture description here

(2) If the search fails jar package ( Ensure that the... Has been downloaded from the local repository jar package , That is, there are... In the local warehouse jar package , But I can't download it ), You can try to rebuild the index .

 Insert picture description here

“Maven Repositories” The following contents can be seen in the view window :

 Insert picture description here

stay "Local Repositories" Right click to select “Rebuild Index” You can rebuild the index .

After completion , Try searching again jar Add package .

2.6.4 Add dependency : Mode two

1、 Directly in pom.xml Add... Inside the label in the file . for example : stay pom.xml Add the following configuration to the file , It can be junit Unit tested jar The package was introduced into the project .

Add dependency :

<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.9</version>
<scope>test</scope>
<dependency>
<dependencies>

2、 To manually add a dependency, you need to specify the dependency jar Coordinates of the package , But in most cases , We don't know jar The coordinates of the package . You can visit the following website , Search and query on the Internet :

http://mvnrepository.com

Or search and query in the company's remote warehouse :

http://maven.tedu.cn/nexus

3、 Example : add to c3p0 Of jar Package coordinates into the project

  • Visit one of the above web sites , Search... In the search box “c3p0”

  • In the search results , Select the desired version and click version , View this version of c3p0
    jar The coordinates corresponding to the package :

  • Copy coordinates directly to the of the project pom.xml In the file :

 Insert picture description here

 Insert picture description here
 Insert picture description here

4、 Copy the coordinates selected on the right in the above figure to pom.xml In file :

 Insert picture description here

2.7 Expand :Maven common problem


2.7.1 Copy Maven Warehouse

If it's because of the network environment ( such as : Computers don't have networks ), Lead to jar The package could not be downloaded , You can also download others ( complete )Maven Copy from your local warehouse , Put it in the local warehouse configured by yourself . because Maven Can support copying other people's warehouses .

2.7.2 Common environmental problems 8888888888888

Problem description 1:

  • establish Maven The project times the following errors :

[ 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-LGIACUId-1638456186157)(JAVAWEB-NOTE03.assets/image-20200619235505122.png)]

 Insert picture description here

  • Or create Maven Incomplete project directory structure ( Such as the only src Catalog ), Here's the picture :

 Insert picture description here

  • Import existing Maven project , The project cannot run (jar Not downloaded completely )

This is because maven Our environment has been destroyed , Lead to Maven Incomplete basic operating environment , could not be built Maven project , Or you can't download what you need jar package . resolvent :

(1) In the project pom Type a blank line in the file , Save the file again , The goal is to make maven detected pom The document has changed , According to pom The configuration in the file goes to the local warehouse to find the corresponding jar package , If there is no corresponding jar package ,maven It will be downloaded again .
(2) If that doesn't work , You can try on the project , Right click ---> Maven ---> Update Project..., Force update project , here maven It will also check pom file , Is there a corresponding... In the local warehouse jar package .
(3) If the above method still doesn't solve the problem , Check whether the current network environment can connect to the configured remote warehouse .( Like using the Internet at home , Unable to connect to the remote warehouse in Darnay , Or you can't connect to alicloud's remote warehouse by using mobile hot network )
a) In Dane classroom , It's connected to the intranet : stay settings.xml The file is configured to connect to the remote warehouse within
b) In the home , Using the Internet ( Not a mobile hotspot ): You can not configure , Default connection to central warehouse , perhaps stay settings.xml Configure the connection to alicloud warehouse in the file
c) It's a hot mobile network : You can't configure to connect to the remote warehouse or alicloud warehouse , Not even !!
(4) If the network can connect to the configured remote warehouse , Go to the local warehouse Directory , Delete all directories in the local repository , deleted ,eclipse Using resource file from local warehouse , So it will prevent deletion , At this time will be eclipse close , Then delete all the directories in the local warehouse , restart eclipse.
(5) start-up eclipse after , Then put the top of the (1) And the first step (2) Do it again !6) If not, replace your local warehouse with the local warehouse issued by the teacher .

** Problem description 2:** Open it for the first time every day Eclipse Discover previously created Maven Engineering error report ( For example, there is a cross or exclamation mark on the project , But before the project was OK Of ), resolvent : Find... In the menu bar Project —> Clean…

 Insert picture description here

Or is it : Right click on the item reporting error --> Maven --> Update Project:

 Insert picture description here

2.7.3 Can't find jar Package problem

In the project, we introduce... Through coordinates jar package ( Or plug-ins ), And there are corresponding in the local warehouse jar package , But the project still reported an error , The prompt says that... Cannot be found .

resolvent : If you introduce jar package , Exists in the local warehouse , But I still can't find , You can store... In the local warehouse jar Delete the entire directory of the package or plug-in ( If you are prompted that the file is in use when deleting , close eclipse Delete it again ), Save again pom.xml file , And update the project , Give Way maven Download the above... Again jar Bag can !

Incomplete sample download :

 Insert picture description here

Normal download complete example :

 Insert picture description here

2.7.4 Maven The scope of dependence

Here's a jsp-api Dependence ,maven Will go to download jsp-api Of jar Package and some of its dependencies jar package .

<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jsp-api</artifactId>
<version>2.0</version>
<scope>provided</scope>
</dependency>

There is a in the dependency configuration scope I haven't said before , It is Depend on the range .

1、 What is dependency range : Is to designate you jar At what stage is the package valid .

  • compile - Compile dependency range . Default range , Can not fill , Indicates that it is valid in all processes , Such as compile time 、 During the test 、 During operation, etc .

  • provided - Dependency scope... Has been provided . This scope means that only the compilation and test phases are available , There is no need to , image tomcat The container itself has provided servlet-api、jsp-api Such dependence .

  • runtime - Runtime dependency range . This range indicates that it is only valid during operation and testing , You don't need... During compilation , Like connecting to a database jdbc Drivers, etc .

  • test - Test dependency range . This range is only valid during the test phase , Compile and run without , Like unit testing provides junit package .

  • system - System dependency range . This range indicates that it does not depend on the local warehouse ,jar In other directories , Need to pass through systemPath Specify the path , This is not recommended .

  • import - Reference dependency range .Maven2.0.9 The scope added later , Can only be used in , And imported type by pom Parent project configuration of type , It is generally used to solve multi inheritance problems .

2、 What is dependent delivery :

As mentioned earlier, the transmission of dependencies can be achieved through inheritance and aggregation , You can easily inherit from the parent project through inheritance , It can also be transferred indirectly through aggregation .

Inherit :A Inherit B,A You can inherit B Of dependencies rely on .

polymerization :A rely on C,C rely on D, that A It depends on D Naturally, you get D Dependence .

3、 What is dependency exclusion :

In the process of dependency passing , Such as A rely on B、S2.0,B rely on C、S1.0, such A And then there is S1.0 and S2.0 Two dependencies , In some cases, this will cause conflicts. You need to manually B Indirectly passed dependencies are eliminated , Just don't rely on B Brought in S1.0 My bag .

<dependency>
<groupId>org.testgroupId>
<artifactId>B</artifactId>
<version>1.0</version>
<!-- exclude B Handed over S rely on -->
<exclusions>
<exclusion>
<groupId>com.test</groupId>
<artifactId>S</artifactId>
</exclusion>
</exclusions>
</dependency>

Or set it directly Exclude all indirect dependencies :

<dependency>
<groupId>org.testgroupId>
<artifactId>B</artifactId>
<version>1.0</version>
<!-- exclude B All the dependencies passed on -->
<exclusions>
<exclusion>
<groupId>*</groupId>
<artifactId>*</artifactId>
</exclusion>
</exclusions>
</dependency>

3. Cookie、Session

=====================

3.1 What is conversation


What is conversation : When the browser sends a request to access the server , Until the end of accessing the server , Until the browser is closed , During this period, I visited All the requests and responses generated between the browser and the server add up , It is called a session between the browser and the server .

Some data is often generated in a session , And these data often need us to keep , How to save the data generated in the session ?

  • For example, in the process of shopping , Add merchandise to cart , In fact, it is to save the commodity information to the database .( Don't discuss )
  • If you are not logged in , Add merchandise to cart , In fact, it saves the commodity information to cookie or session in .
  • Because the login will bind which user stores the data , No login, not stored in the database .

have access to cookie perhaps session Save the data generated in the session .

How to save the data generated in the session to cookie Or is it session in ?

3.2 cookie Principle and Application


3.2.1 cookie How it works

 Insert picture description here

  1. Cookie Is to transfer the data generated in the session Save on client , It's client technology .
  2. Cookie It works based on two heads : Namely Set-Cookie Response head and Cookie Request header
  3. adopt Set-Cookie The response header will cookie Send it to the browser from the server , Let the browser save to the inside ; And once the browser is saved cookie, In the future, every time the browser accesses the server , Will pass cookie Request header , take cookie The information is brought back to the server . When needed , On the server side, you can get the information in the request cookie Data in , So as to realize some functions .

3.2.2 cookie Of API And Application

1、 establish Cookie object

Cookie c = new Cookie(String name, String value);
// establish cookie At the same time, you need to specify cookie And cookie The value to save 
// Cookie Once your name is specified , You can't modify !

2、 take Cookie Add to response Response

response.addCookie( Cookie c );
// take cookie Add to response , The server is responsible for cookie The information is sent to the browser , Then saved to the inside by the browser ( You can call this method multiple times , Add more than one cookie)

3、 Get all... In the request cookie An array of objects

Cookie[] cs = request.getCookies();
// Get all... Carried in the request cookie Composed of cookie An array of objects , If the request does not carry any cookie, Calling this method will return null.

4、 Delete... In the browser Cookie

// cookie Of API Direct deletion... Is not provided in cookie Methods , You can delete... Indirectly in other ways cookie
// Delete the name as cart Of cookie: You can send another message with the same name to the browser cookie( The name is also called cart), And set up cookie The maximum survival time of is zero , Because the browser is based on cookie To distinguish cookie, If you send the same name to the browser twice cookie, Sent after cookie Will overwrite the previously sent cookie. Then sent cookie Set the lifetime to zero , Therefore, the browser will delete it immediately after receiving it !

Code example :

// Create a name cart Of cookie
Cookie c = new Cookie("cart", "");
// Set up cookie The maximum survival time of is zero 
c.setMaxAge( 0 );
// take cookie Add to response , Send it to the browser 
response.addCookie( c );
out.write( " Successfully deleted the file named cart Of cookie..." );

5、Cookie The common method of

cookie.getName(); // obtain cookie Name Once the name is specified, it cannot be modified 
cookie.getValue(); // obtain cookie The value stored in the 
cookie.setValue(); // Set up / modify cookie The value stored in the ( No, setName Method , because cookie Your name cannot be modified )
cookie.setMaxAge(); // Set up cookie Maximum lifetime of ( If not set ,cookie By default, it is destroyed at the end of a session !) API Direct deletion... Is not provided in Cookie Methods , Set to 0 Indirectly delete 

6、setMaxAge Method : Set up cookie Maximum lifetime of

 If this method is not set ,cookie The default is session level cookie, That is, the lifetime is a session . When the browser closes , At the end of the conversation ,cookie It's going to be destroyed (cookie By default, it is stored in the browser's memory , When the browser closes , Memory free ,cookie It will also be destroyed as the memory is released .)
If this method is set ,cookie Will not be saved to the browser's memory , Instead, it is saved as a file in the browser's temporary folder ( That is, on the hard disk ), Then close the browser , Memory free , Saved to hard disk cookie The document will not be destroyed , Open the browser again , You can also get... On your hard disk cookie Information .
If it is negative : Express Cookie In the browser's memory , By default, it is stored in the browser memory without setting
If by 0: Delete immediately Cookie

Code example :

// Create a Cookie object , Save product information to cookie in 
Cookie cookie = new Cookie( "cart", prod );
// Set up cookie Maximum lifetime of , Company : second 
cookie.setMaxAge( 60*60*24 );
// take cookie Object added to response Response 
response.addCookie( cookie );

3.2.3 Case study : Use cookie Simulation shopping cart

1.index.html stay webapp To create a html file ( Use maven establish html file )

[ 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-IgNc389V-1638456186161)(JAVAWEB-NOTE03.assets/120.PNG)]


<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title> List of goods </title>
</head>
<body>
<h3> Click on the following items to add them to the shopping cart </h3>
<!-- http://localhost:8080/day13-cookie/index.html http://localhost:8080/day13-cookie/CartServlet -->
<p>HUAWEI P30 <a href="CartServlet?prod=HUAWEI P30"> Add to cart </a></p>
<p>Iphone11 <a href="CartServlet?prod=Iphone11"> Add to cart </a></p>
<p>VIVONEX3s <a href="CartServlet?prod=VIVONEX3s"> Add to cart </a></p>
<p>xiaomi <a href="CartServlet?prod=xiaomi"> Add to cart </a></p>
<p> Small rice <a href="CartServlet?prod= Small rice "> Add to cart </a></p>
<h3> Click the payment link , Pay for shopping cart items </h3>
<a href="PayServlet"> Pay for shopping cart items </a>
</body>
</html>

2.CartServlet stay src/main/java Create one in the directory servlet Because it is java Program servlet Error reporting will = To introduce the running environment . F12 Network Application ----Cookies You can view the information you carry

Here you can delete , Change your name, etc .

[ 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-QdPbJhrS-1638456186162)(JAVAWEB-NOTE03.assets/121.PNG)]

package com.tedu;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/** * datetime: 2020 year 7 month 15 Japan In the morning 11:05:32 */
public class CartServlet extends HttpServlet {

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

response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
//=====================================
//1. Get the product information to be added to the shopping cart (prod=xxx)
String prod = request.getParameter( "prod" );
// The name of the goods is URL code ( Compare the Chinese characters and the spaces in it URL code )
String temp = URLEncoder.encode( prod , "utf-8");
//2. Create a Cookie object , Save product information to cookie in 
Cookie cookie = new Cookie( "cart", temp );
// Set up cookie Maximum lifetime of ! second / Company 
cookie.setMaxAge( 60*60*24*30 );
//3. take cookie Add to response (response) in , Send to browser to save 
response.addCookie( cookie );
//4. To respond to 
out.write( " Will succeed ["+prod+"] Joined the shopping cart ..." );
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

doGet(request, response);
}
}

3.PayServlet

package com.tedu;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/** * datetime: 2020 year 7 month 15 Japan In the morning 11:06:19 */
public class PayServlet extends HttpServlet {

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

response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
// Get all... In the request cookie Array of components 
Cookie[] cs = request.getCookies(); //null
// Traverse cookie Array 
String prod = null;
if( cs != null ) {

for (Cookie cookie : cs) {

// Judge the currently traversing cookie Is your name cart
if( cookie.getName().equals( "cart" ) ) {

// If it is , Then get cookie The value stored in the 
prod = cookie.getValue();
// Yes cookie The name of the product taken out from URL decode 
prod = URLDecoder.decode(prod , "utf-8");
}
}
}
if( prod == null ) {

out.write( " You haven't added any items to the shopping cart yet ..." );
}else {
 //prod!=null
out.write( " Success for ["+prod+"] Paid "+ (int)(Math.random()*10000) +" element ..." );
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

doGet(request, response);
}
}

Delete Cookie:

package com.tedu;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* datetime: 2020 year 7 month 15 Japan Afternoon 2:32:20
*/
public class DeleteCookie extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
// Delete the name as cart Of cookie
// Create a name cart Of cookie From the same server to the browser Cookie The name cannot be repeated , Repetition will cover Cookie, Different servers can repeat . This is to cover
Cookie c = new Cookie("cart", "");
// Appoint cookie The survival time is zero
c.setMaxAge( 0 );
// then cookie Send it to the browser
response.addCookie( c );
out.write( " Delete successful !" );
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}

3.3 session Principle and Application

3.3.1 session How it works

 Insert picture description here

  1. Session Is to transfer the data generated in the session Save on the server side , It's server-side technology
  2. Session Is a domain object ,session There's also a map aggregate , Go to session Data stored in , It's actually saving data to session Of map Collection .
  3. adopt session.setAttribute() Method can save data to session in , adopt session.getAttribute() Methods can transfer data from session To remove .
  4. One server corresponds to only one server session( The browser accesses the server for the first time , Will create Session, The previous will be used in the next visit , Not created until destroyed )

Be careful web It's best not to copy the project , Want to use the best to build a new . Because he can't send it to the server . If you simply change your name , Its release path has not changed . solve :

Right click on the project ----properties( The last option )—

Change the publishing path. The default is the project name .

[ 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-C37yiLxD-1638456186164)(JAVAWEB-NOTE03.assets/122.PNG)]

Then change it pom.xml file

[ 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-PqWJzAc0-1638456186165)(JAVAWEB-NOTE03.assets/123.PNG)]

3.3.2 session Is a domain object

obtain session object :

request.getSession()
// Get one session object ; If there is a corresponding to the current browser inside the server session, Directly returns the session object ; If there is no corresponding session, A new one will be created session Object returns ;

Session Is a domain object ,session There's also a map aggregate , also session Methods of accessing data are also provided in .

as follows :

session.setAttribute(String attrName, Object attrValue);
// Go to session Add a domain attribute to the domain , Property name can only be string type , Property values can be of any type .
session.getAttribute(String attrName);
// Get the value of the attribute in the domain according to the attribute name , The return value is one Object type 

Session Three characteristics of domain objects :

(1) Life cycle :

** establish session:** First call request.getSession() When the method is used , Will create a session object .( When the browser does not have a corresponding... On the server side session when , call request.getSession() The method server creates a session object .)

The destruction session: ( Similar person )

  1. Destroy over time : By default , When more than 30 Minutes no visit session,session It will be destroyed over time .(30 Minutes is the default time , You can modify , But it's not recommended to modify Yes 3 Kind of : Specific Baidu )

  2. commit suicide : call session Of invalidate When the method is used , It will be destroyed immediately session. (invalidate: To invalidate )

  3. Accidental death : When the server is shut down abnormally ( Hardware damage , power failure , Memory overflow causes the server to shut down abnormally ),session It will be destroyed when the server is shut down ;

    When the server is shut down normally , Before closing , The server will take the internal session Object serialization is saved to the server work Under the table of contents , Turn it into a file . This process is called session Passivation of ( serialize ); Start the server again , Passive session Will return to the server again , Become an object in the server , This process is called session Activation of ( Deserialization ).

**(2) Scope of action :** Within the scope of a conversation ( You get the same thing session object ) and cookie In a request , Smaller range .

**(3) The main function :** Share data in the whole session

Be careful :

If it is web project Make a copy and create a new web It is possible that the path of the project to browse will not change , It's best not to copy , if java Items can be copied without sending to the browser .

solve : Right click on the project Properties( The last option ) —Web Project Settings—Context root This is the oak release path , The default is consistent with the project name . The copied project still uses the previous release path , Make changes here . And then again Poem.xml Change the release path in the file .

3.3.3 Case study : Use session Simulation shopping cart

1、index.html


<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title> List of goods </title>
</head>
<body>
<h3> Click on the following items to add them to the shopping cart </h3>
<!-- http://localhost:8080/day13-cookie/index.html http://localhost:8080/day13-cookie/CartServlet -->
<p>HUAWEI P30 <a href="CartServlet?prod=HUAWEI P30"> Add to cart </a></p>
<p>Iphone11 <a href="CartServlet?prod=Iphone11"> Add to cart </a></p>
<p>VIVONEX3s <a href="CartServlet?prod=VIVONEX3s"> Add to cart </a></p>
<p>xiaomi <a href="CartServlet?prod=xiaomi"> Add to cart </a></p>
<p> Small rice <a href="CartServlet?prod= Small rice "> Add to cart </a></p>
<h3> Click the payment link , Pay for shopping cart items </h3>
<a href="PayServlet"> Pay for shopping cart items </a>
</body>
</html>

2、CartServlet

package com.tedu;
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;
import javax.servlet.http.HttpSession;
/** * datetime: 2020 year 7 month 15 Japan Afternoon 3:40:44 */
public class CartServlet extends HttpServlet {

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

response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
// Get the shopping cart item to add 
String prod = request.getParameter( "prod" );
// Get one session object , Save the item to session In the object 
//request.getSession(): It must return a session, Yes session Then return to , If not, create and then return It may be created before , Or if not, it will automatically create a session
HttpSession session = request.getSession();
// Temporarily session The timeout for is changed to 30 second 
//session.setMaxInactiveInterval( 30 );
session.setAttribute( "cart", prod );
// Make corresponding ( because session Is an object inside the server , So you don't have to send it to the browser )
out.write( " Will succeed ["+prod+"] Joined the shopping cart ~~~~~" );
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

doGet(request, response);
}
}

3、PayServlet

package com.tedu;
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;
import javax.servlet.http.HttpSession;
/** * datetime: 2020 year 7 month 15 Japan Afternoon 3:41:03 */
public class PayServlet extends HttpServlet {

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

response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
//=====================================
// Get the previous session( Yes session Then return to , No return null ) This place is to get data , Creating a new session It makes no sense .
HttpSession session = request.getSession(false);
// from session Get the previously added product information in 
String prod = null;
if( session != null ) {

System.out.println("session Not for null........");
// The return value is object type , Save string type . Forced to String
prod = (String)session.getAttribute( "cart" );
}
// To respond to 
if( prod == null ) {

out.write( " You haven't added the item to the shopping cart yet ~~~~~" );
}else {

// Simulate payment for goods ( Before payment , take session The destruction , At the same time, the commodity data in the shopping cart will be destroyed )
session.invalidate();
out.write( " Success for ["+prod+"] Paid "+(int)(Math.random()*10000)+" element ~~~~~" );
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

doGet(request, response);
}
}

3.4 summary : The difference between the two

Cookie and session All belong to conversation technology , Can save the data generated in the session , But because of cookie and session The working principle and characteristics of are different , Therefore, the application scenarios of the two are different .

Cookie Characteristics :

  1. cookie Is to save the data generated in the session in Browser client , It's client technology (JS You can visit cookie)

  2. cookie Is to save the data in the client browser , It is easy to lead to cookie Lost or stolen , therefore cookie The data stored in is not stable , It's not safe either .

  3. but cookie Save the data on the client , It doesn't have much impact on the server side , You can keep the data for a long time .

  4. summary : therefore cookie It is suitable for storage and needs to be saved for a long time 、 But data with low security requirements .

  5. The browser to cookie There are limits to the size and number of , It is generally recommended that every site send to the browser cookie No more than 20 individual , every last cookie The size does not exceed 1kb.

  6. Cookie Application : Realize shopping cart 、 Remember the user name 、30 Automatic login within days, etc .

Session Characteristics

  1. session Is to save the data generated in the session in Server side , It's server-side technology
  2. session Store data in server side session In the object , Relatively more secure , And more stable . It is not easy to operate with the user session Lost or stolen data in .
  3. but session It's a server-side object , When the amount of concurrency is high, each browser client must correspond to a server session object , Take up the memory space of the server , Affect efficiency .
  4. summary : therefore session It is suitable for storage and has high security requirements , But data that doesn't need to be saved for a long time .
  5. Session Application : Save login status 、 Save verification code

3.5 Extended content

3.5.1 cookie Save Chinese Space Data problems

Session There is no Chinese space in the stored data The problem of .

The following questions are for Tomcat8.0 And 8.0 The following version , stay Tomcat8.5 And 8.5 This problem has been solved in later versions !

HTTP The agreement stipulates that the request information and response information cannot contain Chinese data !

There's another problem : stay Tomact8.5 If there is a space between the stored data, an exception will be thrown ?

solve : Transcoding spaces It can be changed to + Decode after fetching and change to space Garbled code may not be resolved back , but URL The code can be parsed back .

// The name of the goods is URL code ( Compare the Chinese characters and the spaces in it URL code )
String temp = URLEncoder.encode( prod , "utf-8");
// Yes cookie The name of the product taken out from URL decode
prod = URLDecoder.decode(prod , "utf-8");

Therefore, when sending Chinese data to the server through the browser , The browser will edit Chinese data URL code , The encoding is in the following format :

 Insert picture description here

http://localhost/day13-cookie/index.html?user=%E5%BC%A0%E9%A3%9E%E9%A3%9E

Convert Chinese data into the following format , be called URL code :

Zhang Feifei ---> URL code ---> %E5%BC%A0%E9%A3%9E%E9%A3%9E

Turn the following format back to Chinese data , be called URL decode :

%E5%BC%A0%E9%A3%9E%E9%A3%9E ---> URL decode ---> Zhang Feifei

problem : When cookie Save Chinese data in , take cookie When added to the response , Will report a 500 abnormal , 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-29pVWvpX-1638456186166)(JAVAWEB-NOTE03.assets/image-20200226095315873.png)]

The solution is :

Will deposit cookie Proceed first in URL code , Re deposit Cookie in , for example :

[ 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-mcOw1Gyt-1638456186167)(JAVAWEB-NOTE03.assets/image-20200225174242538.png)]

from cookie The extracted data is for URL Encoded data , Before use, it is necessary to URL decode , for example :

[ 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-I0OkVhKv-1638456186167)(JAVAWEB-NOTE03.assets/image-20200225174252978.png)]

3.5.2 Can't get the previous session The problem of

Save the item to session In the after , Close the browser and then open the browser , Access server , At this time, the previous session. because session Is based on Cookie Working .

Create a... On the server session after , Would be session Assign a unique number , be called session Of id, In this response , The server will session Of id Take a name for JSESSIONID Of cookie Send it to the browser and save it inside the browser .

Because of saving sessionid Of cookie The default is session level cookie, After browser is closed ,cookie Will follow the destruction ,sessionid Also lost . So the next time you visit the server , No, session Of id You can't get the previous session. You can't get session Product information in

resolvent : We can create one named JSESSIONID Of cookie, It contains session Of ID, And set up cookie The maximum survival time of , Give Way cookie Save to hard disk ( Even if the browser is closed ,cookie It won't destroy ), So the next time you access the server , Can also be sessionid To the server , The server can go through sessionid Get the previous session. from session Get product information from

 Insert picture description here

4. MySQL Database transactions

Today's goal :

  • Understand the role of transactions

  • Grasp the four characteristics of business ( interview )

  • Understand the three concurrent read issues of transactions

  • master mysql Open and close business

  • Understand the four levels of isolation

4.1 Business and four characteristics


4.1.1 What is business

Database transactions (Database Transaction), A series of operations performed as a single logical unit of work , Or fully executed , Or not at all .

To put it simply : A transaction is a collection of SQL sentence ( It's usually adding, deleting and modifying ) Bind together to perform , Or they all succeed , Or they all fail , That is to say, only when the implementation is successful is success , Otherwise it's going to come back to this pile SQL Status before execution .

Let's take bank transfer as an example , Zhang sanzhuan 100 To Li Si's account , It takes at least two SQL sentence :

  • Subtract from Zhang San's account 100 element ;
update Account form set money=money-100 where name=' Zhang San ';
  • Add to Li Si's account 100 element .
update Account form set money=money+100 where name=' Li Si ';

If in the first article SQL After the statement is executed successfully , In implementation of Article 2 SQL The statement before , The program was interrupted ( Maybe an exception was thrown , It could be something else ), Li Si's account didn't add 100 element , And Zhang San subtracted 100 element , In real life, this is definitely not allowed .

If you add a transaction to the transfer process , Then all of the SQL Statement will be in a transaction , And all operations in a transaction , Or it all works , Or they all fail , There can't be a half success .

That is to say, subtract... From Zhang San's account 100 If yuan succeeds , So add... To Li Si's account 100 Meta operations must also be successful ; otherwise , Subtract... From Zhang San 100 Yuan and add... To Li Si 100 Yuan is a failure .

4.1.2 Four characteristics of transactions

Four characteristics of transactions (ACID) yes :

(1) Atomicity (Atomicity): All operations in a transaction are indivisible atomic units . All operations in the transaction are successful , Or all failed .

(2) Uniformity (Consistency): After transaction execution , Database state is consistent with other business rules . Such as transfer business , Whether the transaction is executed successfully or not , The sum of the amounts of the two accounts involved in the transfer should remain unchanged before and after the transaction .

 Zhang San :1000 1000-500=500 1000
Li Si :1000 1000+500=1500 1000

(3) Isolation, (Isolation): Isolation refers to concurrent operations , Separate transactions , Keep transactions in each concurrency from interfering with each other . in other words , When checking the data update in the process , The state of the data is either the state of another transaction before it was modified , Or another transaction changes its state , Transactions do not see data in the intermediate state . for example : stay A Transaction , See another B Business ( Modifying Zhang San's account amount ) Zhang's account amount , To see B Zhang San's account amount before the transaction , Or you can see B After the transaction, Zhang San's account amount .

2 Individuals take exams in different rooms , You can only see before entering the exam room and After the exam, I tried to find out the state of the room .

It's related to the isolation level .

 Business 1: Inquire about A、B Sum of account amount (1000+1000、500+1500、1000+1000)
Business 2: A Transfer to B 500 element
A - 500 = 500
B + 500 = 1500

(4) persistence (Durability): Once the transaction is committed successfully , All data operations in a transaction must be persisted to the database , Even after the transaction is committed , The database crashed immediately , On database restart , It must also be possible to ensure that data can be recovered through some mechanism .

The data will not be updated until it is submitted , Before submitting, it seems that the changes are only recorded. In fact, the original data is still unchanged .

Such as :A Transfer to B 100 element ,2 Everyone has 1000 element , a Turn into 900 element ,b Turn into 1100 But in fact, at this time 2 The person's account is still 1000 element , Only 2 After everyone transfers money successfully , And submit 2 The amount of people will change . If the middle party fails , The whole thing failed .

 Open transaction ---A to B Transfer accounts 500 element
A: 1000 - 500 = 500 ( succeed ) Record in the log , Transaction success ,A The account amount is updated to 500
B: 1000 + 500 = 1500 ( succeed ) Record in the log , Transaction success ,B The account amount is updated to 1500
End the business --- Roll back / Submit Roll back , That is, cancel the previous operation

4.2 MySQL The transaction


By default ,**MySQL Every time you execute one SQL sentence , It's all a separate business .** Because the bottom layer is executing SQL The transaction is automatically opened before the statement , stay SQL After statement execution , Will end the transaction immediately ! ( This end is the end of the submission )

if necessary Include multiple items in a transaction SQL sentence , You need to start and end the transaction manually .

  • Open transaction :start transaction; transaction: Business

  • End the business :commit( Commit transaction ) or rollback( Roll back the transaction ).

In execution SQL The statement before , Execute first strat transaction, This opens a transaction ( Starting point of transaction ), Then you can execute multiple SQL sentence , End of transaction ,commit Indicates submission , That is, multiple transactions SQL The impact of the statement is persisted to the database . perhaps rollback, Represents a rollback , That is, roll back to the start of the transaction , All previous actions have been undone !

The following demonstration A Account to B An example of account transfer :

Prepare the data :

set names gbk; Prevent garbled code in inserted data .

-- 1、 Create database jt_db database ( Create... If it doesn't exist )
create database if not exists jt_db charset utf8;
use jt_db; -- choice jt_db database 
-- 2、 stay jt_db Create... In the library acc surface ( Bank account statement ), Ask for id( Primary key ),name( full name ),money( Amount of account )
drop table if exists acc;
create table acc(
id int primary key auto_increment,
name varchar(50),
money double
);
-- 3、 Go to acc In the table , Insert 2 Bar record 
insert into acc values(null,'B',1000);
-- Inquire about acc All records in the table 
select * from acc;

Next, we will show you how to start and execute a series of transactions SQL after , Roll back the transaction 、 The effect of committing transactions and interrupting operations .

rollback( Roll back the transaction )

-- Inquire about acc In the account table A and B Amount of
select * from acc;
-- Open transaction
start transaction;
-- Start transferring money ,A Account minus 100 element
update acc set money=money-100 where name='A';
-- Inquire about acc In the account table A and B Amount of
select * from acc;
-- B Account increase 100 element
update acc set money=money+100 where name='B';
-- Inquire about acc In the account table A and B Amount of
select * from acc;
-- Roll back the transaction
rollback; comit Submit data
-- Query again acc In the account table A and B Amount of
select * from acc;

commit( Commit transaction ): Do the above operation again , The final will be rollback Replace with commit, That is, commit the transaction

commit; After submitting, it is successfully saved to the database , You can query , If you don't submit something, such as : In another Dos The window finds the data before updating .

Interrupt operation : Do the above operation again , The final will be rollback Replace with quit, Interrupt operation

quit;

4.3 Transaction concurrent read problem


4.3.1 Transaction concurrent read problem

Multiple transactions operate on the same data at the same time , This is called transaction concurrency .

When transactions are concurrent , If the necessary isolation measures are not taken , May lead to various concurrent problems , Destroy the integrity of data, etc . Among these questions , There are three types of reading questions , Namely : Dirty reading 、 It can't be read repeatedly 、 Fantasy reading .

(1) Dirty reading (dirty read): In a transaction **, Read data from another transaction that did not commit an update ,** That is, dirty data is read ;

for example : In a transaction ,A to B Transfer accounts 100 Yuan but uncommitted transaction , In another transaction B Query account amount , Query to A No updated data submitted , We call it dirty reading .

 Tips : The transaction isolation level of the database needs to be set to the minimum , To see dirty reading
Business 1: Open transaction ; A - 100 = 900; B + 100 = 1100; ( No transaction committed )
Business 2: Open transaction ; Inquire about B The amount of the account 1100, This process is called dirty reading , 1100 It's just dirty data

(2) It can't be read repeatedly (unrepeatable read): The two reading results of the same record are inconsistent , Because in During two queries , Another transaction has modified the record ( Is aimed at Modify the operating

for example : In the transaction 1 in , Two queries before and after A The amount of the account , Between two queries , Another thing 2 Yes A The amount of the account has been modified ( And also committed the transaction ), This situation may lead to transaction 1 in , The results of the previous two queries are inconsistent . This is unrepeatable reading .

 Business 1: Open transaction ---
First read A The amount of the account :1000
Second read A The amount of the account :900
Business 2: Open transaction ---
A Account - 100 = 900;
Commit transaction ---

(3) Fantasy reading ( Virtual reading )(phantom read): The results of two queries on the same table are inconsistent , Because during two queries , Another transaction has been inserted or deleted ( Is aimed at Insert or delete operation );

 Business 1: Open transaction ---
select * from acc where id=3;// non-existent id by 3 The record of There will be an error when inserting or deleting .
insert into acc value(3,'C',2000);
select * from acc where id=3;// There is id by 3 The record of 
Business 2: Open transaction ---
insert into acc value(3,'C',2000);
Commit transaction ---

Be careful :mysql By default, dirty reads and non repeatable reads are not allowed , So before the following demonstration, you need to set mysql Dirty reads are allowed 、 Non repeatable, etc .

set tx_isolation='read-uncommitted'; -- Set up mysql Transaction isolation level for
// This is the lowest level , Dirty reading is only possible at the lowest level .

1、 Dirty reading example :

-- At the window 1 in , Open transaction , perform A to B Transfer accounts 100 element 
set tx_isolation='read-uncommitted'; -- Dirty reading allowed 、 It can't be read repeatedly 、 Fantasy reading 
use jt_db; -- choice jt_db library 
start transaction; -- Open transaction 
update acc set money=money-100 where name='A';
update acc set money=money+100 where name='B';
-- At the window 2 in , Open transaction , Inquire about B Account amount of 
set tx_isolation='read-uncommitted'; -- Dirty reading allowed 、 It can't be read repeatedly 、 Fantasy reading 
use jt_db; -- choice jt_db library 
start transaction; -- Open transaction 
select * from acc where name='B'; -- Dirty data 
-- Switch to window 1, Roll back the transaction , Cancel the transfer operation .
rollback; -- Roll back the transaction 
-- Switch to window 2, Inquire about B Account amount of 
select * from acc where name='B';

At the window 2 in ,B See your account increase 100 element ( Data at this time A The operation transaction was not committed ), This situation is called " Dirty reading ".

2、 Non repeatable reading example :

-- At the window 1 in , Open transaction , Inquire about A The amount of the account 
set tx_isolation='read-uncommitted'; -- Dirty reading allowed 、 It can't be read repeatedly 、 Fantasy reading 
use jt_db; -- choice jt_db library 
start transaction; -- Open transaction 
select * from acc where name='A';
-- At the window 2 in , Open transaction , Inquire about A The amount of your account minus 100
set tx_isolation='read-uncommitted'; -- Dirty reading allowed 、 It can't be read repeatedly 、 Fantasy reading 
use jt_db; -- choice jt_db library 
start transaction; -- Open transaction 
update acc set money=money-100 where name='A'; -- A Account minus 100
select * from acc where name='A';
commit; -- Commit transaction 
-- Switch to window 1, Query again A The amount of the account .
select * from acc where name='A'; -- Inconsistent query results 

At the window 1 in , The same data twice before and after ( Account A Amount of ) The query results are inconsistent , Because between two queries , Another matter is A The amount of the account has been modified . This situation is " You can't read it over and over again "

3、 Examples of phantom reading :

-- At the window 1 in , Open transaction , Query whether the account table contains id=3 The account of 
set tx_isolation='read-uncommitted'; -- Dirty reading allowed 、 It can't be read repeatedly 、 Fantasy reading 
use jt_db; -- choice jt_db library 
start transaction; -- Open transaction 
select * from acc where id=3;
-- At the window 2 in , Open transaction , An entry was inserted into the account table id by 3 Record , And commit the transaction .
-- Set up mysql Dirty reads are allowed 、 Non repeatability 、 Fantasy reading 
set tx_isolation='read-uncommitted';
use jt_db; -- choice jt_db library 
start transaction; -- Open transaction 
insert into acc values(3, 'C', 1000);
commit; -- Commit transaction 
-- Switch to window 1, Because the upper window 1 No... Found in the query id by 3 The record of , So you can insert id by 3 The record of .
insert into acc values(3, 'C', 1000); -- Insertion will fail !

At the window 1 in , The query does not exist id by 3 The record of , So the next step is to insert id by 3 The record of , But when the insertion has not been performed , In another transaction id by 3 Records and commits the transaction , So the next window 1 The insert operation will fail .

Explore why , Found in the account table again id by 3 The record of ( It feels like an illusion ). This situation is called " Fantasy reading "

The above are three common concurrent read problems in transaction concurrency , So how to prevent these problems ?

You can prevent this by setting the transaction isolation level .

4.3.2 Transaction isolation level

There are four levels of transaction isolation , In the same data environment , Perform the same operation on the data , Set different isolation levels , May lead to different results . The ability of different transaction isolation levels to solve the data concurrency problem is also different .

set tx_isolation='read-uncommitted';

1、READ UNCOMMITTED( Read uncommitted data )

The worst security , Any transaction concurrency issues may occur ( For example, dirty reading 、 You can't read it over and over again 、 Unreal reading, etc )

But the performance is the best **( Don't use !!)**

2、READ COMMITTED( Read submitted data )(Oracle Default )

Poor safety

Good performance

Can prevent Dirty reading , But it can't prevent non repeatable reading , It doesn't prevent fantasy reading ;

3、REPEATABLE READ( Repeatable )(MySQL Default )

High security

Poor performance

Can prevent Dirty reading and It can't be read repeatedly , But it can't prevent the unreal reading problem ;

4、SERIALIZABLE( Serialization )

Highest security , No concurrency issues , Because its access to the same data is serial , Non concurrent access ;

The worst performance ;( Don't use !!)

MySQL The default isolation level for is REPEATABLE READ, That is, dirty reading and non repeatable reading can be prevented

4.3.3 Set isolation level ( understand )

0、MySQL Query the current transaction isolation level

select @@tx_isolation;

1、MySQL Set the transaction isolation level ( understand )

(1) set tx_isolation=‘read-uncommitted’;

The worst security , It's easy to see Dirty reading It can't be read repeatedly Fantasy reading , But the highest performance

(2) set tx_isolation=‘read-committed’;

General safety , Can prevent Dirty reading , Can't prevent It can't be read repeatedly Fantasy reading

(3) set tx_isolation=‘repeatable-read’;

Good security , Can prevent Dirty reading It can't be read repeatedly , But it can't be prevented Fantasy reading

(4) set tx_isolation=‘serialiable’;

The best security , It can prevent all transaction concurrency problems , But the worst performance .

2、JDBC Set up a transaction isolation domain

JDBC Pass through Connection The method provided is Set transaction isolation level :

Connection.setTransactionIsolation(int level)
Parameters can be 1 2 4 8 0, this 5 A constant corresponding to a value The effect is the same as that of the previous parameter form .

The optional parameters are as follows :

Connection.TRANSACTION_READ_UNCOMMITTED 1( Read uncommitted data ) The lowest level
Connection.TRANSACTION_READ_COMMITTED 2( Read submitted data )
Connection.TRANSACTION_REPEATABLE_READ 4( Repeatable )
Connection.TRANSACTION_SERIALIZABLE 8( Serialization ) The highest level
Connection.TRANSACTION_NONE 0( Do not use transactions ) Such as , When you only need to make a query, you can not use things

Tips : In development , Generally, there is no need to modify the transaction isolation level

3、JDBC Example of transfer in

Tips :JDBC The default is to commit transactions automatically , So you need to turn off auto submit , Instead, commit the transaction manually

in other words , When auto submit is turned off , The transaction starts automatically , But after execution, you need to manually commit or roll back !!

(1) Perform the following procedure , There is no exception in program execution , Transfer succeeded !A Account minus 100 element ,B Account increase 100 element .

(2) Will be the first 4 Step 、5 Let go of the code in the middle of the step , Execute the program again , Throw an exception in the transfer process , Transfer failure ! Due to transaction rollback , therefore A and B The amount of the account remains unchanged .

First in pom.xml Add... To the file mysql Drive pack If the local warehouse has stay pom.xml– Right click –maven—add dependency–

Collect in the pop-up window , See the notes above for details .

package com.tedu;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import com.tedu.util.JdbcUtil;
/** * test Jdbc Business */
public class TestTransaction {
public static void main(String[] args) throws SQLException {
Connection conn = null;
Statement stat = null;
ResultSet rs = null;
try {
//1. Get the connection 
conn = JdbcUtil.getConn();
//2. close JDBC Auto commit transaction If you don't close it, it will help you automatically submit things , Will help you automatically turn on 
//2 strip sql Statements are not in the same thing , beyond control 
conn.setAutoCommit(false);
//3. Get the transmitter 
stat = conn.createStatement();
/* ***** A to B Transfer accounts 100 element ***** */
//4.A Account minus 100 element 
String sql = "update acc set money=money-100 where name='A'";
stat.executeUpdate(sql);
// int i = 1/0; // Let the program throw an exception , Interrupt the transfer operation 
//5.B Account plus 100 element 
sql = "update acc set money=money+100 where name='B'";
stat.executeUpdate(sql);
//6. Commit transactions manually 
conn.commit();
System.out.println(" Transfer succeeded ! Commit transaction ...");
} catch (Exception e) {
e.printStackTrace();
// If one of the operations fails, it will be rolled back , Make both operations unsuccessful 
conn.rollback();
System.out.println(" Execution failure ! Roll back the transaction ...");
} finally{
//JdbcUtil.close(conn, stat, rs); The framework will help you automatically close resources 
//rs.close(); Query used rs Resources need to be closed , The update operation does not use rs, There is no need to close the resource .
stat.close();
conn.close();
}
}
}
Be careful : to Maven When adding dependencies , If used in local warehouse jar package , But I can't get it , Can be re indexed :
Maven Repositories window ( stay window show view In looking for )----- First click on ---Local
Repositoru ( Local repository )---Rebuild Index( Rebuild index )
ctrl shift +o : Package guide shortcut key

Good performance , Can prevent Dirty reading It can't be read repeatedly , But it can't be prevented Fantasy reading

(4) set tx_isolation=‘serialiable’;

The best security , It can prevent all transaction concurrency problems , But the worst performance .

2、JDBC Set up a transaction isolation domain

JDBC Pass through Connection The method provided is Set transaction isolation level :

Connection.setTransactionIsolation(int level)
Parameters can be 1 2 4 8 0, this 5 A constant corresponding to a value The effect is the same as that of the previous parameter form .

The optional parameters are as follows :

Connection.TRANSACTION_READ_UNCOMMITTED 1( Read uncommitted data ) The lowest level
Connection.TRANSACTION_READ_COMMITTED 2( Read submitted data )
Connection.TRANSACTION_REPEATABLE_READ 4( Repeatable )
Connection.TRANSACTION_SERIALIZABLE 8( Serialization ) The highest level
Connection.TRANSACTION_NONE 0( Do not use transactions ) Such as , When you only need to make a query, you can not use things

Tips : In development , Generally, there is no need to modify the transaction isolation level

3、JDBC Example of transfer in

Tips :JDBC The default is to commit transactions automatically , So you need to turn off auto submit , Instead, commit the transaction manually

in other words , When auto submit is turned off , The transaction starts automatically , But after execution, you need to manually commit or roll back !!

(1) Perform the following procedure , There is no exception in program execution , Transfer succeeded !A Account minus 100 element ,B Account increase 100 element .

(2) Will be the first 4 Step 、5 Let go of the code in the middle of the step , Execute the program again , Throw an exception in the transfer process , Transfer failure ! Due to transaction rollback , therefore A and B The amount of the account remains unchanged .

First in pom.xml Add... To the file mysql Drive pack If the local warehouse has stay pom.xml– Right click –maven—add dependency–

Collect in the pop-up window , See the notes above for details .

package com.tedu;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import com.tedu.util.JdbcUtil;
/** * test Jdbc Business */
public class TestTransaction {
public static void main(String[] args) throws SQLException {
Connection conn = null;
Statement stat = null;
ResultSet rs = null;
try {
//1. Get the connection 
conn = JdbcUtil.getConn();
//2. close JDBC Auto commit transaction If you don't close it, it will help you automatically submit things , Will help you automatically turn on 
//2 strip sql Statements are not in the same thing , beyond control 
conn.setAutoCommit(false);
//3. Get the transmitter 
stat = conn.createStatement();
/* ***** A to B Transfer accounts 100 element ***** */
//4.A Account minus 100 element 
String sql = "update acc set money=money-100 where name='A'";
stat.executeUpdate(sql);
// int i = 1/0; // Let the program throw an exception , Interrupt the transfer operation 
//5.B Account plus 100 element 
sql = "update acc set money=money+100 where name='B'";
stat.executeUpdate(sql);
//6. Commit transactions manually 
conn.commit();
System.out.println(" Transfer succeeded ! Commit transaction ...");
} catch (Exception e) {
e.printStackTrace();
// If one of the operations fails, it will be rolled back , Make both operations unsuccessful 
conn.rollback();
System.out.println(" Execution failure ! Roll back the transaction ...");
} finally{
//JdbcUtil.close(conn, stat, rs); The framework will help you automatically close resources 
//rs.close(); Query used rs Resources need to be closed , The update operation does not use rs, There is no need to close the resource .
stat.close();
conn.close();
}
}
}
Be careful : to Maven When adding dependencies , If used in local warehouse jar package , But I can't get it , Can be re indexed :
Maven Repositories window ( stay window show view In looking for )----- First click on ---Local
Repositoru ( Local repository )---Rebuild Index( Rebuild index )
ctrl shift +o : Package guide shortcut key
copyright:author[Cool breeze AAA],Please bring the original link to reprint, thank you. https://en.javamana.com/2022/02/202202130736118989.html