Course summary of VIP innovation project 1 semester 1 of 2021-2022 academic year

Course summary of VIP innovation project 1 semester 1 of 2021-2022 academic year

1. Java Foundation

1.1 how does java code execute

reference resources:
https://zhuanlan.zhihu.com/p/92906774
The Java execution process is as follows:

  1. Write Java code in the specified directory. The source code of Hello.java is as follows:
class Hello{ 
public static void main(String[] agrs){ 
     System.out.println("hello"); 
	} 
}
  1. Compiling java source code
    When the java source code is finished, it needs to be compiled by the compiler.
    After installing the jdk, we open the jdk directory and there are two. Exe files, namely javac.exe (compiled source code, xxx.java file) and java.exe (executed bytecode, xxx.class file)
    Enter the directory with the command line and compile the file javac Hello.java
F:\Your project path>javac Hello.java
  1. Type the compiled Hello.class file into a jar package
    jar -cvf hello.jar Hello.class
    c means to create a new jar package, v means to output some information about the creation process on the console during the creation process, and f means to name the generated jar package
 F:\Your project path> jar -cvf hello.jar Hello.class
 Added manifest
 Adding: Hello.class(input = 409) (output = 280)(Compressed 31%)
  1. Run the jar package
    java -jar hello.jar will report the following error. There is no main list attribute in hello.jar
F:\Your project path>java -jar hello.jar
hello.jar There is no master manifest attribute in the
  1. In the last case, you must enter and leave one line blank, otherwise the configuration of the last line cannot be recognized.

  2. Manifest version, main class and class path are followed by an English colon. The colon must be followed by a space, followed by the version number, class and ClassPath.

  3. Items in class path should be separated by spaces, not commas or semicolons.

  4. If there are many items in the class path, an error line too long will be reported when it is written in one line. At this time, the class path needs to be written in multiple lines. Note: starting from the second line, it must start with two spaces. I haven't tried more than three, but I can't start without a space or a space. I've tried.

  5. After class path is written, there must be a blank line at the end.

  6. Some configuration files in the jar package want to be placed outside the jar package, such as the file config.properties: if this file is loaded by path, such as new file("./config/config.properties"), then put config.properties in the config directory under the same directory of the jar package, that is to say, ". /" path is equivalent to the directory where the jar package is located; If the file is loaded as a file under the ClassPath, such as loading classpath:config.properties in Spring, add ". /" in the ClassPath of the configuration file of the MF file, and then put the configuration file in the same directory as the jar package. Alternatively, add ". / config /" in the ClassPath of the configuration file of the MF file, Then put the configuration files in the config directory under the same directory of the jar package.

When you open hello.jar with compression software, you will find a META-INF folder with a MENIFEST.MF file. Open it with Notepad

    Manifest-Version: 1.0
    Created-By: 1.8.0_121 (Oracle Corporation)
    Main-Class: Hello

Write main class: hello at the position of the third line (note that there is a space after the colon, and there is an empty line at the end of the whole file), and save
Run again

java -jar hello.jar

At this point, you can see hello on the console. Success

remarks:
. jar is divided into two types, one of which is just used as a call package; The other is that it can be executed directly, similar to. exe.
However, generally executable *. jar files are opened with winrar and other decompression software. You will find that there is a META-INF folder. There must be a MANIFEST.MF file in this folder. This file is mainly used to describe the executable *. jar execution entry file (usually a class file with main() method). The format is generally as follows:

Manifest-Version: 1.0
Created-By: 1.4.2_08 (Sun Microsystems Inc.)
Main-Class: Main

Here, Main is both a running class and a class file containing the main() method. The name is Main.class.

1.2 Java packaging case

1. jar package with package -- directly output hello

Method steps

(0) create directory F:\Example_Project

(1) Create the edu.hncj.vip directory and write a Hello.java file with Notepad

package edu.hncj.vip;

class Hello{
     public static void main(String[] agrs){
         System.out.println("hello");
     }
}

(2) Enter the directory with the command line and compile the file javac - D. hello. Java

F:\Example_Project\edu\hncj\vip>javac -d . Hello.java

javac -d. - d parameter: during compilation, the system will automatically generate the package directory. Parameter: specify the directory where the package name of Hello.java class will be generated, and. Represents the current directory, which can be specified arbitrarily

(3) Type the compiled Hello.class file into a jar package

jar -cvf hello.jar edu\hncj\vip\

F:\Example_Project\edu\hncj\vip>jar -cvf hello.jar edu\hncj\vip\
Added manifest
 Adding: edu/hncj/vip/(input = 0) (output = 0)(Stored 0%)
Adding: edu/hncj/vip/Hello.class(input = 422) (output = 292)(Compressed by 30%)

c means to create a new jar package, v means to output some information about the creation process on the console during the creation process, and f means to name the generated jar package

(4) Run the jar package

   java -jar hello.jar

At this time, the following error will be reported: there is no main list attribute in hello.jar

When you open hello.jar with compression software, you will find a META-INF folder with a MENIFEST.MF file. Open it with Notepad

Add main class attribute

Manifest-Version: 1.0
Created-By: 1.8.0_181 (Oracle Corporation)
Main-Class: edu.hncj.vip.Hello

Write main class: hello at the position of the third line (note that there is a space after the colon, and there is an empty line at the end of the whole file), and save

Run java -jar hello.jar again. At this time, you can see hello on the console successfully

