SSM Integration (Super detailed)

This is the 28th day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021

We integrate SSM and implement a function to query the blogs in the database and display them on the page.

A, tools,

  • idea
  • MySQL 8.0.22
  • Tomcat 9

Project Structure:

2. Database preparation

  1. Create a database table to hold your blog and insert some data
create table blog(
	id int primary key comment 'blog id',
	title varchar(100) not null comment 'Blog title',
	author varchar(30) not null comment 'Blogger',
	create_time varchar(50) not null comment 'Creation time',
	views int(30) not null comment 'Views'
) 

insert into blog values(1.'javaWeb tutorial'.'Dark Horse Programmer',now(),1000) 
insert into blog values(2.'Android Software Development'.'Zhou Shikai, Chen Xiaolong',now(),1000) 
insert into blog values(3.'Data structure'.Tsinghua University Press,now(),10000) 
insert into blog values(4.'Humanities Foundation and Application'.'MAO Can moon',now(),560)
insert into blog values(5.'the Java tutorial'.'money',now(),123456)
insert into blog values(6.'C'.'Tam Ho Keung',now(),10000)
insert into blog values(7.'C'.'xiaomao',now(),10000)
Copy the code

3. Basic environment construction

1. Create a New Maven project and add Web support

Import the dependencies we need to use in pom.xml

Connections could not be acquired from the underlying database!

 <dependencies>
        <! -- Database driver -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.22</version>
        </dependency>
        <! -- Database connection pool -->
        <dependency>
            <groupId>com.mchange</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.5.2</version>
        </dependency>
        <! -- junit-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13</version>
        </dependency>
        <! -- Servlet - 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.2</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <! --mybatis-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.1 track of</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.1</version>
        </dependency>

        <! --spring-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.2.0. RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.1.8. RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.12</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>RELEASE</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>RELEASE</version>
            <scope>compile</scope>
        </dependency>
    </dependencies>
Copy the code

3. Add Maven resource filtering in pom. XML to prevent resource export failures

 <build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
        </resources>
    </build>
Copy the code

4. Build the infrastructure and configuration framework!

  • com.mq.controller
  • com.mq.dao
  • com.mq.pojo
  • com.mq.service
  • mybatis-config.xml

      
<! DOCTYPEconfiguration
        PUBLIC "- / / mybatis.org//DTD Config / 3.0 / EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<! -- Configuration Core configuration file -->
<configuration>
    
  
</configuration>

Copy the code
  • applicationContext.xml

      
<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 https://www.springframework.org/schema/mvc/spring-mvc.xsd">

</beans>
Copy the code

4. MyBatis layer compilation

1. Database configuration file database.properties

Note: Database connections may encounter driver issues, SSL secure access issues, and time zone issues. ServerTimezone =GMT%2B8 for MySQL 8.0 or later

Driver of a later version has changed from com.mysql.jdbc.driver to com.mysql.cj.jdbc.driver.

Error 500 Failed to obtain JDBC Connection; nested exception is java.sql.SQLException: Connections could not be acquired from the underlying database!

jdbc.driver=com.mysql.cj.jdbc.Driver
# mysql 8.0Jdbc. url= JDBC :mysql://localhost:3306/firend_mq? useSSL=false&useUnicode=&characterEncodeing=UTF-8&serverTimezone=GMT%2B8
jdbc.username=root
jdbc.password=root
Copy the code

2. Connect to the database using IDEA

If the connection fails, check whether the time zone is not configured.

3. Write entity classes

Create the Blog entity class under the POJO package and import the dependencies using the Lombok plug-in.

package com.mq.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Blog {
    private int id;
    private String title;
    private String author;
    private String create_time;
    private int views;
}

Copy the code

4. Write DAO layer interface and mapper.xml

If you’re just integrating, you don’t have to write interfaces, so I’m just testing.

  1. Create the BlogMapper interface under the DAO package
package com.mq.dao;

import com.mq.pojo.Blog;

import java.util.List;

public interface BlogMapper {

    // Query all blogs
    List<Blog> queryAllBLog(a);
}

Copy the code
  1. Write mapper.xml file corresponding to BlogMapper

      
