利用配置的方式搭建SSM(Spring、SpringMVC、MyBatis)框架


前言

使用SSM框架,需要熟练掌握MySQL数据库、Spring、JAVAWeb以及MyBatis知识,简单前端知识。


一、步骤

1.前期搭建

1)创建数据库表:

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 '描述',
  PRIMARY KEY (`bookID`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;

INSERT INTO `books` VALUES ('1', 'Java', '1', '从入门到放弃');
INSERT INTO `books` VALUES ('2', 'MySQL', '10', '从删库到跑路');
INSERT INTO `books` VALUES ('3', 'Linux', '5', '从进门到进牢');

注意:这里sql语句不要全选运行,可能会出错!

2)环境搭建

新建maven项目,命名为ssmbuild,添加web支持
pom 导入相关依赖

<dependencies>
	<!-- junit -->
	 <dependency>
	 	<groupId>junit</groupId>
	 	<artifactId>junit</artifactId>
	 	<version>3.8.1</version>
	 	<scope>test</scope>
	 </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核心依赖 -->
	 <dependency>
	 	<groupId>javax.servlet</groupId>
	 	<artifactId>javax.servlet-api</artifactId>
	 	<version>3.1.0</version>
	 	<scope>provided</scope>
	 </dependency>
	 
	 <!-- JSTL标签库 -->
	 <dependency>
	 	<groupId>javax.servlet</groupId>
	 	<artifactId>jstl</artifactId>
	 	<version>1.2</version>
	 </dependency>
	 
	 <!-- jsp -->
	 <!-- Servlet核心依赖 -->
	 <dependency>
	 	<groupId>javax.servlet.jsp</groupId>
	 	<artifactId>jsp-api</artifactId>
	 	<version>2.2</version>
	 </dependency>
	 
	 <!-- mybatis -->
	 <dependency>
	 	<groupId>org.mybatis</groupId>
	 	<artifactId>mybatis</artifactId<version>3.5.2</version>
	 </dependency>
	 
	 <dependency>
	 	<groupId>org.mybatis</groupId>
	 	<artifactId>mybatis-spring</artifactId>
	 	<version>2.0.2</version>
	 </dependency>
	 
	 <!-- Spring依赖 -->
	 <dependency>
	 	<groupId>org.springframework</groupId>
	 	<artifactId>spring-jdbc</artifactId>
	 	<version>5.1.9.RELEASE</version>
	 </dependency>
	 <dependency>
	 	<groupId>org.springframework</groupId>
	 	<artifactId>spring-webmvc</artifactId>
	 	<version>4.3.29.RELEASE</version>
	 </dependency>
	 <dependency>
	 	<groupId>org.aspectj</groupId>
	 	<artifactId>aspectjweaver</artifactId>
	 	<version>1.8.13</version>
	 </dependency>
	 
	 <!-- lombok -->
	 <dependency>
	 	<groupId>org.projectlombok</groupId>
	 	<artifactId>lombok</artifactId>
	 	<version>1.16.10</version>
	 </dependency>
</dependencies>

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>

1、建立基本的包结构 :com.xxx.pojo(实体)、com.xxx.controller(控制层)、com.xxx.dao(数据持久层)、com.xxx.service(业务层)
2、在resources目录下建立需要的资源:mybatis-config.xml(MyBatis核心配置文件)、appilcationContext.xml(Spring核心配置文件)

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="STDOUT_LOGGING"/>
    </settings>
    <!-- 配置数据源,交给Spring去做 -->
    
    <typeAliases>
        <package name="com.xxx.pojo"/>
    </typeAliases>

	<!-- 绑定接口 -->
    <mappers>
        <mapper class="com.xxx.dao.BookMapper"/>
    </mappers>

</configuration>

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

2.MyBatis层

1)数据库配置文件database.properties(在resources目录下创建):

mysql.driver=com.mysql.jdbc.Driver
# 如果使用的时MySQL8.0+,增加一个时区的配置;    serverTimezone=Asia/Shanghai
mysql.url=jdbc:mysql://localhost:3306/ssmbuild?useSSL=true&useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
mysql.username=root
mysql.password=123456

2)编写mybatis-config.xml(见上)

3)创建实体类 Books.java:

package com.xxx.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Books {

    private int bookID;
    private String bookName;
    private int bookCounts;
    private String detail;

}

4)在dao层创建对应接口以及MyBatis映射文件:

接口

package com.xxx.dao;

import com.xxx.pojo.Books;
import org.apache.ibatis.annotations.Param;

import java.util.List;

public interface BookMapper {

    // 增加一本书
    int addBook(Books books);

    // 删除一本书
    int deleteBookById(@Param("bookId") int id);

    // 更新一本书
    int updateBook(Books books);

    // 查询一本书
    Books queryBookById(@Param("bookId") int id);

    // 查询全部书籍
    List<Books> queryAllBook();

    Books queryBookByName(@Param("bookName") String bookName);
}

映射文件