2. jar package containing two classes -- output hello by calling

(0) create the directory F:\Example_Project \ jar >

(1) Write a Hello.java and a Student.java file with Notepad

The purpose is to have Hello call the Student's speak method

class Hello{
     public static void main(String[] agrs){
         //System.out.println("hello");
		 Student.speak();
     }
}

class Student{
    public static void speak(){
        System.out.println("hello,I'm 20 Grade students ");
    }
}

(2) Compilation: javac -encoding UTF-8 Hello.java

At this point, Hello.java and Student.java are compiled at the same time, because Student is invoked in Hello, and Student is also found in the process of compiling Hello.

F:\Example_Project\Of two classes jar>javac -encoding UTF-8 Hello.java

(3) Make jar package

Create META-INF folder under jar > of F:\Example_Project \ two classes

F:\Example_Project\Of two classes jar>mkdir META-INF

Create MANIFEST.MF under META-INF

F:\Example_Project\Of two classes jar>type nul>META-INF\MANIFEST.MF

This time, we define the main class directly in another way.

Manifest-Version: 1.0
Created-By: 1.8.0_121 (Oracle Corporation)
Main-Class: Hello

Prepare the above MANIFEST.MF file in advance and store it in META-INF folder. At this time, the command to type jar package is as follows

F:\Example_Project\Of two classes jar> jar -cvfm hello.jar META-INF\MANIFEST.MF Hello.class Student.class
 Added manifest
 Adding: Hello.class(input = 293) (output = 223)(Compressed 23%)
Adding: Student.class(input = 408) (output = 308)(Compressed 24%)

The jar -cvfm hello.jar META-INF\MANIFEST.MF Hello.class Student.class command is explained as follows:
Indicates that the first file is used as the MENIFEST.MF file, and hello.jar is used as the name to type Hello.class and Student.class into jar packages. One more parameter m indicates that the MANIFEST file is to be defined

(4) Run java -jar hello.jar, and you will see hello on the console. Success

F:\Example_Project\Of two classes jar> java -jar hello.jar
hello,I'm 20 Grade students

3. jar package with directory structure -- output hello by quoting the package and calling

(0) create folder

F:\Example_Project \ two class jar s with directory structure

(1) Let's change the previous one slightly by putting the Student class under the edu.hncj.vip package and Hello under the com package

Modify the Hello.java file

package com;

import edu.hncj.vip.Student;
class Hello{
     public static void main(String[] agrs){
         //System.out.println("hello");
		 Student.speak();
     }
}

Modify the Student.java file. Note that it needs to be modified to a public class

package edu.hncj.vip;

public class Student{
    public static void speak(){
        System.out.println("hello,I'm 20 Grade students ");
    }
}

View current directory structure

F:\Example_Project\Two classes with directory structure jar>tree .  /f  /a
 Folder for working volumes PATH list
 The volume serial number is 00000057 5296:88B3
F:\EXAMPLE_PROJECT\Two classes with directory structure JAR
+---com
|       Hello.java
|
\---edu
    \---hncj
        \---vip
                Student.java

Method steps

(1) Compile Hello.java

 javac -encoding UTF-8 -d . com\Hello.java

When you compile Hello.java, the Student.java file is compiled automatically

(2) Open the jar package and prepare the MANIFEST file as well

In F:\Example_Project \ create META-INF folder under jar > of two classes

F:\Example_Project\Two classes with directory structure jar>mkdir META-INF

Create MANIFEST.MF under META-INF

F:\Example_Project\Two classes with directory structure jar>type nul>META-INF\MANIFEST.MF

This time, we define the main class directly in another way. Pay attention to the blank lines behind

Manifest-Version: 1.0
Created-By: 1.8.0_121 (Oracle Corporation)
Main-Class: com.Hello
 There are blank lines here

Prepare the above MANIFEST.MF file in advance and store it in META-INF folder. At this time, the command to type jar package is as follows

jar -cvfm hello.jar META-INF\MANIFEST.MF com\Hello.class edu\hncj\vip

F:\Example_Project\Two classes with directory structure jar>jar -cvfm hello.jar META-INF\MENIFEST.MF com\Hello.class edu\hncj\vip
 Added manifest
 Adding: com/Hello.class(input = 310) (output = 238)(Compressed 23%)
Adding: edu/hncj/vip/(input = 0) (output = 0)(Stored 0%)
Adding: edu/hncj/vip/Student.class(input = 421) (output = 319)(Compressed 24%)
Adding: edu/hncj/vip/Student.java(input = 146) (output = 130)(Compressed by 10%)

The output indicates which files have been packaged in hello.jar

(3) Run java -jar hello.jar, and you will see hello on the console. Success

4. Make a jar package containing jar files

Let's make the scenario a little more complicated and take a look at the scenario where other jar packages need to be introduced into the jar package

1. Two jar packages call each other -- call the jar outside the jar to output hello

Finally generated jar package structure

hello.jar
tom.jar

Method steps

(0) generate student.jar

Preparation: create Student.java file

public class Student{
    public static void speak(){
        System.out.println("hello,I'm 20 Grade students ");
    }
}

Open cmd in the Student.java peer directory
Execute the following command to compile the java file

javac -encoding UTF-8 Student.java 

Execute the jar -cvf student.jar Student.class command to generate the jar package

F:\Example_Project\Two jar Mutual call>javac -encoding UTF-8 Student.java