<! DOCTYPEmapper
        PUBLIC "- / / mybatis.org//DTD Mapper / 3.0 / EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<! Namespace: bind Dao/Mapper interface -->
<mapper namespace="com.mq.dao.BlogMapper">
<! -- Query all blogs -->
        <select id="queryAllBLog" resultType="Blog">
                select * from firend_mq.blog
        </select>
</mapper>
Copy the code

5. Write the core configuration file of MyBatis

We leave it to Spring to configure the data source.

Mybatis configuration details can see Mybatis configuration details


      
<! DOCTYPEconfiguration
        PUBLIC "- / / mybatis.org//DTD Config / 3.0 / EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<! -- Configuration Core configuration file -->
<configuration>

    <! Configure the data source and let Spring do it.

<! -- Scan poJO package for entity class and select alias -->
    <typeAliases>
        <package name="com.mq.pojo"/>
    </typeAliases>

<! - registered mapper -- -- >
    <mappers>
        <mapper class="com.mq.dao.BlogMapper"/>
    </mappers>
</configuration>
Copy the code

6. Write interfaces and implementation classes for the Service layer

Interface:

package com.mq.service;

import com.mq.pojo.Blog;

import java.util.List;

public interface BlogService {
    // Query all blogs
    List<Blog> queryAllBLog(a);
}

Copy the code

Implementation class:

package com.mq.service;

import com.mq.dao.BlogMapper;
import com.mq.pojo.Blog;

import java.util.List;

public class BlogServiceImpl implements BlogService{

    // Call the DAO layer to set up a set interface for Spring management
    private BlogMapper blogMapper;

    public BlogServiceImpl(BlogMapper blogMapper) {
        this.blogMapper = blogMapper;
    }

    
    @Override
    public List<Blog> queryAllBLog(a) {
        return blogMapper.queryAllBLog();
    }

    public void setBlogMapper(BlogMapper blogMapper) {}}Copy the code

Fifth, Spring layer writing

Here we split the Spring authoring into three configuration authoring, each of which is equivalent to integrating two. Easy to understand.

1.spring-dao.xml

Spring integrates the relevant configuration file of Mybatis, which is mainly the work that we need to configure the data source in Mybatis -config. XML, now Spring does it, and obtains the SqlSessionFactory object and so on. The code is commented in detail.


      
<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 https://www.springframework.org/schema/mvc/spring-mvc.xsd">
    
    <! -- 1. Associate database files -->
    <context:property-placeholder location="classpath:database.properties"/>

    <! -- 2. Database connection pool -->
    <! C3p0 automatic operation (automatically load configuration files and set them to objects) -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <! -- Set connection pool properties -->
        <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 connection pool private property -->
        <property name="maxPoolSize" value="30"/>
        <property name="minPoolSize" value="10"/>
        <! -->
        <property name="autoCommitOnClose" value="false"/>
        <! Get connection timeout time -->
        <property name="checkoutTimeout" value="10000"/>
        <! Retry times -->
        <property name="acquireRetryAttempts" value="2"/>
    </bean>

    <! SqlSessionFactory = SqlSessionFactory
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <! Insert into database pool -->
        <property name="dataSource" ref="dataSource"/>
        <! Mybatis -config.xml -->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
    </bean>
    <! -- configure the Dao interface package to dynamically inject Dao interface into spring container -->
    <! - explanation: https://www.cnblogs.com/jpfss/p/7799806.html-- >
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <! SqlSessionFactory -->
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
        <! The Dao interface package needs to be scanned
        <property name="basePackage" value="com.mq.dao"/>
    </bean>
</beans>
Copy the code

2. spring-service.xml

Write dependency injection for Spring Ioc


      
<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 https://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <! -- Scan service related beans -->
    <context:component-scan base-package="com.mq.service" />

    <! BlogServiceImpl injected into IOC container -->
    <bean id="BlogServiceImpl" class="com.mq.service.BlogServiceImpl">
        <property name="blogMapper" ref="blogMapper"/>
    </bean>
    <! -- Configure transaction manager -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <! Insert into database pool -->
    <property name="dataSource" ref="dataSource" />
    </bean>
