Project Management and SSM Framework - Maven

Maven learning + case practice



1. Introduction to Maven

1. Introduction to Maven

Maven is a project management tool. It can help programmers build projects, manage jar packages, compile code, complete testing, project packaging, and more.

●The Maven tool is implemented based on POM (Project Object Model, project object model). Under the management of Maven, each project is equivalent to an object.
●Maven standardizes the construction of projects. That is, the project structure, build commands, etc. are standardized.
●Maven provides a free central warehouse, in which you can find almost any popular open source class library.
●Maven is cross-platform, and the same commands can be used on Windows, Linux, and Mac.

2. The role of Maven

One-click build
Our projects often go through a series of processes such as compiling, testing, running, packaging, installing, and deploying. These processes are called builds. Through the Maven tool, the construction work can be easily completed with simple commands.

Dependency management
In traditional web projects, we must copy the jar packages that the project depends on to the project, which causes the project to become very large. If a company has ten projects with the same architecture, then this jar package needs to be copied to ten different projects, which is a waste of resources.

For the same project content, the traditional Web project size is as follows:

insert image description here

And the size of the project built using Maven is as follows:

insert image description here

This shows that most of the disk space in traditional web projects is occupied by jar packages, but there must be no jar packages in Maven projects, so how do projects without jar packages run?

insert image description here

The maven project does not directly import the jar package into the project, but has a warehouse dedicated to storing the jar package, and each jar package in the warehouse has its own coordinates. In the maven project, you only need to configure the coordinates of the jar package. When the project needs to use the jar package, you can get the jar package from the maven warehouse according to the coordinates and then run it.

3. Maven installation

Download
https://maven.apache.org/download.cgi

image-20211111163834866

Installation
Unzip the downloaded installation file. After decompression, the directory structure is as follows:

image-20211111164129440

●bin: stores the command of maven
●boot: stores the boot program of maven itself, such as class loader, etc.
●conf: stores the configuration file of maven
●lib: stores the jar package required for maven itself to run

Configure environment variables
Since Maven is developed by the Java language and depends on the Java environment at runtime, it must be configured in the environment variables of the computerJAVA_HOME

insert image description here

In order to use Maven commands more conveniently, you need to configure MAVEN_HOMEandPath

insert image description here

insert image description here

View the version
Open the CMD command window, enter mvn -v, and display the Maven version and Java version, which proves that the installation is successful

