Maven aggregation development [example detailed explanation --- 5555 words]

Table of contents

1. Maven aggregate development_inheritance relationship

Two, Maven aggregation case

1. Build dao module

2. Build the service module  

3. Build the web module 

4. Run the project


1. Maven aggregate development_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 that the parent project type must be 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 in <dependencyManagement> .

It is written as follows:

Two, Maven aggregation case

1. Build dao module

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

Create a maven module under the parent project , do not select a template , and be sure to select the parent project when creating it.

The parent project is written in the pom file of the submodule to prove that the inheritance is successful. As shown below:

prepare database 

//新建数据库
CREATE DATABASE student;

//建表
CREATE TABLE student(
  id int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
  name varchar(255) DEFAULT NULL,
  sex varchar(10) DEFAULT NULL,
  address varchar(255) DEFAULT NULL 
)ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT
CHARSET=utf8

//插入数据
insert into student values(1,'几何心凉','男','北京');
insert into student values(2,'哈士奇','女','上海');

Write entity class Student

package com.mavenstudy.pojo;

public class Student {
    private int id;
    private String name;
    private String sex;
    private String address;

    public Student(){

    }

    public Student(int id, String name, String sex, String address) {
        this.id = id;
        this.name = name;
        this.sex = sex;
        this.address = address;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @Override
    public String toString() {
        return "Student [" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", sex='" + sex + '\'' +
                ", address='" + address + '\'' +
                ']';
    }
}

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

Write dao class and corresponding method

package com.mavenstudy.dao;

import com.mavenstudy.pojo.Student;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

public class StudentDao {
    //查询所有学生
    public List<Student> findAll() throws Exception{
        //读取配置文件
        Properties properties = new Properties();
        InputStream is = this.getClass().getClassLoader().getResourceAsStream("db.properties");
        properties.load(is);

        String url = properties.getProperty("jdbc.url");
        String user = properties.getProperty("jdbc.user");
        String password = properties.getProperty("jdbc.password");

        //查询数据库
        Connection connection = DriverManager.getConnection(url,user,password);
        Statement statement = connection.createStatement();
        ResultSet resultSet = statement.executeQuery("select * from student");

        //处理结果集
        List<Student> students = new ArrayList<>();
        while(resultSet.next()){
            int id = resultSet.getInt(1);
            String name = resultSet.getString(2);
            String sex = resultSet.getString(3);
            String address = resultSet.getString(4);

            Student student = new Student(id,name,sex,address);
            students.add(student);
        }

        //释放资源
        resultSet.close();
        statement.close();
        connection.close();

        return students;
    }
}

Test the dao method Here we can use the Junit annotation to help us test

Now let's run it to see if it can actually be executed!

OK!, there is indeed no problem, then let's build the service module

2. 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 it needs to call the method of the dao sub-project, it needs to import the dependencies of the dao sub-project.

Create a maven module under the parent project , do not select a template, and select the parent project. (This is the same as above, no screenshots)

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

<dependencies>
        <dependency>
            <groupId>com.mavenstudy</groupId>
            <artifactId>maven_demo2_dao</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
</dependencies>

Write the Service class and the corresponding method

package com.mavenstudy.service;

import com.mavenstudy.dao.StudentDao;
import com.mavenstudy.pojo.Student;

import java.util.List;

public class StudentService {
    private StudentDao studentDao = new StudentDao();

    public List<Student> findAllStudent() throws Exception{
        return studentDao.findAll();
    }
}

Write test service method

package com.mavenstudy.service;

import com.mavenstudy.pojo.Student;
import org.junit.Test;

import java.util.List;

public class StudentServiceTest {
    //测试findAllStudent
    @Test
    public void findAllStudentTest() throws Exception {
        StudentService studentService = new StudentService();
        List<Student> students = studentService.findAllStudent();
        students.forEach(System.out::println);
    }
}

Test Results

OK! The result is still the same as we expected, let's build the web module next!

3. 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.

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

After creation, add the parent project, delete the jdk compiled version in the pom file, delete the junit dependency, and introduce the service dependency.

<dependencies>
    <dependency>
      <groupId>com.mavenstudy</groupId>
      <artifactId>maven_demo2_service</artifactId>
      <version>1.0-SNAPSHOT</version>
    </dependency>
</dependencies>

Write the controller, FindAllStudentServlet class

package com.mavenstudy.servlet;

import com.mavenstudy.pojo.Student;
import com.mavenstudy.service.StudentService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/allStudent")
public class FindAllStudentServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        StudentService studentService = new StudentService();
        List<Student> students = null;
        try {
            students = studentService.findAllStudent();
        } catch (Exception e) {
            e.printStackTrace();
        }

        req.setAttribute("students",students);

        req.getRequestDispatcher("allStudent.jsp").forward(req,resp);
    }
}

Write JSP pages, in which we need to use EL expressions, but maven does not recognize EL expressions by default, so we need to add an attribute   isELIgnored="false" and an import

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

jsp page displaying all student information

<%@ page contentType="text/html;charset=UTF-8" language="java"
    isELIgnored="false"  %>
<%@taglib prefix="c"
  uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>
      全部学生
    </title>
</head>
<body>
  <table align="center" border="1" cellspacing="0" cellpadding="0" width="500px">
    <tr>
      <th>id</th>
      <th>姓名</th>
      <th>性别</th>
      <th>地址</th>
    </tr>
    <c:forEach items="${students}" var="student">
      <tr>
        <td>${student.id}</td>
        <td>${student.name}</td>
        <td>${student.sex}</td>
        <td>${student.address}</td>
      </tr>
    </c:forEach>
  </table>
</body>
</html>

4.  Run the project

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

 Click to configure the tomcat7 plug-in 

OK! After configuration, click the run button, and the following is the result of the operation

Guess you like

Origin blog.csdn.net/qq_53317005/article/details/129187397