F:\Example_Project\Two jar Mutual call>jar -cvf student.jar Student.class
 Added manifest
 Adding: Student.class(input = 408) (output = 307)(Compressed 24%)

(1) Write a Hello.java and compile it into Hello.class. Note that since the speak method of the Student class is referenced in Hello, you should use the - cp parameter to import the student.jar package into the jar package

Hello.java file content:

class Hello{
     public static void main(String[] agrs){
         //System.out.println("hello");
		 Student.speak();
     }
}

Execute the javac command to compile Hello.java
If you compile Hello.java directly, you will be prompted with the following error

F:\Example_Project\Two jar Mutual call>javac  Hello.java
Hello.java:5: error: Symbol not found
                Student.speak();
                ^
Symbol:   variable Student
 position: class Hello
 1 Errors

You can put the dependent jar s under the classpath while compiling Hello.java

 F:\Example_Project\Two jar Mutual call>javac -cp student.jar Hello.java

Here, - cp means - classpath, which means adding student.jar to the classpath

(2) Add hello.class to the jar package

Create the META-INF directory, create the MANIFEST.MF file, and pay attention to the blank line at the end

Manifest-Version: 1.0
Created-By: 1.8.0_181 (Oracle Corporation)
Main-Class: Hello
 There's room here

Reach the jar package and execute jar -cvfm hello.jar META-INF/MANIFEST.MF hello.class

F:\Example_Project\Two jar Mutual call>jar -cvfm hello.jar META-INF/MANIFEST.MF Hello.class
 Added manifest
 Adding: Hello.class(input = 293) (output = 223)(Compressed 23%)

At present, the jar package can be successfully achieved, but errors will occur during operation, as shown below.
(3) At this time, run java -jar and find the error ClassNotFoundException: Student

F:\Example_Project\Two jar Mutual call>java -jar hello.jar
Exception in thread "main" java.lang.NoClassDefFoundError: Student
        at Hello.main(Hello.java:5)
Caused by: java.lang.ClassNotFoundException: Student
        at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:349)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
        ... 1 more

The reason is very simple. To import a jar package, you need to configure a new attribute in the MENIFEST.MF file: class path. The path points to all the jar packages you need

Now open the MENIFEST.MF file in hello.jar and add class path. Should become

Manifest-Version: 1.0
Created-By: 1.8.0_121 (Oracle Corporation)
Main-Class: Hello
Class-Path: student.jar

(4) OK, modify this file and run it again. It is found that hello is successfully output on the console

tips: introduce multiple jar packages separated by spaces

So far, we can conclude that the command changes are as follows

javac -cp xxx.jar file to compile - d destination

jar -cvfm name MENIFEST file file file to package 1 file to package 2

5.jar package contains jar package -- call jar in jar to output hello

When we type the required third-party jar package into our own jar package in the project, if we still follow the above operation method, we will report that the Class exception is not found. The reason is that jar cannot refer to the jar package placed inside itself.
The specific implementation details of this situation are complex. You can refer to this article first:

http://www.cnblogs.com/adolfmc/archive/2012/10/07/2713562.html

Reference method 1: use AppClassloader to load

Reference method 2: you can also throw all the jars to be loaded into% JRE_ Under home% / lib / ext, the jar packages in this directory will be loaded by the Extension Classloader after the Bootstrap Classloader finishes working. Very convenient, very worry free.

(1) This section uses AppClassloader to load

In F: \ example_ Create edu.hncj.vip.Student.java under the directory containing the jar package in the project \ jar package

package edu.hncj.vip;

public class Student{
    public static void speak(){
        System.out.println("hello,I'm 20 Grade students ");
    }
}

(2) Generate student.jar file
Compile the Student.java file and execute the javac - D. - encoding UTF-8 edu / hncj / VIP / Student.java command

F:\Example_Project\jar The package contains jar package>javac -d . -encoding UTF-8 edu/hncj/vip/Student.java

Generate student.jar package, jar -cvf student.jar edu\hncj\vip\

F:\Example_Project\jar The package contains jar package>jar -cvf student.jar edu\hncj\vip\
Added manifest
 Adding: edu/hncj/vip/(input = 0) (output = 0)(Stored 0%)
Adding: edu/hncj/vip/Student.class(input = 421) (output = 319)(Compressed 24%)
Adding: edu/hncj/vip/Student.java(input = 146) (output = 130)(Compressed by 10%)

In F: \ example_ The project \ jar package contains the jar package directory, create the lib directory, and place the student s in the lib directory

(3) Create Hello.java and compile it
In F:\Example_Project\jar package contains jar package directory to create com.Hello.java, and Hello calls Student.

package com;
import edu.hncj.vip.Student;
class Hello{
     public static void main(String[] agrs){
         //System.out.println("hello");
		 Student.speak();
     }
}

Compile the Hello.java file, javac - D. - encoding UTF-8 COM / Hello.java

F:\Example_Project\jar The package contains jar package>javac -d . -encoding UTF-8 com/Hello.java

Generate the hello.jar package, jar -cvf hello.jar com\ lib\

F:\Example_Project\jar The package contains jar package>jar -cvf hello.jar com\ lib\
Added manifest
 Adding: com/(input = 0) (output = 0)(Stored 0%)