![Insert picture description here](https://img-blog.csdnimg.cn/d54a3ed3963f404085fc1f661477de3e.png?x-oss-process=

4. Types and structures of Maven projects

Maven project type

●POM project
POM project is a logical project, and Maven will not package this type of project. These projects often do not contain specific services, but are used to integrate other projects.

●JAR project
As a common Java project, the project will be packaged into a jar package when packaging.

●WAR project
JAVA Web project, the project will be packaged into a war package.

Maven project structure
Next, we learn the structure of Maven project through a WAR project

File directory structure:
insert image description here
●src: source code
●target: compiled file
●pom.xml: Maven project configuration file, such as coordinate information, etc.

Project structure:
insert image description here
src/main/java: store java files of the project
src/main/resources: store project resource files, such as configuration files
src/test/java: store test files of the project
src/test/resources: store Resource files for testing

5. The life cycle of a Maven project

The process of using maven to complete the construction of the project includes: verification, compilation, testing, packaging, deployment and other processes. Maven regulates these processes as the life cycle of project construction.

insert image description here

life cycle work done
validate validate Verify that the project is correct
compile compile source code compilation
Test Test Run the tests using an appropriate unit testing framework such as junit.
package package Create JAR/WAR package
check verify The results of the integration tests are checked to ensure that the quality is up to standard.
install install Install the packaged project to the local repository for use by other projects.
deploy deploy Copy the final project package to the remote warehouse to share with other developers and projects.

Maven has three sets of independent life cycles. It is divided into construction life cycle, clean life cycle (cleaning the built files), and site life cycle (generating project reports). As a developer, the general focus is on learning the build life cycle.

6. Maven common commands

Every step of building a project in Maven can be completed with a simple command. Next, we will learn these commands:

Order effect
mvn clean Clear the compiled class files, that is, delete the target directory.
mvn validate Verify that the project is correct
mvn compile Compile maven project
mvn test Compile maven project and run test file
mvn package Compile the maven project and run the test file, and package it
mvn install Compile the maven project and run the test file and package it, and publish it to the local warehouse
mvn deploy Deploy project to remote repository
mvn tomcat7:run Run the project with tomcat

Maven relies on plug-ins to execute commands, such as clean, validate and other commands that come with maven, and the tomcat7 command is a third-party plug-in introduced.

7. Maven warehouse type

Local repository
A local repository refers to a folder on a user's computer. It is used to store the jar package downloaded from the remote warehouse or the central warehouse. Only the jar package downloaded to the local warehouse can be used. When the project uses the jar package, it is first searched from the local warehouse.

Remote warehouse
Remote warehouse generally refers to private server, which is a warehouse service set up on a local area network. It can download resources from the central warehouse for use in the local area network, thereby reducing the bandwidth wasted by each programmer downloading from the central warehouse.

If the jar package required by the project is not available in the local warehouse, it will be downloaded from the remote warehouse, and it can be used after downloading to the local warehouse.

The remote warehouse does not have to be configured. If the local warehouse does not have a jar package and the remote warehouse is not configured, it will be downloaded directly from the central warehouse.

Central Warehouse
The Central Warehouse is a server on the Internet. It is the largest warehouse provided by Maven, and it has the most complete jar package resources.

If the jar package required by the project is not available in the local warehouse or the remote warehouse, it will be downloaded from the central warehouse and downloaded to the local warehouse for use.

Maven central warehouse access page: https://mvnrepository.com/

The access speed of the central warehouse is relatively slow. We generally configure mirrors to proxy download requests from the central warehouse, such as Ali mirrors and Huawei mirrors.

8. Maven configuration file

The default location of the local warehouse is ${user.dir}/.m2/repository, ${user.dir}which means the windows user directory. We can ${MAVEN_HOME}\conf\settings.xmlmodify the location of the local warehouse by modifying it.

Configure the local warehouse Add the following tags
in <settings>:

<!-- 本地仓库路径 -->
<localRepository>F://repository</localRepository>

Configuring mirroring
Because the access speed of the central warehouse is slow, you can configure the mirroring agent to download requests from the central warehouse. <settings>Add the following tags in the following <mirrors>to configure the mirror:

<mirror>  
    <!-- 指定镜像ID -->
    <id>nexus-aliyun</id>  
    <!-- 匹配中央仓库。-->
    <mirrorOf>central</mirrorOf>
    <!-- 指定镜像名称 -->    
    <name>Nexus aliyun</name>  
    <!-- 指定镜像路径 -->
<url>http://maven.aliyun.com/nexus/content/groups/public</url>  
</mirror>

Configure the JDK version
When creating a maven project, the default JDK version 1.5 is used, and the verification syntax, compilation, and runtime will be operated according to JDK1.5, so many syntaxes cannot be used. If the JDK installed on this machine is JDK11, you can configure maven to create projects according to JDK11.

<settings>Add the following tags in the following <profiles>to configure the JDK version:

<profile>   
    <id>jdk11</id>    
    <activation>   
        <activeByDefault>true</activeByDefault>    
        <jdk>11</jdk>   
    </activation>    
    <properties>   
        <maven.compiler.source>11</maven.compiler.source>    
        <maven.compiler.target>11</maven.compiler.target>    
        <maven.compiler.compilerVersion>11</maven.compiler.compilerVersion>   
    </properties>   
</profile>

2. Maven project development

1. IDEA configures the Maven plugin

File-Settings-search maven-configuration Maven home directory: the path where the downloaded maven is located, User settings file:the path where maven’s settings.xml file is located, Local repository:repository local warehouse path

insert image description here
insert image description here

2. Construct Maven project

Open idea and choose to create a new project

insert image description here

Select the Maven project and use the maven web project template

insert image description here

Click Next to fill in the project information

Name: project name Location: project save path GroupId: company or organization name ArtifactId: project name Version: version number

Subsequent to complete the creation

The src/main/java directory needs to be added manually, and Java code cannot be written in this directory at this time.

Set the src/main/java directory Mark Directory asas Sources Root.

3. pom file configuration

The top of the pom file is the basic information of the project:

groupId
groupId generally defines the project group name, and the naming rules use reverse domain names.

artifactId
artifactId generally defines the project name, using lowercase letters for naming. After the project is released, its coordinates are groupId+artifactId.

version
version defines the version number. The version number generally has three paragraphs, the first paragraph: revolutionary product upgrades. Second paragraph: New feature release. Third paragraph: Fix some bugs.

packaging
packaging defines the packaging method.

<properties>Define some configuration information in:
insert image description here

<dependencies>Define the dependent jar package coordinates in:

Since the project is a web project, Servlet and JSP need to be written, so the dependencies of Servlet and JSP need to be introduced. Find sites that rely on coordinates:
https://mvnrepository.com/

insert image description here
Configuration example:

1<dependencies>
2    <dependency>
3        <groupId>junit</groupId>
4        <artifactId>junit</artifactId>
5        <version>4.11</version>
6        <scope>test</scope>
7    </dependency>
8    <!-- jsp -->
9    <dependency>
10        <groupId>javax.servlet.jsp</groupId>
11        <artifactId>jsp-api</artifactId>
12        <version>2.2</version>
13    </dependency>
14    <!-- servlet -->
15    <dependency>
16        <groupId>javax.servlet</groupId>
17        <artifactId>javax.servlet-api</artifactId>
18        <version>3.0.1</version>
19    </dependency>
20</dependencies>

<plugins>Define third-party plugins in:

The web project relies on tomcat to run, so add the tomcat7 plug-in

Example:

1<plugins>
2    <!-- tomcat插件 -->
3    <plugin>
4        <groupId>org.apache.tomcat.maven</groupId>
5        <artifactId>tomcat7-maven-plugin</artifactId>
6        <version>2.1</version>
7        <configuration>
8            <port>8080</port>
9            <path>/</path>
10            <uriEncoding>UTF-8</uriEncoding>
11            <server>tomcat7</server>
12        </configuration>
13    </plugin>
14</plugins>

4. Maven dependency scope

Because our project introduces Servlet and Jsp jar packages, and when the project is running, Tomcat will use its own Servlet and Jsp jar packages, which causes jar package conflicts. And if the project does not introduce the Servlet and Jsp jar packages, the project will fail to compile.

At this time, you can set the scope of dependency to solve this problem. Setting the jar package of Servlet and Jsp only works during compilation, and does not work during runtime. This will not only pass compilation, but also avoid jar package conflicts during runtime.

By <dependency>adding in <scope>, you can set the scope of the dependency, with the following values:

compile
default scope. Indicates that the dependency takes effect when compiling and running, and the dependency will also be packaged when the project is packaged.

provided
Maven dependencies that use this dependency scope are valid when compiling and testing, but not at runtime. A typical example is servlet-api. The web container has already provided dependencies at runtime, so Maven does not need to introduce it repeatedly.

runtime
The scope of runtime indicates that it does not need to take effect at compile time, but only at runtime. A typical example is the JDBC driver package, which only needs the JDBC interface of the JDK when compiling, and only needs the specific JDBC driver when running the project.

test
The test range indicates that the dependencies using this dependency range only take effect when compiling and running the test code, and such dependencies are not required for the normal operation of the program. A typical example is JUnit, which is only needed when compiling test code and running tests.

system
If some of the jar packages we depend on do not have Maven coordinates, they are not in the Maven system at all. At this time, you can download it to the local hard disk and then refer to it through system.

So we can add the scope of Servlet and Jsp dependencies to provided.

1<dependency>
2    <groupId>javax.servlet.jsp</groupId>
3    <artifactId>jsp-api</artifactId>
4    <version>2.2</version>
5    <scope>provided</scope>
6</dependency>
7<dependency>
8    <groupId>javax.servlet</groupId>
9    <artifactId>javax.servlet-api</artifactId>
10    <version>3.0.1</version>
11    <scope>provided</scope>
12</dependency>

Restart the project to access Servlet and Jsp normally

3. Maven engineering test

1. Test overview

Testing is to evaluate the written code before delivery, which is divided into black box testing and white box testing:

Black-box testing : No need to write code, give the input value to see if the program can output the expected value.
White box testing : need to write code. Pay attention to the specific execution process of the program.
insert image description here

Unit testing refers to the inspection and verification of the smallest testable unit in the software. Unit testing in Java refers to the function of a class. Unit testing is the lowest level of testing activity to be performed during software development, where an independent unit of software is tested in isolation from the rest of the program.

Junit is a unit testing framework for the Java programming language for writing and running repeatable automated tests. From the classification belongs to white box testing.

2. Junit usage steps

Introduce dependency in Maven project

1<dependency>
2    <groupId>junit</groupId>
3    <artifactId>junit</artifactId>
4    <version>4.12</version>
5    <scope>test</scope>
6</dependency>

Define the class to be tested
We define a calculator tool class.

1public class Calculator {
    
    
2    // 加法
3    public int add(int a,int b){
    
    
4        return a+b;
5    }
6    // 除法
7    public int div(int a,int b){
    
    
8        return a/b;
9    }
10}

Test the defined classes
Create a src/test/java package and set the package as a test package.

Create a test class package in src/test/java, and the package name is generally consistent with the package name to be tested.

Define the test class, the class name is generally the class under test + Test

insert image description here

Write the test method in the test class.

1public class CalculatorTest {
    
    
2    /**
3     * 测试方法是可以独立运行的,写法如下:
4     * 1.方法名一般为test+被测试方法名
5     * 2.方法上方添加@Test
6     * 3.测试方法没有参数和返回值
7     */
8    @Test
9    public void testAdd(){
    
    
10        Calculator calculator = new Calculator();
11        int add = calculator.add(1, 2);
12        System.out.println(add);
13    }
14
15    @Test
16    public void testDiv(){
    
    
17        Calculator calculator = new Calculator();
18        int div = calculator.div(2,0);
19        System.out.println(div);
20    }
21}

3. Junit result judgment

Click the triangle next to the test method to run the test method. If a green tick appears, it proves that the method can run normally; if a red exclamation mark appears, it proves that the method throws an exception and needs to be modified.
insert image description here

Of course, it doesn’t mean that the method must have no problem if it can run normally, and the result of the method may not be consistent with the expected result. In this case, the assertion operation is needed.

1@Test
2public void testAdd(){
    
    
3    Calculator calculator = new Calculator();
4    int add = calculator.add(1, 2);
5    /**
6     * 断言
7     * 参数1:预期结果,参数2:实际结果
8     */
9    Assert.assertEquals(2,add);
10}

If the actual result does not match the expected result, the following exception is thrown:
insert image description here

4.@Before、@After

In the test class, @Beforethe decorated method will be automatically executed before the test method, and @Afterthe decorated method will be automatically executed after the test method is executed. For example, we can set the pre-method to acquire resources, and the post-method to release resources.

1@Before
2public void before(){
    
    
3    System.out.println("开始测试");
4}
5
6@After
7public void after(){
    
    
8    System.out.println("结束测试");
9}

4. Reliance on conflict mediation

1. Shortest path first principle

Causes of Dependency Conflict—Dependency Transfer
Suppose your project depends on jar package A, and jar package A depends on jar package B. When adding jar package A, Maven will automatically add jar package B to the project. For example, we just added junit dependencies, and junit depends on hamcrest, so Maven will add both junit and hamcrest to the project.

insert image description here

At this time, dependency conflicts may arise. For example, dependency A will introduce dependency C, and dependency B will also introduce dependency C. If there is no mediation, two dependencies C will be introduced, so how does Maven solve the problem of dependency conflicts?

Dependency conflict mediation
Let's take Spring dependency as an example. spring-webmvc depends on spring-aop, and spring-context also depends on spring-aop. If both are introduced at the same time, which version of spring-aop will be introduced?

Test code:

1<dependency>
2    <groupId>org.springframework</groupId>
3    <artifactId>spring-context</artifactId>
4    <version>5.2.12.RELEASE</version>
5</dependency>
6
7<dependency>
8    <groupId>org.springframework</groupId>
9    <artifactId>spring-webmvc</artifactId>
10    <version>4.2.4.RELEASE</version>
11</dependency>

The first principle of Maven mediating dependency conflicts is the shortest path first principle:

That is, the version with the shortest path in the project's dependency tree will be used. For example, suppose there are several jar packages whose dependencies are: A->B->C->D(2.0)and E->F->D(1.0), if both A and E are imported, then D(1.0) will be used because the path from E to D is shorter.

The way to view the dependency path is as follows:
insert image description here
The path from spring-webmvc to spring-aop is as follows:
insert image description here
The path from spring-context to spring-aop is as follows:
insert image description here
As you can see, the path from spring-webmvc to spring-aop is:
spring-webmvc -> spring-context ->spring-aop

And the path from spring-context to spring-aop is:
spring-context ->spring-aop

The path from spring-context to spring-aop is shorter, so spring-aop will be introduced according to the version of spring-context.
insert image description here

2. First to declare principle

The shortest path first principle cannot solve all problems, such as this dependency: A–>B–>C(1.0)and D–>E–>C(2.0), after introducing A and D at the same time, the length of the dependency path of C (1.0) and C (2.0) is 2. At this point first principles will not solve the problem

The second principle of Maven's mediation of dependency conflicts is the principle of first declaration:
on the premise that the lengths of the dependency paths are equal, the order of the dependency declarations in the POM will be parsed and used. For example: In the above case, the paths from spring-webmvc and spring-context to spring-core are both 1. Whoever declares above, spring-core will be introduced according to whose version. (Refer to the picture above.)

3. Exclude dependencies

If you don't want to use Maven's default conflict mediation method, there are two ways to manually mediate conflicts.

Exclude dependencies
For example, in the above case, if you want to use the spring-aop package of spring-webmvc, you can exclude the import of spring-aop package when importing spring-context, so that you can use the spring-aop package of spring-webmvc to test the code writing as follows:

1<dependency>
2    <groupId>org.springframework</groupId>
3    <artifactId>spring-webmvc</artifactId>
4    <version>4.2.4.RELEASE</version>
5</dependency>
6<dependency>
7    <groupId>org.springframework</groupId>
8    <artifactId>spring-context</artifactId>
9    <version>5.2.12.RELEASE</version>
10    <exclusions>
11        <exclusion>
12            <groupId>org.springframework</groupId>
13            <artifactId>spring-aop</artifactId>
14        </exclusion>
15    </exclusions>
16</dependency>

4. Lock version

After configuring a locked version for a certain jar package in Maven, regardless of the dependency declaration order and dependency path, the locked version shall prevail and be added to the project. This method is commonly used in enterprise development. The version locked by spring-aop can be directly configured as follows.

1<dependencyManagement>
2    <dependencies>
3        <dependency>
4            <groupId>org.springframework</groupId>
5            <artifactId>spring-aop</artifactId>
6            <version>4.2.4.RELEASE</version>
7        </dependency>
8    </dependencies>
9</dependencyManagement>

Five, Maven aggregation development

1. Aggregation relationship

If we have written two projects now, namely the e-commerce seller and the e-commerce buyer, both projects need to call the method of the serive layer to query the order. The original way of writing is as follows:
insert image description here
such repeated coding reduces development efficiency.

After using maven, we can split the previous project into small projects as needed, and then publish the small projects to the warehouse. Small projects can also refer to each other, and introduce the required small projects into our projects. That's it.
insert image description here

Maven divides a large project into small projects for development, and finally packs these small projects into a complete war package to run independently.

2. Inheritance relationship

Inheritance in Maven is for parent projects and child projects. Dependencies and plugin subprojects defined by the parent project can be used directly. Note: The parent project type is a POM type project.

Multiple inheritance
In Maven, single inheritance is also used for inheritance, which means that a sub-project can only have one parent project. But we can configure multiple inheritance. It is written as follows:

1<dependencyManagement>
2    <dependencies>
3        <!--父项目a-->
4        <dependency>
5            <groupId>com.package</groupId>
6            <artifactId>parent_a</artifactId>
7            <version>1.0-SNAPSHOT</version*>
8            <type>pom</type>
9            <!-- 引入父项目,scope的值为import -->
10            <scope>import</scope>
11        </dependency>
12
13        <!--父项目b-->
14        <dependency>
15            <groupId>com.package</groupId>
16            <artifactId>parent_b</artifactId>
17            <version>1.0-SNAPSHOT</version>
18            <type>pom</type>
19            <scope>import</scope>
20        </dependency>
21    </dependencies>
22</dependencyManagement>

6. Maven Aggregation Case

1. Build the parent project

insert image description here

1. Create a Maven project without selecting a template when creating it.
insert image description here
2. Since the parent project is a virtual project, no logic code needs to be written, so delete the src directory of the parent project.

3. Since the parent project's dependencies and plug-ins can be inherited by sub-projects, all required dependencies and plug-ins can be configured in the parent project.

1<groupId>com.package</groupId>
2<artifactId>maven_demo2</artifactId>
3<version>1.0-SNAPSHOT</version>
4<packaging>pom</packaging>
5
6<properties>
7    <maven.compiler.source>11</maven.compiler.source>
8    <maven.compiler.target>11</maven.compiler.target>
9</properties>
10
11<dependencies>
12    <dependency>
13        <groupId>junit</groupId>
14        <artifactId>junit</artifactId>
15        <version>4.12</version>
16        <scope>test</scope>
17    </dependency>
18    <dependency>
19        <groupId>javax.servlet.jsp</groupId>
20        <artifactId>jsp-api</artifactId>
21        <version>2.2</version>
22        <scope>provided</scope>
23    </dependency>
24    <dependency>
25        <groupId>javax.servlet</groupId>
26        <artifactId>javax.servlet-api</artifactId>
27        <version>3.0.1</version>
28        <scope>provided</scope>
29    </dependency>
30    <!-- jdbc驱动 -->
31    <dependency>
32        <groupId>mysql</groupId>
33        <artifactId>mysql-connector-java</artifactId>
34        <version>8.0.27</version>
35    </dependency>
36    <!-- jstl -->
37    <dependency>
38        <groupId>org.apache.taglibs</groupId>
39        <artifactId>taglibs-standard-spec</artifactId>
40        <version>1.2.5</version>
41    </dependency>
42    <dependency>
43        <groupId>org.apache.taglibs</groupId>
44        <artifactId>taglibs-standard-impl</artifactId>
45        <version>1.2.5</version>
46    </dependency>
47</dependencies>
48
49<build>
50    <plugins>
51        <!-- tomcat插件 -->
52        <plugin>
53            <groupId>org.apache.tomcat.maven</groupId>
54            <artifactId>tomcat7-maven-plugin</artifactId>
55            <version>2.1</version>
56            <configuration>
57                <port>8080</port>
58                <path>/</path>
59                <uriEncoding>UTF-8</uriEncoding>
60                <server>tomcat7</server>
61                <systemProperties>
62<java.util.logging.SimpleFormatter.format>%1$tH:%1$tM:%1$tS %2$s%n%4$s: %5$s%6$s%n</java.util.logging.SimpleFormatter.format>
63                </systemProperties>
64            </configuration>
65        </plugin>
66    </plugins>
67</build>

What is the difference between a project and a module in IDEA?

There is no difference, except that the new project will occupy a new window. We generally define it as a new project when writing a parent project, and define it as a new module when writing a subproject.

2. Build the dao module

In the dao subproject, the entity class and dao layer are generally written:

1. Create a maven module under the parent project, do not select a template, and be sure to select the parent project when creating it.
insert image description here
2. Write the parent project in the pom file of the submodule to prove that the inheritance is successful.

3. Prepare the database

1CREATE DATABASE `student`;
2USE `student`;
3DROP TABLE IF EXISTS `student`;
4CREATE TABLE `student` (
5  `id` int(11) NOT NULL AUTO_INCREMENT,
6  `name` varchar(255) DEFAULT NULL,
7  `sex` varchar(10) DEFAULT NULL,
8  `address` varchar(255) DEFAULT NULL,
9  PRIMARY KEY (`id`)
10) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
11
12insert  into `student`(`id`,`name`,`sex`,`address`) values (1,'小可爱','男','青青草原'),(2,'小淘气','女','海洋');

4. Write entity classes

1public class Student {
    
    
2    private int id;
3    private String name;
4    private String sex;
5    private String address;
6    
7    // 省略getter/setter/tostring/构造方法
8}

5. Write the configuration file db.properties to connect to the database in resources

1jdbc.url=jdbc:mysql:///student
2jdbc.user=root
3jdbc.password=root

6. Write dao method

1public class StudentDao {
    
    
2    // 查询所有学生
3    public List<Student> findAll() throws Exception {
    
    
4        // 读取配置文件
5        Properties properties = new Properties();
6        InputStream is = this.getClass().getClassLoader().getResourceAsStream("db.properties");
7        properties.load(is);
8
9        String url = properties.getProperty("jdbc.url");
10        String user = properties.getProperty("jdbc.user");
11        String password = properties.getProperty("jdbc.password");
12
13        // 查询数据库
14        Connection connection = DriverManager.getConnection(url, user, password);
15        Statement statement = connection.createStatement();
16        ResultSet resultSet = statement.executeQuery("select * from student");
17
18        // 处理结果集
19        List<Student> students = new ArrayList();
20        while (resultSet.next()){
    
    
21            int id = resultSet.getInt("id");
22            String name = resultSet.getString("name");
23            String sex = resultSet.getString("sex");
24            String address = resultSet.getString("address");
25            Student student = new Student(id, name, sex, address);
26            students.add(student);
27        }
28
29        // 释放资源
30        resultSet.close();
31        statement.close();
32        connection.close();
33
34        return students;
35    }
36}

7. Test dao method

1public class StudentDaoTest {
    
    
2    // 测试findAll
3    @Test
4    public void testFindAll() throws Exception {
    
    
5        StudentDao studentDao = new StudentDao();
6        List<Student> all = studentDao.findAll();
7        all.forEach(System.out::println);
8    }
9}

3. Build the service module

The content of the service layer is generally written in the service sub-project, and it also needs to inherit the parent project. Since the method of the dao sub-project needs to be called, it is necessary to import the dependencies of the dao sub-project.

1. Create a maven module under the parent project, do not select a template, and select the parent project.

2. Introduce the dependency of the dao subproject in the pom file of the service module.

1<dependencies>
2    <dependency>
3        <groupId>/*同dao工程*/</groupId>
4        <artifactId>/*同dao工程*/</artifactId>
5        <version>1.0-SNAPSHOT</version>
6    </dependency>
7</dependencies>

3. Write the Service method

1public class StudentService {
    
    
2    private StudentDao studentDao = new StudentDao();
3    public List<Student> findAllStudent() throws Exception {
    
    
4        return studentDao.findAll();
5    }
6}

4. Test the service method

1public class StudentServiceTest {
    
    
2    // 测试findAllStudent
3    @Test
4    public void testFindAll() throws Exception {
    
    
5       StudentService studentService = new StudentService();
6        List<Student> allStudent = studentService.findAllStudent();
7        allStudent.forEach(System.out::println);
8    }
9}

4. Build the web module

The content of the controller and the front-end page is generally written in the web sub-project. It is not an ordinary java project, but a web project, which needs to inherit the parent project and import the dependencies of the service sub-project.

1. Create a maven module under the parent project, select the web project template, and select the parent project.

2. After creation, add the parent project, delete the jdk compiled version in the pom file, delete the junit dependency (because there is a response specification in the inherited parent project), and introduce the service dependency.

1<parent>
2    <artifactId>maven_demo2</artifactId>
3    <groupId>/*same*/</groupId>
4    <version>1.0-SNAPSHOT</version>
5</parent>
6
7<properties>
8    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
9    <maven.compiler.source>11</maven.compiler.source>
10    <maven.compiler.target>11</maven.compiler.target>
11</properties>
12
13<dependencies>
14    <dependency>
15        <groupId>/*same*/</groupId>
16        <artifactId>maven_demo2_service</artifactId>
17        <version>1.0-SNAPSHOT</version>
18    </dependency>
19</dependencies>

3. Write the controller

1@WebServlet("/allStudent")
2public class FindAllStudentServlet extends HttpServlet {
    
    
3    @Override
4    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
5        StudentService studentService = new StudentService();
6        List<Student> allStudent = null;
7        try {
    
    
8            allStudent = studentService.findAllStudent();
9        } catch (Exception e) {
    
    
10            e.printStackTrace();
11        }
12        req.setAttribute("allStudent",allStudent);
13        req.getRequestDispatcher("allStudent.jsp").forward(req,resp);
14    }
15}