<?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.xxx.dao.BookMapper">

    <insert id="addBook" parameterType="Books">
        insert into ssmbuild.books (bookName, bookCounts, detail)
        values (#{bookName},#{bookCounts},#{detail});
    </insert>

    <delete id="deleteBookById" parameterType="int">
        delete from ssmbuild.books where bookID = #{bookID}
    </delete>

    <update id="updateBook" parameterType="Books">
        update ssmbuild.books
        set bookName=#{bookName},bookCounts=#{bookCounts},detail=#{detail}
        where bookID=#{bookId};
    </update>

    <select id="queryBookById" resultType="Books">
        select bookID,bookName,bookCounts,detail
        from ssmbuild.books
        where bookID=#{bookId};
    </select>

    <select id="queryAllBook" resultType="Books">
        select bookID,bookName,bookCounts,detail
        from ssmbuild.books
    </select>

    <select id="queryBookByName" resultType="Books">
        select bookID,bookName,bookCounts,detail
        from ssmbuild.books
        where bookName=#{bookName}
    </select>
    
</mapper>

将接口绑定到配置文件mybatis-config.xml中:
说明:上述建立配置文件时,内容已包含接口绑定,这里只是做说明,以便结构完整清楚

<mappers>
	<mapper class="com.xxx.dao.BookMapper"/>
</mappers>

5)在service层中创建相应业务接口及对应实现类:

接口:

package com.xxx.service;

import com.xxx.pojo.Books;

import java.util.List;

public interface BookService {
    // 增加一本书
    int addBook(Books books);

    // 删除一本书
    int deleteBookById(int id);

    // 更新一本书
    int updateBook(Books books);

    // 查询一本书
    Books queryBookById(int id);

    // 查询全部书籍
    List<Books> queryAllBook();

    Books queryBookByName(String bookName);
}

实现类:

package com.xxx.service;

import com.xxx.dao.BookMapper;
import com.xxx.pojo.Books;

import java.util.List;

public class BookServiceImpl implements BookService {

    //service层 调 dao层:组合Dao
    private BookMapper bookMapper;
    public void setBookMapper(BookMapper bookMapper) {
        this.bookMapper = bookMapper;
    }

    public int addBook(Books books) {
        return bookMapper.addBook(books);
    }

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

    public int updateBook(Books books) {
        return bookMapper.updateBook(books);
    }

    public Books queryBookById(int id) {
        return bookMapper.queryBookById(id);
    }

    public List<Books> queryAllBook() {
        return bookMapper.queryAllBook();
    }

    public Books queryBookByName(String bookName) {
        return bookMapper.queryBookByName(bookName);
    }
}

3.Spring层

1)在resources目录下,新建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">

    <!-- 1、关联数据库配置文件 -->
    <!-- 此处不能用import关联,import只能用作导入spring配件 -->
    <context:property-placeholder location="classpath:database.properties"/>

    <!-- 2、连接池 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${mysql.driver}"/>
        <property name="jdbcUrl" value="${mysql.url}"/>
        <property name="user" value="${mysql.username}"/>
        <property name="password" value="${mysql.password}"/>

        <!-- c3p0 私有属性 -->
        <property name="maxPoolSize" value="100"/>
        <property name="minPoolSize" value="2"/>
        <!-- 获取连接超时时间 -->
        <property name="checkoutTimeout" value="30000"/>
        <!-- 关闭连接后不自动commit -->
        <property name="autoCommitOnClose" value="false"/>
        <!-- 当获取连接失败时重试次数 -->
        <property name="acquireRetryAttempts" value="3"/>
    </bean>

    <!-- 3、sqlSessionFactory -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <!-- 绑定Mybatis的配置文件 -->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
    </bean>

    <!-- 配置dao接口扫描包,动态的实现Dao接口可以注入到Spring容器中! -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- 注入sqlSessionFactory -->
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
        <!-- 要扫描的dao包 -->
        <property name="basePackage" value="com.xxx.dao"/>
    </bean>
</beans>

2)在resources目录下,新建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:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       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/aop
       https://www.springframework.org/schema/aop/spring-aop.xsd
       http://www.springframework.org/schema/tx
       http://www.springframework.org/schema/tx/spring-tx.xsd">

    <!-- 1、扫描service下的包 -->
    <context:component-scan base-package="com.xxx.service"/>

    <!-- 2、将我们的所有业务类,注入到Spring,可以通过配置,或者注解实现 -->
    <bean id="BookServiceImpl" class="com.xxx.service.BookServiceImpl">
        <property name="bookMapper" ref="bookMapper"/>
    </bean>

    <!-- 3、声明式事务配置 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!-- 注入数据源 -->
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <!-- 4、aop事务支持 -->
    <!-- 配置事务通知 -->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <!-- 给方法配置事务 -->
        <!-- 配置事务的传播特性 -->
        <tx:attributes>
            <tx:method name="*" propagation="REQUIRED"/>
        </tx:attributes>
    </tx:advice>
    <!-- 配置事务切入 -->
    <aop:config>
        <aop:pointcut id="txPointCut" expression="execution(* com.xxx.dao.*.*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
    </aop:config>

</beans>

3)在appilcationContext.xml中,绑定spring-dao.xml、spring-service.xml:

说明:下面两条语句只用作说明,第一步创建该xml时,代码就已经写入

<import resource="classpath:spring-dao.xml"/>
<import resource="classpath:spring-service.xml"/>

4.SpringMVC层

1)在resources目录下,新建spring-mvc.xml,并放入appilcationContext.xml中:

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

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

appilcationContext.xml

<import resource="classpath:spring-mvc.xml"/>

2)编写web.xml:

前提:项目增加了web支持

<?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:appilcationContext.xml</param-value>
        </init-param>
        <!-- 启动等级为1,与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>encodingFilter</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>encodingFilter</filter-name>
        <!-- 如果只有/,页面乱码无法解决 -->
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <!-- Session -->
    <session-config>
        <session-timeout>15</session-timeout>
    </session-config>

</web-app>

总结

以上是我通过学习总结出的学习笔记,如有错误,欢迎指正!

学习视频链接:【狂神说Java】SSM框架最新整合教学IDEA版
博主B站主页链接:遇见狂神说

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值