SSM framework integration process summary

Insert picture description here

Step 1: Demand analysis and database design

Design the database according to the needs and business needs, mainly including designing the structure of the database and some functions that need to be completed (crud)

Step 2: Build a database

1. Create a database

2. Create a table structure

3. Add constraints and views, etc.

Step 3: Build a basic maven project

1. Import the corresponding dependency package

The dependency packages required by SSM are as follows, written under dependencies in pom.xml:


<!--Junit单元测试包-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <!--数据库驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>
        <!-- 数据库连接池 -->
        <dependency>
            <groupId>com.mchange</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.5.2</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.2</version>
        </dependency>
        
        <!--Spring和Mybatis整合所需依赖包-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.2</version>
        </dependency>

        <!--Spring依赖包-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.1.9.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.1.9.RELEASE</version>
        </dependency>
<!--使用lombok-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.10</version>
        </dependency>

2. Solve the problem of static resource export

Add the following code in pom.xml

<!--解决maven静态资源导出问题-->
  <build>
  <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>

Step 4: Build the basic project structure

1. Build the package structure

pojo (entity class package)

dao (database persistence layer)

service (service layer)

controller (front controller)

2. Build basic resource files (built under resource)

mybatis-config.xml (Mybatis configuration file)

<?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>

</configuration>

applicationContext.xml (Spring configuration file)

<?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">

</beans>

database.properties (database connection resource file)

jdbc.driver=com.mysql.jdbc.Driver
# mysql 8.0及以上驱动包位置发生了改变要这样写:
# jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/数据库名?useSSL=true&useUnicode=true&characterEncoding=utf8
# mysql8.0及以上url也发生了一点点改变,应该这样写:
# jdbc.url=jdbc:mysql://localhost:3306/数据库名?serverTimezone=UTC&characterEncoding=utf8&useUnicode=true&useSSL=false
jdbc.username=用户名
jdbc.password=用户密码

Step 5: Write Mybatis layer code

1. Write entity classes

The entity class is written according to ORM principles, here we use lombok to save time

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Books {
   private int bookID;
   private String bookName;
   private int bookCounts;
   private String detail;
}

2. Write the Mapper interface corresponding to the table

Like the above BooksMapper, and here we use annotations to quickly develop

public interface BooksMapper {
   //增加一本书
   @Insert("insert into books(bookName, bookCounts, detail) VALUES (#{bookName},#{bookCounts},#{details})")
   int addBooks(Books books);
   //删除一本书
   @Delete("delete from books where bookID=#{id}")
   int deleteBookById(@Param("id") int id);
   //更新一本书
   @Update("update books set bookName=#{bookName},bookCounts=#{bookCounts},detail=#{detail}")
   int updateBooks(Books books);
   //查询一本书
   @Select("select * from books where bookID=#{id}")
   Books queryBooksById(@Param("id") int id);
   //查询全部书
   @Select("select * from books")
   List<Books> queryAllBooks();
}

3. Write the corresponding Mapper.xml file under resource

Here we create BooksMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
       PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
       "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--绑定到对应的接口-->
<mapper namespace="com.zyx.dao.BookMapper">

</mapper>

4. Bind Mapper to Mybatis configuration file

Which is our mybatis-config.xml here

<?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>
   <!--配置数据源,交给Spring去做-->

   <!--起别名,指向实体类包-->
   <typeAliases>
       <package name="com.zyx.pojo"/>
   </typeAliases>
   <mappers>
   <!--将BooksMapper.xml绑定进来-->
       <mapper resource="BooksMapper.xml"/>
   </mappers>
</configuration>

At this point, the Mybatis layer code is all done!

5. Write service layer code

(1) Write service interface

Here is BooksService

public interface BooksService {
   //增加一本书
   int addBooks(Books books);
   //删除一本书
   int deleteBookById(int id);
   //更新一本书
   int updateBooks(Books books);
   //查询一本书
   Books queryBooksById(int id);
   //查询全部书
   List<Books> queryAllBooks();
}

(2) Write interface implementation class

Here is BooksServiceImpl

public class BooksServiceImpl implements BooksService{
   //service层调dao,所以需要有一个dao层的mapper对象
   private BooksMapper booksMapper;
   //为了方便Spring对它进行注入,写上set方法
   public void setBookMapper(BooksMapper booksMapper) {
       this.booksMapper = booksMapper;
  }

   public int addBooks(Books books) {
       return booksMapper.addBooks(books);
  }

   public int deleteBookById(int id) {
       return booksMapper.deleteBookById(id);
  }

   public int updateBooks(Books books) {
       return booksMapper.updateBooks(books);
  }

   public Books queryBooksById(int id) {
       return booksMapper.queryBooksById(id);
  }

   public List<Books> queryAllBooks() {
       return booksMapper.queryAllBooks();
  }
}

