• 【Java】Maven模块化工程SSM整合


    创建数据库一个演示表User

    CREATE TABLE `user` (
      `id` int NOT NULL AUTO_INCREMENT,
      `name` varchar(64) DEFAULT NULL,
      `password` varchar(64) DEFAULT NULL,
      `status` int DEFAULT '0',
      `is_del` int DEFAULT '0',
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai

    插入数据:

    insert  into 
        `user`(`id`,`name`,`password`,`status`,`is_del`) 
    values 
    (1,'admin','admin',0,0),
    (2,'user01','123456',0,0),
    (3,'user02','123456',0,0),
    (4,'user03','123456',0,0),
    (5,'user04','123456',0,0),
    (6,'user05','123456',0,0);

    创建新的Maven工程,不点选任何骨架:

    模块化工程,每一个结构层即一个模块,而现在这个工程的SRC可以删除:

    创建最基本的三层结构:

    Dao、Service、Controller

    Dao和Service无骨架创建,但是控制器是视图层了,需要Web骨架搭建

    构建完成发现Controller模块webapp没有被IDEA表示:

    查看控制台发现:

    No archetype found in remote catalog. Defaulting to internal catalog

    远程骨架仓库未找到,调用的本地的

    添加web:

    选择控制器:

    可以发现Maven指定web目录位置不存在,固然没有标记:

    更改目录:

    就有了:

    设置Tomcat:

    修复配置的工程:

    启动测试:


    所有依赖:

      <properties>
            <spring.version>5.2.8.RELEASE</spring.version>
        </properties>
    
        <dependencies>
    
            <dependency>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
                <version>1.18.12</version>
            </dependency>
    
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>4.13</version>
                <scope>test</scope>
            </dependency>
    
            <!-- JDBC & DataSource -->
    
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>8.0.20</version>
            </dependency>
    
            <dependency>
                <groupId>com.zaxxer</groupId>
                <artifactId>HikariCP</artifactId>
                <version>3.4.5</version>
            </dependency>
    
            <!-- log -->
    
            <dependency>
                <groupId>log4j</groupId>
                <artifactId>log4j</artifactId>
                <version>1.2.17</version>
            </dependency>
    
            <dependency>
                <groupId>org.slf4j</groupId>
                <artifactId>slf4j-log4j12</artifactId>
                <version>1.7.30</version>
            </dependency>
    
            <!-- JavaWeb -->
            <dependency>
                <groupId>javax.servlet</groupId>
                <artifactId>servlet-api</artifactId>
                <version>2.5</version>
            </dependency>
    
            <dependency>
                <groupId>javax.servlet.jsp</groupId>
                <artifactId>jsp-api</artifactId>
                <version>2.2</version>
            </dependency>
    
            <dependency>
                <groupId>javax.servlet</groupId>
                <artifactId>jstl</artifactId>
                <version>1.2</version>
            </dependency>
    
            <dependency>
                <groupId>org.apache.taglibs</groupId>
                <artifactId>taglibs-standard-impl</artifactId>
                <version>1.2.5</version>
            </dependency>
    
            <dependency>
                <groupId>org.apache.taglibs</groupId>
                <artifactId>taglibs-standard-impl</artifactId>
                <version>1.2.5</version>
            </dependency>
    
            <!-- Mybatis -->
    
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis</artifactId>
                <version>3.5.5</version>
            </dependency>
    
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis-spring</artifactId>
                <version>2.0.5</version>
            </dependency>
    
            <!-- Spring & SpringMVC ... -->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-webmvc</artifactId>
                <version>${spring.version}</version>
            </dependency>
    
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-jdbc</artifactId>
                <version>${spring.version}</version>
            </dependency>
    
            <dependency>
                <groupId>org.aspectj</groupId>
                <artifactId>aspectjweaver</artifactId>
                <version>1.9.6</version>
            </dependency>
    
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-test</artifactId>
                <version>${spring.version}</version>
            </dependency>
    
        </dependencies>

    公共依赖,实际上也可以具体的根绝结构层来区分导入,不过太麻烦,省事就直接丢总工程的POM里面

    Mybatis-Spring整合:

    创建User实体类:

    package cn.echo42.pojo;
    
    import lombok.AllArgsConstructor;
    import lombok.Data;
    import lombok.NoArgsConstructor;
    
    /**
     * @author DaiZhiZhou
     * @file SSM-ModuleVersion-Sample
     * @create 2020-08-08 9:16
     */
    
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public class User {
        private Integer id;
        private String name;
        private String password;
        private Integer status;
        private Integer is_del;
    }

    创建UserMapper接口

    package cn.echo42.mapper;
    
    import cn.echo42.pojo.User;
    
    import java.util.List;
    
    /**
     * @author DaiZhiZhou
     * @file SSM-ModuleVersion-Sample
     * @create 2020-08-08 9:20
     */
    public interface UserMapper {
        List<User> queryUserList();
    }

    先创建mybatis配置和userMapper映射器配置:

    下面Spring容器XML配置后面在设置,这里还忘了DB连接配置和日志配置

    Mybatis-Configuration.xml

    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE configuration
            PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-config.dtd">
    <configuration>
    
        <settings>
            <setting name="logImpl" value="LOG4J"/>
        </settings>
    
    </configuration>

    仅留下日志配置选项,其他配置移交到Spring管理:

    UserMapper.xml

    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE mapper
            PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    <mapper namespace="cn.echo42.mapper.UserMapper">
    
        <select id="queryUserList" resultType="cn.echo42.pojo.User">
            SELECT * FROM user;
        </select>
    
    </mapper>

    补加日志和数据库连接:

    db.properties

    jdbc.driverClassName=com.mysql.cj.jdbc.Driver
    jdbc.url=jdbc:mysql://localhost:3306/sample?serverTimezone=GMT
    jdbc.username=root
    jdbc.password=123456

    log4j.properties

    # Global logging configuration
    log4j.rootLogger=DEBUG, stdout
    # MyBatis logging configuration...
    log4j.logger.org.mybatis.example.BlogMapper=TRACE
    # Console output...
    log4j.appender.stdout=org.apache.log4j.ConsoleAppender
    log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
    log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

    Application-Dao.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
    
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns:context="http://www.springframework.org/schema/context"
    
           xsi:schemaLocation="
           http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans.xsd
    
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context.xsd
    "
    >
    
        <context:component-scan base-package="cn.echo42.mapper"/> <!-- Spring注册扫描 -->
        
        <context:property-placeholder location="classpath:db.properties"/> <!-- jdbc连接配置读取加载 -->
    
        <!-- Spring 数据源配置 SpringJDBC的数据源 -->
    <!--    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource" >-->
    <!--        <property name="driverClassName" value="${jdbc.driverClassName}" />-->
    <!--        <property name="url" value="${jdbc.url}" />-->
    <!--        <property name="username" value="${jdbc.username}" />-->
    <!--        <property name="password" value="${jdbc.password}" />-->
    <!--    </bean>-->
        
        <!-- Hikari数据源 -->
        <bean id="dataSource" class="com.zaxxer.hikari.HikariDataSource" destroy-method="close" >
            <property name="driverClassName" value="${jdbc.driverClassName}" />
            <property name="jdbcUrl" value="${jdbc.url}" />
            <property name="username" value="${jdbc.username}" />
            <property name="password" value="${jdbc.password}" />
        </bean>
        
        <!-- 配置SqlSessionFactory对象 -->
        <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    
            <!-- 注入数据库连接池 -->
            <property name="dataSource" ref="dataSource"/>
    
            <!--  自动扫描mappers.xml文件  -->
            <property name="mapperLocations" value="classpath:mybatis/mapper/*.xml"/>
            <property name="configLocation" value="classpath:mybatis/Mybatis-Configuration.xml"/>
        </bean>
    
        <!-- DAO接口所在包名,Spring会自动查找其下的类 -->
        <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
            <property name="basePackage" value="cn.echo42.mapper" />
            <!--<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>-->
        </bean>
    
    </beans>

    写一个测试类看看是否正常:

    import cn.echo42.mapper.UserMapper;
    import cn.echo42.pojo.User;
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.test.context.ContextConfiguration;
    import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
    
    /**
     * @author DaiZhiZhou
     * @file SSM-ModuleVersion-Sample
     * @create 2020-08-08 9:37
     */
    
    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(locations = "classpath:Application-Dao.xml")
    public class DaoTest {
    
        @Autowired
        UserMapper userMapper;
    
        @Test
        public void testSample() {
            for (User user : userMapper.queryUserList()) {
                System.out.println(user);
            }
        }
    }

    结果:

    log4j:WARN No appenders could be found for logger (org.springframework.test.context.junit4.SpringJUnit4ClassRunner).
    log4j:WARN Please initialize the log4j system properly.
    log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
    User(id=1, name=admin, password=admin, status=0, is_del=0)
    User(id=2, name=user01, password=123456, status=0, is_del=0)
    User(id=3, name=user02, password=123456, status=0, is_del=0)
    User(id=4, name=user03, password=123456, status=0, is_del=0)
    User(id=5, name=user04, password=123456, status=0, is_del=0)
    User(id=6, name=user05, password=123456, status=0, is_del=0)
    
    Process finished with exit code 0

    日志没有配置到?【才发现少写了j...】

    可以了:

    INFO [main] - HikariPool-1 - Starting...
    DEBUG [main] - HikariPool-1 - Added connection com.mysql.cj.jdbc.ConnectionImpl@59252cb6
     INFO [main] - HikariPool-1 - Start completed.
    DEBUG [main] - JDBC Connection [HikariProxyConnection@1643141512 wrapping com.mysql.cj.jdbc.ConnectionImpl@59252cb6] will not be managed by Spring
    DEBUG [main] - ==>  Preparing: SELECT * FROM user;
    DEBUG [main] - ==> Parameters: 
    DEBUG [main] - <==      Total: 6
    DEBUG [HikariPool-1 housekeeper] - HikariPool-1 - Pool stats (total=1, active=1, idle=0, waiting=0)
    DEBUG [main] - Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@194fad1]
    User(id=1, name=admin, password=admin, status=0, is_del=0)
    User(id=2, name=user01, password=123456, status=0, is_del=0)
    User(id=3, name=user02, password=123456, status=0, is_del=0)
    User(id=4, name=user03, password=123456, status=0, is_del=0)
    User(id=5, name=user04, password=123456, status=0, is_del=0)
    User(id=6, name=user05, password=123456, status=0, is_del=0)

    结合Service业务层:

    首先在业务层的Pom.xml中导入Dao层:

    这样来自dao层的userMapper就可以被service层调用

        <dependencies>
            <dependency>
                <groupId>cn.echo42</groupId>
                <artifactId>Application-Dao</artifactId>
                <version>1.0-SNAPSHOT</version>
            </dependency>
        </dependencies>

    编写接口和实现类:

    UserService接口:

    package cn.echo42.service;
    
    import cn.echo42.pojo.User;
    
    import java.util.List;
    
    /**
     * @author DaiZhiZhou
     * @file SSM
     * @create 2020-08-07 14:21
     */
    public interface UserService {
        List<User> getUserList();
    }

    UserServiceImpl接口实现:

    package cn.echo42.service.impl;
    
    import cn.echo42.mapper.UserMapper;
    import cn.echo42.pojo.User;
    import cn.echo42.service.UserService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    
    import java.util.List;
    
    /**
     * @author DaiZhiZhou
     * @file SSM-ModuleVersion-Sample
     * @create 2020-08-08 9:51
     */
    
    @Service("userService")
    public class UserServiceImpl implements UserService {
    
        @Autowired
        UserMapper userMapper;
    
        public List<User> getUserList() {
            return userMapper.queryUserList();
        }
    }

    业务层的配置主要是扫描包,和事务配置,这里就不编写事务配置了

    Application-Service.xml:

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
    
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns:context="http://www.springframework.org/schema/context"
           xmlns:aop="http://www.springframework.org/schema/aop"
           xmlns:mvc="http://www.springframework.org/schema/mvc"
           xmlns:p="http://www.springframework.org/schema/p"
           xmlns:c="http://www.springframework.org/schema/c"
    
           xsi:schemaLocation="
           http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans.xsd
    
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context.xsd
    
           http://www.springframework.org/schema/aop
           http://www.springframework.org/schema/aop/spring-aop.xsd
    
           http://www.springframework.org/schema/mvc
           http://www.springframework.org/schema/mvc/spring-mvc.xsd
    "
    >
    
        <context:component-scan base-package="cn.echo42.service" />
    
    </beans>

    业务层测试类

    注意我们的容器配置导入,是两个,一个dao一个Service,或者也可以使用import标签和并

    import cn.echo42.pojo.User;
    import cn.echo42.service.UserService;
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.test.context.ContextConfiguration;
    import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
    
    /**
     * @author DaiZhiZhou
     * @file SSM-ModuleVersion-Sample
     * @create 2020-08-08 9:56
     */
    
    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(locations = {"classpath:Application-Dao.xml", "classpath:Application-Service.xml"})
    public class ServiceTest {
    
        @Autowired
        UserService userService;
    
        @Test
        public void testSample() {
            for (User user : userService.getUserList()) System.out.println(user);
        }
    }

    测试结果正常输出:

     INFO [main] - HikariPool-1 - Starting...
    DEBUG [main] - HikariPool-1 - Added connection com.mysql.cj.jdbc.ConnectionImpl@753432a2
     INFO [main] - HikariPool-1 - Start completed.
    DEBUG [main] - JDBC Connection [HikariProxyConnection@923083575 wrapping com.mysql.cj.jdbc.ConnectionImpl@753432a2] will not be managed by Spring
    DEBUG [main] - ==>  Preparing: SELECT * FROM user;
    DEBUG [main] - ==> Parameters: 
    DEBUG [main] - <==      Total: 6
    DEBUG [HikariPool-1 housekeeper] - HikariPool-1 - Pool stats (total=1, active=1, idle=0, waiting=0)
    DEBUG [main] - Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@2f953efd]
    User(id=1, name=admin, password=admin, status=0, is_del=0)
    User(id=2, name=user01, password=123456, status=0, is_del=0)
    User(id=3, name=user02, password=123456, status=0, is_del=0)
    User(id=4, name=user03, password=123456, status=0, is_del=0)
    User(id=5, name=user04, password=123456, status=0, is_del=0)
    User(id=6, name=user05, password=123456, status=0, is_del=0)

    SpringMVC整合:

    首先由Maven骨架创建Web工程没有提供源码和资源两个目录:

    我们需要手动创建:

    导入上一级Service业务层:

        <dependencies>
            <dependency>
                <groupId>cn.echo42</groupId>
                <artifactId>Application-Service</artifactId>
                <version>1.0-SNAPSHOT</version>
            </dependency>
        </dependencies>

    Application-Controller.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns:context="http://www.springframework.org/schema/context"
           xmlns:mvc="http://www.springframework.org/schema/mvc"
    
           xsi:schemaLocation="
           http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans.xsd
    
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context.xsd
    
           http://www.springframework.org/schema/mvc
           http://www.springframework.org/schema/mvc/spring-mvc.xsd
    "
    >
    
        <context:component-scan base-package="cn.echo42.controller" /> <!-- 控制器注册扫描 -->
    
        <mvc:default-servlet-handler/> <!-- 静态资源过滤器 -->
    
        <mvc:annotation-driven /> <!-- 注解驱动 -->
    
        <!-- 视图解析器 -->
        <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <!-- 前缀,这里是请求的路径文件 -->
            <property name="prefix" value="/WEB-INF/view/" />
            <!-- 后缀 ,支持.jsp的请求-->
            <property name="suffix" value=".jsp" />
        </bean>
        
        <import resource="Application-Dao.xml"/> <!-- 合并导入前2层的容器XML配置 -->
        <import resource="Application-Service.xml"/>
    
    </beans>

    Web.xml配置

    导入Controller.xml用以加载

    <!DOCTYPE web-app PUBLIC
     "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
     "http://java.sun.com/dtd/web-app_2_3.dtd" >
    
    <web-app>
      <display-name>Archetype Created Web Application</display-name>
    
      <servlet>
        <servlet-name>dispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
          <param-name>contextConfigLocation</param-name>
          <param-value>classpath:Application-Controller.xml</param-value>
        </init-param>
      </servlet>
      
      <servlet-mapping>
        <servlet-name>dispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
      </servlet-mapping>
      
    </web-app>

    UserController编写:

    package cn.echo42.controller;
    
    import cn.echo42.service.UserService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RequestMapping;
    
    import java.util.Map;
    
    /**
     * @author DaiZhiZhou
     * @file SSM-ModuleVersion-Sample
     * @create 2020-08-08 10:02
     */
    
    @Controller
    @RequestMapping("/user")
    public class UserController {
    
        @Autowired
        UserService userService;
    
        @GetMapping("/list")
        public String toUserListPage(Map<String,Object> map) {
            map.put("message", "Hello SSM module Sample!!!");
            map.put("userList", userService.getUserList());
            return "user/list";
        }
    
    }

    编写页面:

    jsp代码:list.jsp

    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    <%--
      Created by IntelliJ IDEA.
      User: User-Dai
      Date: 2020/8/8
      Time: 10:12
      To change this template use File | Settings | File Templates.
    --%>
    <%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
    <html>
    <head>
        <title>用户列表</title>
    </head>
    <body>
    
    <table width="100%" border="1px">
    
        <caption><h3>${message}</h3></caption>
    
        <thead>
            <tr>
                <th>编号</th>
                <th>名称</th>
                <th>密码</th>
                <th>状态</th>
                <th>标记删除</th>
            </tr>
        </thead>
    
        <tbody>
            <c:forEach items="${userList}" var="user">
                <tr>
                    <td>${user.id}</td>
                    <td>${user.name}</td>
                    <td>${user.password}</td>
                    <td>${user.status}</td>
                    <td>${user.is_del}</td>
                </tr>
            </c:forEach>
        </tbody>
    
    </table>
    
    </body>
    </html>

    访问:

    http://localhost:8080/user/list

  • 相关阅读:
    HTML5之标签
    Linux常用命令(二十四)
    Linux常用命令(二十三)
    Python 定位excel表格的最后一个单元格的位置
    tornado学习
    Linux一些基础命令
    用python打造自己的SDK--使用setuptools打包安装
    Centos开放指定端口命令
    python sqlalchemy基本使用
    python rpc
  • 原文地址:https://www.cnblogs.com/mindzone/p/13456288.html
Copyright © 2020-2023  润新知