Adding: com/Hello.class(input = 310) (output = 237)(Compressed 23%)
Adding: com/Hello.java(input = 175) (output = 138)(Compressed 21%)
Adding: lib/(input = 0) (output = 0)(Stored 0%)
Adding: lib/student.jar(input = 1179) (output = 790)(Compressed 32%)

(4) Run hello.jar, Java - CP hello.jar, com.hello

F:\Example_Project\jar The package contains jar package>java -cp hello.jar com.Hello
Exception in thread "main" java.lang.NoClassDefFoundError: edu/hncj/vip/Student
        at com.Hello.main(Hello.java:6)
Caused by: java.lang.ClassNotFoundException: edu.hncj.vip.Student
        at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:349)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
        ... 1 more

Modify the MANIFEST.MF file in hello.jar

Manifest-Version: 1.0
Created-By: 1.8.0_181 (Oracle Corporation)
Class-Path: lib/student.jar

Run java -cp hello.jar com.Hello again

6. Read the configuration file outside the jar

(1) In F:\Example_Project \ read the files outside the jar and create Hello.java in the directory

Hello.java file

import java.io.InputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.FileInputStream;

class Hello{
    public static void main(String[] args) throws Exception{
        Hello hello = new Hello();
        InputStream is = new FileInputStream("jarconf.txt");
        print(is);
    }
    
    /**
     * Read the file, output the contents, general method
     */
    public static void print(InputStream inputStream) throws Exception {
        InputStreamReader reader = new InputStreamReader(inputStream, "utf-8");
        BufferedReader br = new BufferedReader(reader);
        String s = "";
        while ((s = br.readLine()) != null)
            System.out.println(s);
        inputStream.close();
    }
}

(2) Create a jarconf.txt text file under the same level directory, with the following contents:

calssname=vip
desc=This is an external configuration file

(3) Compile and package java files:
Compile the Hello.java file

javac -encoding UTF-8 Hello.java

Package the hello.jar file:

jar -cvf hello.jar Hello.class

Modify META-INF\MANIFEST.MF file and add

Manifest-Version: 1.0
Created-By: 1.8.0_181 (Oracle Corporation)
Main-Class: Hello

Execute jar: java -jar hello.jar

The complete code is as follows:

# Compile the Hello.java file as a class file
F:\Example_Project\read jar Files in>javac -encoding UTF-8 Hello.java

# Generate jar package,
F:\Example_Project\read jar External documents>jar -cvf hello.jar Hello.class
 Added manifest
 Adding: Hello.class(input = 1008) (output = 594)(Compressed 41%)

# Modify META-INF\MANIFEST.MF in hello.jar

# Execute jar
F:\Example_Project\read jar External documents>java -jar hello.jar
calssname=vip
desc=This is an external configuration file

Directory structure at this time

F:\Example_Project\read jar External documents>tree . /f /a
 Folder for working volumes PATH list
 The volume serial number is 00000001 5296:88B3
F:\EXAMPLE_PROJECT\read JAR External documents
|   Hello.class
|   hello.jar
|   Hello.java
|   jarconf.txt
|
\---META-INF
        MANIFEST.MF

7. Read the configuration file in the jar

(1) In F:\Example_Project \ read the file in the jar and create Hello.java

Hello.java file

import java.io.InputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;

class Hello{
    public static void main(String[] args) throws Exception{
        Hello hello = new Hello();
        InputStream is = hello.getClass().getResourceAsStream("jarconf.txt");
        print(is);
    }
    
    /**
     * Read the file, output the contents, general method
     */
    public static void print(InputStream inputStream) throws Exception {
        InputStreamReader reader = new InputStreamReader(inputStream, "utf-8");
        BufferedReader br = new BufferedReader(reader);
        String s = "";
        while ((s = br.readLine()) != null)
            System.out.println(s);
        inputStream.close();
    }
}

Create a jarconf.txt text file under the same level directory, with the following contents:

calssname=vip
desc=This is an internal configuration file

(2) Compile and type into jar package
Compile java files:

javac -encoding UTF-8 Hello.java

Package class files:

jar -cvfm hello.jar META-INF\MANIFEST.MF . 

Execute jar:

java -jar hello.jar

(3) The complete process is as follows:

# Compile the Hello.java file as a class file
F:\Example_Project\read jar Files in>javac -encoding UTF-8 Hello.java

# Generate the jar package and formulate META-INF\MANIFEST.MF at the same time
F:\Example_Project\read jar Files in>jar -cvfm hello.jar META-INF\MANIFEST.MF .
Added manifest
 Adding: Hello.class(input = 1109) (output = 637)(Compressed 42%)
Adding: Hello.java(input = 755) (output = 385)(Compressed 49%)
Adding: jarconf.txt(input = 50) (output = 55)(Compressed -10%)
Ignoring entry META-INF/
Ignoring entry META-INF/MANIFEST.MF

# Execute hello.jar
F:\Example_Project\read jar Files in>java -jar hello.jar
calssname=vip
desc=This is an internal configuration file

2.Maven topic

2.1Maven introduction

Maven is a build tool (package project), dependency management tool (resource dependency management tool: mainly used to integrate resources) and project information aggregation tool.

2.2Maven installation and common configuration

(1) Installation process
Simplest installation:

Select version
 Download decompression
 to configure MAVEN_HOME environment variable
 adopt mvn -version Confirm next version

This installation does not modify setting.xml, which will lead to Maven's dependence on Disk C and download from the central warehouse by default. The network speed may be slower. At this time, the following configuration can be modified:

Open the D: \ installation directory \ maven\conf\settings.xml file, find and modify the following configuration:

<!-- Modify local warehouse location -->
<localRepository>d:/apache/maven/maven-repo</localRepository>

<!-- Modify mirror address -->
<mirrors>
<!-- Download Image of the given warehouse. -->
<mirror>
    <!-- Unique identifier of the mirror. id Used to distinguish between different mirror Element. -->
	<id>nexus-aliyun</id>
	<!-- Of the mirrored server id. For example, if we want to set up a Maven Central warehouse( http://repo.maven.apache.org/maven2 /), you need to set this element to central. This must be exactly the same as the id central of the central warehouse. -- >
	<mirrorOf>*,!jeecg,!jeecg-snapshots,!getui-nexus</mirrorOf>
	<!-- Image name -->
	<name>Nexus aliyun</name>
	<!-- Of the mirror URL. Building the system will give priority to the use of this URL,Instead of using the default server URL.  -->
	<url>http://maven.aliyun.com/nexus/content/groups/public</url>
</mirror> 
</mirrors>

<repositories>
  <!--Contains information that needs to be connected to the remote warehouse -->
  <repository>
    <!--Unique identification of remote warehouse -->
    <id>codehausSnapshots</id>
    <!--Remote warehouse name -->
    <name>Codehaus Snapshots</name>
    <!--How to handle the download of release version in remote warehouse -->
    <releases>
      <!--true perhaps false Indicates whether the warehouse is enabled for downloading certain types of components (release version, snapshot version). -->
      <enabled>false</enabled>
      <!--This element specifies how often updates occur. Maven Will compare local POM And remote POM The timestamp of the. The options here are: always(All the time), daily(Default, daily), interval: X(here X Is the time interval in minutes), or never(Never). -->
      <updatePolicy>always</updatePolicy>
      <!--When Maven What to do when verifying the component verification file fails-ignore(Ignore), fail(Failed), or warn(Warning). -->
      <checksumPolicy>warn</checksumPolicy>
    </releases>
    <!--How to handle the download of snapshot version in remote warehouse. Yes releases and snapshots These two sets of configurations, POM You can adopt different strategies for each type of component in each separate warehouse. For example, someone may decide to turn on support for snapshot version download only for development purposes. See repositories/repository/releases element -->
    <snapshots>
      <enabled />
      <updatePolicy />
      <checksumPolicy />
    </snapshots>
    <!--Remote warehouse URL,Press protocol://hostname/path form -- >
    <url>http://snapshots.maven.codehaus.org/maven2</url>
    <!--Warehouse layout type used to locate and sort components-Can be default(Default) or legacy(Legacy). Maven 2 Provides a default layout for its warehouse; However, Maven 1.x There is a different layout. We can use this element to specify that the layout is default(Default) or legacy(Legacy). -->
    <layout>default</layout>
  </repository>
</repositories>

2.3Maven project introduction

1. Create Maven project

We can create Maven projects from the command line or from IDEA.
Open the command line window, jump to D:\maven directory, and execute the following mvn command.

mvn archetype:generate -DgroupId=edu.hncj -DartifactId=helloMaven -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false

Parameter Description:

DgroupId: Project team ID,It is usually the reverse of the organization name or company website.
DartifactId: Project name.
DarchetypeArtifactId: appoint ArchetypeId,maven-archetype-quickstart Used to quickly create a simple Maven project
DinteractiveMode: Whether to use interactive mode.

It should be noted that each Maven project needs to have a unique positioning coordinate, that is, the GAV (groupId: project group ID, DartifactId: project name, Version, unique release Version number) mentioned above

2.Maven project catalogue

Engineering structure: agreement is better than configuration
Convention Over Configuration is one of Maven's core concepts. Maven has specified the directory structure of the project and the naming method of test cases. All projects managed by Maven must abide by these rules.
During Maven project construction, the default project structure will be automatically created, and developers only need to place corresponding files under the corresponding directory structure.
For example, the following table shows the default locations of project source code files, resource files, and other configurations in the Maven project.

  file      	catalogue                
  Java source code	src/main/java     
  resource file    	src/main/resources
  Test source code   	src/test/java     
  Test resource file  	src/test/resources
  Package output file  	target            
  Compile output file  	target/classes    

2.4Maven common commands

1,mvn compile compile,take Java Source program compiled into class Bytecode file.
2,mvn test Test and generate test report
3,mvn clean Convert the previously compiled old class Bytecode file deletion
4,mvn pakage pack,dynamic web Engineering play war Package, Java Engineering play jar Bag.
5,mvn install Build project jar The package is placed in the warehouse for other modules to call

2.5Maven pom.xml introduction

Reference resources:
https://blog.csdn.net/weixin_38569499/article/details/91456988
https://blog.csdn.net/liuxiao723846/article/details/106578518

Common labels:

Modelversion is the model version of maven. It follows the definition of maven and cannot be modified.

groupId
The project organization is generally the top-level domain name + company or organization name. For example, the project organization of Alibaba is com.alibaba. If your company's domain name is www.abc.com, your project organization should be named com.abc.

artifactId
The name of the project is also an important indicator of the introduction of dependencies between projects. For example, alibaba has a dubbo project, which may be associated with many sub projects, so artifactId defines projects such as dubbo and dubbo config.

version
The project version and iterative development of the project may go through many versions. By this definition, it is a packaged component by default, such as dubbo-2.8.4.jar. In addition, there are two concepts of version: 0.0.1-SNAPSHOT is a SNAPSHOT version, and 0.0.1-RELEASE or RELEASE without SNAPSHOT is a RELEASE version.

There are several types of packaging: POM, jar, Maven plugin, EJB, war, ear, rar,
par, which is not filled in by default, is the jar package. Generally, pom, jar and war are commonly used.

properties
Configure public properties, such as spring web and spring AOP. You need to rely on these two. They must be the same version, such as 4.5.0. You can put the version number on the properties for unified management and easy maintenance.
dependecies
Configuration project dependency information

builds
Used to manage and execute maven declaration cycles, including plugins, maven dependency plugin, and resources

2.6 Maven project case - generate QR code

1. Build Maven project based on IDEA or Eclipse

Set GAV coordinates:
edu.hncj
VIP01
1.0-SNAPSHOT

Add pom dependency

Add the following tags in pom.xml under the project:

<dependencies>
		<!-- Define the library for QR code generation-->
        <dependency>
            <groupId>com.google.zxing</groupId>
            <artifactId>core</artifactId>
            <version>3.3.1</version>
        </dependency>
        <dependency>
            <groupId>com.google.zxing</groupId>
            <artifactId>javase</artifactId>
            <version>3.3.1</version>
        </dependency>
</dependencies>

<build>
<plugins>
			<!-- definition maven Packaged compilation plug-ins for -->
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.6.0</version>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
          <encoding>UTF-8</encoding>

        </configuration>
      </plugin>

      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-assembly-plugin</artifactId>
        <version>3.1.1</version>

        <configuration>
<!--          <archive>-->
<!--            <manifest>-->
<!--              <mainClass>org.example.HttpClientTest</mainClass>-->
<!--            </manifest>-->
<!--          </archive>-->

          <descriptorRefs>
            <descriptorRef>jar-with-dependencies</descriptorRef>
          </descriptorRefs>
          <encoding>UTF-8</encoding>

        </configuration>
        <executions>
          <execution>
            <id>make-assembly</id>
            <phase>package</phase>
            <goals>
              <goal>single</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
    </plugins>
</build>

Writing Java code

Under edu.hncj.VIP01 package, create QRCodeGenerator class, as follows:

package edu.hncj.VIP01;

import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

public class QRCodeGenerator {
     public static byte[] createQRCode(int width, int height, String content) throws WriterException, IOException {
// Basic parameter setting of QR code
        Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");// Set encoded character set utf-8
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);// Set the error correction level L/M/Q/H. The higher the error correction level, the more difficult it is to identify. The current setting level is the highest level H
        hints.put(EncodeHintType.MARGIN, 0);// The setting range is 0-10, but there are only four changes 0 1 (2) 3 (4 5 6) 7 (8 9 10)
// The generated picture type is QRCode
        BarcodeFormat format = BarcodeFormat.QR_CODE;
// Create bit matrix object
        BitMatrix bitMatrix = new MultiFormatWriter().encode(content, format, width, height, hints);
// Set the parameters of bit matrix to picture
//        MatrixToImageConfig config = new MatrixToImageConfig(Color.black.getRGB(), Color.white.getRGB());
// Bit matrix object to stream object
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        MatrixToImageWriter.writeToStream(bitMatrix, "png", os);
        return os.toByteArray();

    }

    public static void main(String[] args) throws WriterException, IOException {
        byte[] b = createQRCode(100, 100, "Meet your best self!");
        OutputStream os = new FileOutputStream("E:\\bestme.png");
        os.write(b);
        os.close();
    }
}