4. Write JSP pages

1<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
2<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
3<html>
4<head>
5    <title>所有学生</title>
6</head>
7<body>
8<table align="center" border="1" cellspacing="0" cellpadding="0" width="500px">
9    <tr>
10        <th>id</th>
11        <th>姓名</th>
12        <th>性别</th>
13        <th>地址</th>
14    </tr>
15    <c:forEach items="${allStudent}" var="student">
16        <tr>
17            <td>${
    
    student.id}</td>
18            <td>${
    
    student.name}</td>
19            <td>${
    
    student.sex}</td>
20            <td>${
    
    student.address}</td>
21        </tr>
22    </c:forEach>
23</table>
24</body>
25</html>

5. Run the project

There are two ways to run the project:

1. Configure the tomcat plug-in to run the parent project. At this time, the running projects will be aggregated automatically.

Click to configure the tomcat7 plug-in:
insert image description here

Configure as follows:
insert image description here
Click the run arrow to visit http://localhost:8080/allStudent
insert image description here

2. Configure the tomcat plug-in to run the web subproject.

When running the web sub-project, the dependent jar package will be downloaded from the local warehouse, so the dao module and service module must be published to the local warehouse, and we can directly publish the entire project.
insert image description here
Then configure the web project according to the way the tomcat plug-in configures the parent project:
insert image description here

Click the run arrow to visit http://localhost:8080/allStudent

6. Dependency transmission failure and solution

In the previous case, junit is introduced in the parent project, if it is introduced in the dao project, the service project imports the dao project, ie service --> dao --> junit. According to the transitivity of dependencies, service projects can also use junit. But the actual situation is unusable. This is the dependency transitive failure problem.
insert image description here

When Maven defines dependency transfer, some dependency range dependencies cannot be transferred, the table is as follows:
insert image description here

In actual development, there is no need to memorize this form. When the dependency is not delivered, we can directly add the dependency again in this project.

1<dependencies>
2 <dependency>
3     <groupId>/*same*/</groupId>
4     <artifactId>maven_demo2_dao</artifactId>
5     <version>1.0-SNAPSHOT</version>
6 </dependency>
7 <dependency>
8     <groupId>junit</groupId>
9     <artifactId>junit</artifactId>
10     <version>4.12</version>
11     <scope>test</scope>
12 </dependency>
13</dependencies>


Guess you like

Origin blog.csdn.net/TIpotencial/article/details/123761801