• 【SSM】SSM框架整合


    1、SSM框架整合

    Gitee SSM-Template 仓库

    1.1、 环境需求

    • IDEA
    • MySQL 5.7.XX
    • Tomcat 9
    • Maven 3.6

    1.2、SSM 项目基础结构

    image

    1.2.1、Mavem 项目建立

    新建一个普通的Maven项目即可
    image

    1.2.1.1、 项目依赖

    <dependencies>
        <!--  JSON 解析-->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.12.4</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.20</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
            <scope>test</scope>
        </dependency>
    
        <!--  java jsp-->
        <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.1</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
    
        <!--  Mysql-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.7</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.6</version>
        </dependency>
    
        <!--  数据源-->
        <dependency>
            <groupId>com.mchange</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.5.5</version>
        </dependency>
    
        <!-- Spring-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.3.7</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.3.9</version>
        </dependency>
    </dependencies>
    

    1.2.1.2、静态资源导出

    <build>
        <!-- 修改Maven工程的 JDK版本 :1.8 -->
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <target>1.8</target>
                    <source>1.8</source>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
        </plugins>
        <!-- 解决静态资源导出-->
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
        </resources>
    </build>
    

    1.2.1.3、数据库

    CREATE DATABASE `ssmbuild`;
    
    USE `ssmbuild`;
    
    DROP TABLE IF EXISTS `books`;
    
    CREATE TABLE `books` (
      `bookID` INT(10) NOT NULL AUTO_INCREMENT COMMENT '书id',
      `bookName` VARCHAR(100) NOT NULL COMMENT '书名',
      `bookCounts` INT(11) NOT NULL COMMENT '数量',
      `detail` VARCHAR(200) NOT NULL COMMENT '描述',
      KEY `bookID` (`bookID`)
    ) ENGINE=INNODB DEFAULT CHARSET=utf8
    
    INSERT  INTO `books`(`bookID`,`bookName`,`bookCounts`,`detail`)VALUES 
    (1,'Java',1,'从入门到放弃'),
    (2,'MySQL',10,'从删库到跑路'),
    (3,'Linux',5,'从进门到进牢');
    

    1.2.1.4、applicationContet.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"
           xsi:schemaLocation="http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans.xsd">
        <import resource="classpath:spring-dao.xml"/>
        <import resource="classpath:spring-service.xml"/>
        <import resource="classpath:spring-mvc.xml"/>
    </beans>
    

    1.3、Mybatis层

    database.properties

    jdbc.driver=com.mysql.jdbc.Driver
    # 如果使用的 Mysql8.0+,增加时区配置
    jdbc.url=jdbc:mysql://localhost:3306/ssmbuild?useSSL=false&amp;useUnicode=true&amp;characterEncoding=UTF-8
    jdbc.username=root
    jdbc.password=123456
    

    1.3.1、spring-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 https://www.springframework.org/schema/context/spring-context.xsd">
    
        <!-- 关联数据库文件 database -->
        <context:property-placeholder location="classpath:database.properties"/>
    
        <!-- c3p0 连接池-->
        <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
            <property name="driverClass" value="${jdbc.driver}"/>
            <property name="jdbcUrl" value="${jdbc.url}"/>
            <property name="user" value="${jdbc.username}"/>
            <property name="password" value="${jdbc.password}"/>
    
            <!-- c3p0连接池的私有属性 -->
            <property name="maxPoolSize" value="30"/>
            <property name="minPoolSize" value="10"/>
            <!-- 关闭连接后不自动commit -->
            <property name="autoCommitOnClose" value="false"/>
            <!-- 获取连接超时时间 -->
            <property name="checkoutTimeout" value="10000"/>
            <!-- 当获取连接失败重试次数 -->
            <property name="acquireRetryAttempts" value="2"/>
        </bean>
    
        <!-- sqlSessionFactory-->
        <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
            <property name="dataSource" ref="dataSource"/>
            <property name="configLocation" value="classpath:mybatis-config.xml"/>
        </bean>
    
        <!-- 配置 dao 接口扫描包-->
        <bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer" >
            <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
            <property name="basePackage" value="com.xg.mapper"/>
        </bean>
    </beans>
    

    1.3.2、mybatis-config.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="COMMONS_LOGGING"/>
        </settings>
    
        <typeAliases>
            <package name="com.xg.pojo"/>
        </typeAliases>
    
        <mappers>
            <package name="com.xg.mapper"/>
        </mappers>
    </configuration>
    

    1.4、Service层

    1.4.1、spring-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"
           xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
    
        <!--  扫描service包下 注解-->
        <context:component-scan base-package="com.xg.service"/>
        <context:annotation-config/>
    
        <!--  配置 事务-->
        <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
            <!-- 注入 数据源-->
            <property name="dataSource" ref="dataSource"/>
        </bean>
    
        <!-- 将 我们们的所有 业务类注册到spring
            可以通过配置或者, <bean id="" class="">
            注解实现 @Service
        -->
    </beans>
    

    1.5、Web 层

    1.5.1、添加Web框架

    image

    1.5.2、web.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
             version="4.0">
    
        <!--  视图解析器-->
        <servlet>
            <servlet-name>app</servlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
            <init-param>
                <param-name>contextConfigLocation</param-name>
                <!-- 一定要注意 绑定的文件 applicationContext.xml-->
                <param-value>classpath:applicationContext.xml</param-value>
            </init-param>
            <load-on-startup>1</load-on-startup>
        </servlet>
        <servlet-mapping>
            <servlet-name>app</servlet-name>
            <url-pattern>/</url-pattern>
        </servlet-mapping>
    
        <!--字符编码过滤器 -->
        <filter>
            <filter-name>encoding</filter-name>
            <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
            <init-param>
                <param-name>encoding</param-name>
                <param-value>utf-8</param-value>
            </init-param>
        </filter>
        <filter-mapping>
            <filter-name>encoding</filter-name>
            <url-pattern>/*</url-pattern>
        </filter-mapping>
    
        <session-config>
            <!-- session 过期时间-->
            <session-timeout>15</session-timeout>
        </session-config>
    </web-app>
    

    1.5.3、spring-mvc.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 https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">
        <!-- 开启注解支持, 静态资源过滤 -->
        <context:component-scan base-package="com.xg.controller"/>
        <mvc:default-servlet-handler/>
        <mvc:annotation-driven>
            <!--JSON 乱码问题-->
            <mvc:message-converters register-defaults="true">
                <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                    <constructor-arg value="UTF-8"/>
                </bean>
                <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
                    <property name="objectMapper">
                        <bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
                            <property name="failOnEmptyBeans" value="false"/>
                        </bean>
                    </property>
                </bean>
            </mvc:message-converters>
        </mvc:annotation-driven>
    
        <!-- 视图解析器-->
        <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <property name="prefix" value="/WEB-INF/jsp/"/>
            <property name="suffix" value=".jsp"/>
        </bean>
    </beans>
    

    1.6、最后配置

    1.6.1、配置 Tomcat

    image

    1.6.2、添加 lib

    image

    1.6.3、books.jsp

    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
        <title>Title</title>
        <style>
            .table {
                line-height: 1.6;
                font: 14px Helvetica Neue, Helvetica, PingFang SC, Tahoma, Arial, sans-serif;
                -webkit-tap-highlight-color: rgba(0, 0, 0, 0);
                border-collapse: collapse;
                border-spacing: 0;
                margin: 10px 0;
                 30%;
                background-color: #fff;
                color: #666;
            }
            .table th{
                text-align: left;
            }
        </style>
    </head>
    <body>
    <table class="table">
        <thead>
        <tr>
            <th style=" 100px">书籍编号</th>
            <th style=" 180px">书籍名称</th>
            <th style=" 120px">书籍数量</th>
            <th style=" 250px">书籍详情</th>
        </tr>
        </thead>
        <tbody>
        <c:forEach var="book" items="${booksList}">
            <tr>
                <td>${book.bookID}</td>
                <td>${book.bookName}</td>
                <td>${book.bookCounts}</td>
                <td>${book.detail}</td>
            </tr>
        </c:forEach>
        </tbody>
    </table>
    </body>
    </html>
    

    1.6.4、测试 Controller

    BooksController

    package com.xg.controller;
    
    import com.fasterxml.jackson.core.JsonProcessingException;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import com.xg.service.books.BooksServiceImpl;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    import java.util.HashMap;
    
    @RestController
    public class BooksController {
    
        private final ObjectMapper objectMapper = new ObjectMapper();
    
        private final BooksServiceImpl booksService;
    
        public BooksController(BooksServiceImpl booksService) {
            this.booksService = booksService;
        }
    
        @RequestMapping(value = "getBooksListJSON", produces = "application/json")
        public String getBooksListJSON() throws JsonProcessingException {
            return objectMapper.writeValueAsString(booksService.queryBooks());
        }
    
        @RequestMapping(value = "getBooksListJSON02", produces = "application/json")
        public String getBooksListJSON02() throws JsonProcessingException {
            HashMap<String, Object> map = new HashMap<>();
            map.put("booksList", booksService.queryBooks());
            map.put("username", "遇见星光");
            map.put("count", 10);
            map.put("page", 1);
    
            return objectMapper.writeValueAsString(map);
        }
    
    }
    
    > BooksController02
    
    ```java
    
    package com.xg.controller;
    
    import com.xg.pojo.Books;
    import com.xg.service.books.BooksServiceImpl;
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.Model;
    import org.springframework.web.bind.annotation.RequestMapping;
    import java.util.List;
    
    @Controller
    public class BooksController02 {
    
        private final BooksServiceImpl booksService;
    
        public BooksController02(BooksServiceImpl booksService) {
            this.booksService = booksService;
        }
    
        @RequestMapping("/allBooks")
        public String queryBooksList(Model model) {
            List<Books> booksList = booksService.queryBooks();
            model.addAttribute("booksList", booksList);
    
            return "books";
        }
    }
    

    1.6.3.1、结果

    http://localhost:8080/ssm_01/getBooksListJSON

    image

    http://localhost:8080/ssm_01/getBooksListJSON02

    image

    http://localhost:8080/ssm_01/allBooks

    image

    1.7、排错思路

    1.7.1、问题 :bean不存在

    步骤:

    1. 查看这个bean注入是否成功

    2. Junit单元测试,看我们的代码是否可以查询出结果

    3. 问题,一定出在底层,是spring出了问题

    4. springMVC,整合的时候没有调用到我们的service层的bean

      1. applioncationContext.xml 没有注入bean

      2. web.xml 中,我们也绑过配置文件! ,发现问题我们配置的是 spring-MVC.xml

        这里面确实没有 service bean ,所以空指针异常

  • 相关阅读:
    C# 1.0 到 C# 3.0 委托创建过程的发展
    C#禁用窗体最大化按钮
    TeamViewer 通过Internet进行远程访问和远程支持
    c# 匿名方法
    BeginInvoke会重新开一个线程
    c# 线程调用带参数的函数
    c# msdn 委托
    判断某张表是否存在在数据库中(access 2003 与sql server 2008)
    新浪微博自动发送微博 功能已实现(net)
    validateRequest="false" 在asp.net 4.0中失效的解决办法
  • 原文地址:https://www.cnblogs.com/Right-A/p/15103783.html
Copyright © 2020-2023  润新知