At this point, the Mybatis layer code is all completed

Step 6: Write Spring layer code

1. Write a resource file for Spring to integrate the DAO layer

Is here 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
      http://www.springframework.org/schema/context/spring-context-4.2.xsd">
<!--1.关联数据库相关文件-->
   <context:property-placeholder location="classpath:database.properties"/>
<!--2.数据源(种类有)
   dbcp:半自动化操作,不能自动连接,需要手动连接
   c3p0:自动化操作,自动化加载配置文件,并且可以自动设置到对象中
   druid
   hikari
   DriverManngerDateSource Spring默认数据源
   这里我们使用C3P0
-->
   <bean class="com.mchange.v2.c3p0.ComboPooledDataSource" id="dataSource">
       <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>
<!--3.sqlSessionFactory-->
   <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
       <!-- 注入数据库连接池 -->
       <property name="dataSource" ref="dataSource"/>
       <!-- 配置MyBaties全局配置文件:mybatis-config.xml -->
       <property name="configLocation" value="classpath:mybatis-config.xml"/>
   </bean>

   <!-- 4.配置扫描Dao接口包,动态实现Dao接口注入到spring容器中 -->
   <!--解释 :https://www.cnblogs.com/jpfss/p/7799806.html-->
   <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
       <!-- 注入sqlSessionFactory -->
       <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
       <!-- 给出需要扫描Dao接口包 -->
       <property name="basePackage" value="com.zyx.dao"/>
   </bean>
</beans>

2. Write Spring integrated service layer resource files

The file here is 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"
      xmlns:mvc="http://www.springframework.org/schema/mvc"
      xsi:schemaLocation="http://www.springframework.org/schema/beans
      http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
   http://www.springframework.org/schema/mvc
   http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
   http://www.springframework.org/schema/context
   http://www.springframework.org/schema/context/spring-context-4.2.xsd">
   <!--1.扫描service下的包-->
   <context:component-scan base-package="com.zyx.service"/>
   <!--2.将业务类注入到Spring容器中,可以使用配置,也可以使用注解
       注解则不需要以下代码
   -->
   <bean class="com.zyx.service.BookServiceImpl" id="bookService">
       <property name="bookMapper" ref="bookMapper"/>
   </bean>
   <!--3.声明式事务配置-->
   <bean class="org.springframework.jdbc.datasource.DataSourceTransactionManager" id="transactionManager">
   <!--注入数据源-->
       <property name="dataSource" ref="dataSource"/>
   </bean>

   <!--4.aop事务支持-->

</beans>

Note: Use annotations to add @Service above the interface implementation class

At this point, the Spring layer code is all completed!

Step 7: Write SpringMVC layer code

1. Increase web support and create the required folders

It's relatively simple here, but not much explanation

2. Write SpringMVC configuration resource file

Here we are 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">


<!--1.注解驱动-->
   <mvc:annotation-driven/>
   <!--2.静态资源过滤-->
   <mvc:default-servlet-handler/>
   <!--3.扫描包 扫描Controller-->
   <context:component-scan base-package="com.zyx.controller"/>
   <!--4.视图解析器-->
   <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
       <property name="prefix" value="WEB-INF/jsp/"/>
       <property name="suffix" value=".jsp"/>
   </bean>
</beans>

3. Write the web.xml configuration file

<?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">
<!--DispatcherServlet-->
   <servlet>
       <servlet-name>springmvc</servlet-name>
       <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
       <!--绑定到配置文件-->
       <init-param>
           <param-name>contextConfigLocation</param-name>
           <param-value>classpath:Spring-mvc.xml</param-value>
       </init-param>
       <!--设置启动级别,和Tomcat一起启动-->
       <load-on-startup>1</load-on-startup>
   </servlet>
   <servlet-mapping>
       <servlet-name>springmvc</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过期时间-->
   <session-config>
       <session-timeout>15</session-timeout>
   </session-config>
</web-app>

Step 8: Configure Tomcat

slightly

Step 9: Increase business according to demand

Is to write the controller layer code and the view layer

Such as

index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
 <head>
   <title>首页</title>
 </head>
 <body>
 <a href="/allBook">点击跳转到数据展示页面</a>
 </body>
</html>

BookController.java

@Controller
public class BookController {
   //controller层调service层
   @Autowired
   @Qualifier("bookService")
   private BookService bookService;

   //查询所有书籍并且返回到书籍展示页面
   @RequestMapping("/allBook")
   public String list(Model model){
       List<Books> books = bookService.queryAllBooks();
       model.addAttribute("list",books);
       return "allBook";
  }
}

allBook.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
   <title>书籍展示页面</title>
</head>
<body>
${list}
</body>
</html>

Guess you like

Origin blog.csdn.net/weixin_49527334/article/details/113247683