</beans>
Copy the code

Vi. SpringMVC layer writing

1. spring-mvc.xml

Main write registry view parser: InternalResourceViewResolver annotation driven.


      
<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 https://www.springframework.org/schema/mvc/spring-mvc.xsd">

<! -- Annotation driven -->
    <mvc:annotation-driven/>
<! Static resource filtering -->
    <mvc:default-servlet-handler/>
<! -- Scan package -->
    <context:component-scan base-package="com.mq.controller"/>

<! -- View resolver -->
    <! -- Configure the JSP to display the ViewResolver -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>
Copy the code

2. Write the applicationContext. XML


      
<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 https://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <import resource="spring-mvc.xml"/>
    <import resource="spring-dao.xml"/>
    <import resource="spring-service.xml"/>
</beans>
Copy the code

3. web.xml


      
<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">
    <! --DispatcherServlet-->
    <servlet>
        <servlet-name>DispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <! Note: we are loading the total configuration file here, which was corrupted before! -->
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:applicationContext.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>DispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <! --encodingFilter -->
    <filter>
        <filter-name>encodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encodeing</param-name>
            <param-value>utf-8</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/ *</url-pattern>
    </filter-mapping>

    <! -- Session expiration time -->
    <session-config>
        <session-timeout>15</session-timeout>
    </session-config>
</web-app>
Copy the code

At this point our integration is over!

So let’s test that out

Seven, test,

1. Create a BlogController class test in Controller

package com.mq.controller;

import com.mq.pojo.Blog;
import com.mq.service.BlogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@Controller
@RequestMapping("/blog")
public class BlogController {

    @Autowired
    @Qualifier("BlogServiceImpl")
    private BlogService service;

    @RequestMapping("/allblog")
    public String alllist(Model model){
        List<Blog> blogs = service.queryAllBLog();
        model.addAttribute("blog",blogs);
        return "allblog"; }}Copy the code

2. Write the view layer

index.jsp

<%--
  Created by IntelliJ IDEA.
  User: hp
  Date: 2021/5/21
  Time: 13:18
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html; charset=UTF-8" language="java" %>
<html>
  <head>
    <title>$Title$</title>
    <style type="text/css">
      a {
        text-decoration: none;
     color: black;
        font-size: 18px;
      }
      h3 {
        width: 180px;
        height: 38px;
        margin: 100px auto;
        text-align: center;
        line-height: 38px;
       background: deepskyblue;
        border-radius: 4px;
        }
      </style>
  </head>
  <body>
  <h3>
    <a href="${pageContext.request.contextPath}/blog/allblog"> Enter the blog page </a> </h3> </body> </ HTML >Copy the code

allblog.jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--
  Created by IntelliJ IDEA.
  User: hp
  Date: 2021/5/21
  Time: 14:28
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html; charset=UTF-8" language="java"%> <html> <head> <! Bootstrap --> <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"> <title> Blog display </title> </head> <body> <divclass="container">
    <div class="row clearfix">
        <div class="col-md-12 column">
            <div class="page-header"List > < h1 > < small > blog < / small > < / h1 > < / div > < / div > < / div > < divclass="row clearfix">
        <div class="col-md-12 column">
            <table class="table table-hover table-striped"> < thead > < tr > < th > blog number < / th > < th > blog title < / th > < th > blogger < / th > < th > blog creation time < / th > < th > blog traffic < / th > < / tr > < thead > < tbody > <c:forEachvar="blog" items="${blog}">
                        <tr>
                            <td>${blog.id}</td>
                            <td>${blog.title}</td>
                            <td>${blog.author}</td>
                            <td>${blog.create_time}</td>
                            <td>${blog.views}</td>
                        </tr>
                    </c:forEach>
                </tbody>
            </table>
        </div>
    </div>
</div>
</body>
</html>

Copy the code
  1. Running results:

At this point our integration and testing is complete!

Perfect finish!

Write in the last

If there is any mistake, you are welcome to point it out.

💌 The lower desires can be obtained through indulgence, the higher desires can be obtained through self-discipline, and the top desires can be obtained through suffering

A romantic universe, but also cherish the world’s daily code farmers