Right click to execute to run successfully. At the same time, the bestme.png file is generated in the root directory of E disk. After scanning the QR code with wechat, you can see the message "meet the best yourself!"

Package, generate jar s, and execute

Double click package under maven to generate jar package at target
Enter the G:\ideaproject\VIP01\targe directory, enter CMD, and then enter it in the command line window

G:\ideaproject\VIP01\target>java -cp VIP01-1.0-SNAPSHOT-jar-with-dependencies.jar edu.hncj.VIP01.QRCodeGenerator

Execute the code, and the bestme.png image will be generated in the root directory of the E-disk

3.Git topics

3.1Git introduction

Git is one of the most advanced distributed version control systems in the world.
What are the characteristics of Git? Simply put, it is: high-end atmosphere, high-grade! Written by Linus, the father of linux.

3.2 work area, temporary storage area, local warehouse and remote warehouse

Git has
Workspace: workspace
index/Stage: staging area
Repository: local repository
Remote: remote warehouse
Four areas, as shown in the figure below:
Usually, the code we write is in the workspace. After executing the add command, it is submitted to the temporary storage area. After executing the commit command, the code is submitted to the version library. Finally, execute the push command to submit the local code to the remote version library. The figure below basically means this.

3.3Git installation

Download from Git's official website at: https://git-scm.com/downloads

The next step is to install

After installation, configure the user name and mailbox

$ git config --global user.name "Your Name"
$ git config --global user.email "email@example.com"

View user name and email address

$ git config user.name
$ git config user.email

Modify local user name and email address:

$ cd ~/you project                       
$ git config user.name  "username"      
$ git config user.email "email"   

3.4 Git basic commands

1. Initialize a repository:

The version library can be simply understood as a directory. All files in this directory can be managed by GIT. Git can track the modification and deletion of each file, so that the history can be tracked at any time, or "restored" at some time in the future.

  • Create an empty directory:
$ mkdir learngit
$ cd learngit
  • Use the git init command to turn this directory into a repository that Git can manage:
$ git init
Initialized empty Git repository in /Users/michael/learngit/.git/

In an instant, GIT has built the warehouse and told you that it is an empty Git repository. Careful readers can find that there is an additional. Git directory in the current directory. Git tracks and manages the version library. Don't manually modify the files in this directory, otherwise the GIT warehouse will be damaged if it is changed.
If you don't see the. git directory, it's because the directory is hidden by default. You can see it with the ls -ah command.

2. Add files to the version Library

Write a readme.txt file in the directory of the version library learngit, as follows:

Git is a version control system.
Git is free software.

Be sure to put it in the learngit directory (subdirectory is OK), because this is a git warehouse. Git can't find this file in other places.

It takes only two steps to put a file in Git warehouse, compared with three steps to put an elephant in the refrigerator.

First, use the command git add to tell Git to add the file to the warehouse:

$ git add readme.txt

Execute the above command without any display, which is right. The philosophy of Unix is "no news is good news", indicating that the addition is successful.

Step 2: use the command git commit to tell Git to submit the file to the warehouse:

$ git commit -m "wrote a readme file"
[master (root-commit) eaadf4e] wrote a readme file
 1 file changed, 2 insertions(+)
 create mode 100644 readme.txt

3. Time shuttle

Modify the readme.txt file to read as follows:

Git is a distributed version control system.
Git is free software.

Now run the git status command to see the results:

$ git status
On branch master
Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

	modified:   readme.txt

no changes added to commit (use "git add" and/or "git commit -a")

The git status command allows us to keep abreast of the current state of the warehouse. The above command output tells us that readme.txt has been modified, but it is not ready to submit the modification.
Use git diff to view the specific modifications:

  $ git diff readme.txt 
    diff --git a/readme.txt b/readme.txt
    index 46d49bf..9247db6 100644
    --- a/readme.txt
    +++ b/readme.txt
    @@ -1,2 +1,2 @@
    -Git is a version control system.
    +Git is a distributed version control system.
     Git is free software.

git diff, as the name suggests, is to view difference. The display format is the general diff format of Unix. You can see from the command output above that we have added a distributed word in the first line.

After you know what changes have been made to readme.txt, it's much easier to submit it to the warehouse. Submitting changes and submitting new files are the same two steps. The first step is git add:

$ git add readme.txt

Again, there is no output. Before executing the second step git commit, let's run git status to see the status of the current warehouse:

$ git status
On branch master
Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

	modified:   readme.txt

git status tells us that the modifications to be submitted include readme.txt. Next, you can submit them safely:

$ git commit -m "add distributed"
[master e475afc] add distributed
 1 file changed, 1 insertion(+), 1 deletion(-)

After submitting, we use the git status command to see the current status of the warehouse:

$ git status
On branch master
nothing to commit, working tree clean

Git tells us that there are no changes to submit at present, and the working tree is clean.

Summary

  • To keep track of the status of the workspace, use the git status command.
  • If git status tells you that a file has been modified, use git diff to view the modified content.

3.4 version return

View submission history:
There must be a command in the version control system that can tell us the history. In Git, we use the git log command to view:

$ git log
commit 1094adb7b9b3807259d8cb349e7df1d4d6477073 (HEAD -> master)
Author: Michael Liao <askxuefeng@gmail.com>
Date:   Fri May 18 21:06:15 2018 +0800

    append GPL

commit e475afc93c209a690c39c13a46716e8fa000c366
Author: Michael Liao <askxuefeng@gmail.com>
Date:   Fri May 18 21:03:36 2018 +0800

    add distributed

commit eaadf4e385e865d25c48e7ca9c8395c3f7dfaef0
Author: Michael Liao <askxuefeng@gmail.com>
Date:   Fri May 18 20:59:18 2018 +0800

    wrote a readme file

The git log command displays the latest and farthest submission logs. We can see three submissions. The latest one is append GPL, the last one is add distributed, and the earliest one is write a readme file.

If you are dazzled by too much output information, you can try adding the – pretty=oneline parameter:

$ git log --pretty=oneline
1094adb7b9b3807259d8cb349e7df1d4d6477073 (HEAD -> master) append GPL
e475afc93c209a690c39c13a46716e8fa000c366 add distributed
eaadf4e385e865d25c48e7ca9c8395c3f7dfaef0 wrote a readme file

Regression history version
First, Git must know which version the current version is. In Git, HEAD is used to represent the current version, that is, the latest submission 1094adb... (note that my submission ID is certainly different from yours). The previous version is HEAD, and the previous version is HEAD. Of course, it is easier to write 100 versions up to 100, so it is written as HEAD~100.

Now, to rollback the current version of append GPL to the previous version of add distributed, you can use the git reset command:

$ git reset --hard HEAD^
HEAD is now at e475afc add distributed

– what is the meaning of the hard parameter? I'll talk about this later. Now you can use it at ease.
Note: if the version is rolled back, git log will lose subsequent records, that is, you can no longer view the version after the current version. At this time, you can use git reflog command, which can record each operation

Git provides a command git reflog to record every command:

$ git reflog
e475afc HEAD@{1}: reset: moving to HEAD^
1094adb (HEAD -> master) HEAD@{2}: commit: append GPL
e475afc HEAD@{3}: commit: add distributed
eaadf4e HEAD@{4}: commit (initial): wrote a readme file

You can see each change from the command execution history, so you can roll back the version to the specified version.

To sum up:

  • The version pointed to by HEAD is the current version. Therefore, Git allows us to shuttle between the version history and use the command git reset --hard commit_id.
  • Before shuttling, you can view the submission history with git log to determine which version to fallback to.
  • To go back to the future, use git reflog to view the command history to determine which version to go back to in the future.

3.5 other commands

Command git checkout
The command git checkout – readme.txt means to undo all modifications of the readme.txt file in the workspace. There are two situations:
One is that as like as two peas, the readme.txt is not being put in the temporary storage area since it has been modified.
One is that readme.txt has been added to the staging area and modified. Now, undo the modification and return to the state after adding to the staging area.
In short, this file is returned to the state of the last git commit or git add.

Command git rm
To delete the file from the version library, use the command git rm to delete it, and git commit:

$ git rm test.txt
rm 'test.txt'

$ git commit -m "remove test.txt"
[master d46f35e] remove test.txt
 1 file changed, 1 deletion(-)
 delete mode 100644 test.txt

The file is now deleted from the repository.

If the deletion is wrong, you can restore the wrongly deleted file from the version library to the latest version:

$ git checkout -- test.txt

git checkout actually replaces the version of the workspace with the version in the version library. No matter whether the workspace is modified or deleted, it can be "restored with one click".

3.6 remote warehouse

Add remote warehouse
Suppose that after you have created a Git warehouse locally, you want to create a Git warehouse in GitHub and synchronize the two warehouses remotely. In this way, the warehouse on GitHub can be used as a backup and other people can cooperate through the warehouse. It is really killing multiple birds with one stone.

Connect the existing local warehouse with the remote warehouse and run the command under the local learngit warehouse:

$ git remote add origin git@github.com:michaelliao/learngit.git

Please be careful to replace the above Michael Liao with your own GitHub account name. Otherwise, you are locally associated with my remote library. There is no problem with the association, but you can't push it in the future because your SSH Key public key is not in my account list.

After adding, the name of the remote library is origin, which is the default name of Git. It can also be changed to other names, but the name origin can be known as the remote library at a glance.

Next, you can push all the contents of the local library to the remote library:

$ git push -u origin master
Counting objects: 20, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (15/15), done.
Writing objects: 100% (20/20), 1.64 KiB | 560.00 KiB/s, done.
Total 20 (delta 5), reused 0 (delta 0)
remote: Resolving deltas: 100% (5/5), done.
To github.com:michaelliao/learngit.git
 * [new branch]      master -> master
Branch 'master' set up to track remote branch 'master' from 'origin'.

Push the contents of the local library to the remote. Using the git push command actually pushes the current branch master to the remote.

Because the remote library is empty, when we first push the master branch, we add the - u parameter. Git will not only push the contents of the local master branch to the new remote master branch, but also associate the local master branch with the remote master branch. In future push or pull, we can simplify the command.

After successful push, as like as two peas in the GitHub page, you can see that the contents of the remote library are exactly the same as those of the local library.

Clone from remote library

Last time we talked about how to associate remote libraries when there are local libraries first and then remote libraries.
Now, assuming we develop from scratch, the best way is to create a remote library first and then clone it from the remote library.
Now that the remote library is ready, the next step is to clone a local library with the command git clone:

$ git clone git@github.com:michaelliao/gitskills.git
Cloning into 'gitskills'...
remote: Counting objects: 3, done.
remote: Total 3 (delta 0), reused 0 (delta 0), pack-reused 3
Receiving objects: 100% (3/3), done.

Please change the address of Git library to your own, and then enter gitskills directory to see that README.md file already exists:

$ cd gitskills
$ ls
README.md

If more than one person cooperates in the development, each person can clone one from a remote location.

You may also notice that GitHub gives more than one address, which can also be used https://github.com/michaelliao/gitskills.git Such an address. In fact, git supports a variety of protocols. The default git: / / uses ssh, but other protocols such as HTTPS can also be used.

In addition to the slow speed of using https, the biggest trouble is that you must enter a password for each push. However, in some companies that only open the http port, you can't use the ssh protocol but only use https.

Summary

To clone a warehouse, you must first know the address of the warehouse, and then clone it with the git clone command.

Git supports a variety of protocols, including https, but ssh is the fastest.

3.7 summary of common commands for Git

Easy command line tutorial:

Git global settings:

git config --global user.name "Your username"
git config --global user.email "Your mailbox"

Create git warehouse:

mkdir gittest1
cd gittest1
git init
touch README.md
git add README.md
git commit -m "first commit"
git remote add origin2 git@gitee.com:Your username/gittest1.git
git push -u origin master

Existing warehouse?

cd existing_git_repo
git remote add origin git@gitee.com:Your username/gittest1.git
git push -u origin master

summary

This article mainly shares Java packaging, Maven installation and use, and Git installation and use, which may not be comprehensive enough, but try to provide readers with the basic features of the three technologies in a relatively long time.
If you have any questions, please leave a message in time and will reply in time.

Tags: Java jar

Posted on Sun, 05 Dec 2021 19:14:18 -0500 by mewhocorrupts