欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

SSM框架的整合

程序员文章站 2024-01-15 23:52:40
...

一、搭建SSM的整合环境

1.1、SSM整合的思路

        1.先搭建整合的环境

        2.Spring的配置搭建

        3.Spring整合SpringMVC

        4.Spring整合Mybatis

1.2、创建数据库和表

CREATE TABLE `ssm_user` (
	`id` INT ( 11 ) NOT NULL AUTO_INCREMENT,
	`username` VARCHAR ( 20 ) DEFAULT NULL,
	`password` VARCHAR ( 20 ) DEFAULT NULL,
PRIMARY KEY ( `id` ) 
) ENGINE = INNODB DEFAULT CHARSET = utf8

1.3、创建Maven工程

1.3.1、创建SSM的Maven工程

SSM框架的整合

1.3.2、导入需要的依赖

<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>cn.waggag.ssm</groupId>
	<artifactId>ssm</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>
	<description>SSM框架的整合</description>

	<!-- 版本控制 -->
	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<maven.compiler.source>1.8</maven.compiler.source>
		<maven.compiler.target>1.8</maven.compiler.target>
		<spring.version>5.1.8.RELEASE</spring.version>
		<slf4j.version>1.6.6</slf4j.version>
		<log4j.version>1.2.16</log4j.version>
		<mysql.version>8.0.16</mysql.version>
		<mybatis.version>3.5.2</mybatis.version>
		<junit.version>4.12</junit.version>
	</properties>

	<dependencies>
		<!-- spring -->
		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjweaver</artifactId>
			<version>1.9.4</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-aop</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-tx</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>${junit.version}</version>
		</dependency>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>${mysql.version}</version>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
			<version>2.5</version>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jsp-api</artifactId>
			<version>2.0</version>
		</dependency>
		<dependency>
			<groupId>jstl</groupId>
			<artifactId>jstl</artifactId>
			<version>1.2</version>
		</dependency>
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>${log4j.version}</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>${slf4j.version}</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-log4j12</artifactId>
			<version>${slf4j.version}</version>
		</dependency>
		<!--Mybatis -->
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis</artifactId>
			<version>${mybatis.version}</version>
		</dependency>
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis-spring</artifactId>
			<version>2.0.2</version>
		</dependency>
		<!-- druid的连接池 -->
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>druid</artifactId>
			<version>1.1.19</version>
		</dependency>
	</dependencies>

	<build>
		<finalName>ssm</finalName>
		<pluginManagement>
			<plugins>
				<plugin>
					<groupId>org.apache.maven.plugins</groupId>
					<artifactId>maven-compiler-plugin</artifactId>
					<version>3.8.1</version>
					<configuration>
						<source>1.8</source>
						<target>1.8</target>
						<encoding>UTF-8</encoding>
						<showWarnings>true</showWarnings>
					</configuration>
				</plugin>
			</plugins>
		</pluginManagement>
	</build>
</project>

1.4、编写一个JavaBean的类

package cn.waggag.domain;

import java.io.Serializable;

/**
 * @description: 用户的实体类
 * @author waggag
 * @Data 2019年7月19日下午6:04:44
 * @Company www.waggag.cn
 */
public class User implements Serializable{
	
	private String username;
	private String password;
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	@Override
	public String toString() {
		return "User [username=" + username + ", password=" + password + "]";
	}
	
}

1.5、创建基本的包结构和类

SSM框架的整合

1.6、Dap层

package cn.waggag.mapper;

import java.util.List;

import cn.waggag.domain.User;

/**
 * @description: 用户的mapper接口
 * @author waggag
 * @Data 2019年7月19日下午6:10:45
 * @Company www.waggag.cn
 */
public interface UserMapper {
	
	//查询所有用户
	public List<User> findAll();
	
	//添加一个用户
	public void addUser(User user);
	
}

1.7、Service层

//接口
public interface UserService {

	// 查询所有用户
	public List<User> findAll();

	// 添加一个用户
	public void addUser(User user);

}

//实现类

package cn.waggag.service.impl;
import java.util.List;
import cn.waggag.domain.User;
import cn.waggag.service.UserService;
public class UserServiceImpl implements UserService {

	@Override
	public List<User> findAll() {
		System.out.println("Service的findAll");
		return null;
	}

	@Override
	public void addUser(User user) {
		System.out.println("Service的addUser");
	}

}

1.8、Controller层

package cn.waggag.controller;

public class UserController {

}

二、Spring环境的搭建

2.1、在resources下创建applicationContext.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
        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/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd">
        
        <!-- 开启注解扫描 -->
        <context:component-scan base-package="cn.waggag.*">
        	<!-- 排除Controller的注解扫描 -->
        	<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
        </context:component-scan>
        
</beans>

2.2、UserService加上注解扫描

package cn.waggag.service.impl;
import java.util.List;
import org.springframework.stereotype.Service;
import cn.waggag.domain.User;
import cn.waggag.service.UserService;
@Service("accountService")
public class UserServiceImpl implements UserService {
	@Override
	public List<User> findAll() {
		System.out.println("Service的findAll");
		return null;
	}
	@Override
	public void addUser(User user) {
		System.out.println("Service的addUser");
	}
}

2.3、测试Spring的搭建

package cn.waggag.test;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import cn.waggag.service.UserService;

/**
 * 测试Spring环境的搭建
 * @description:
 * @author waggag
 * @Data 2019年7月19日下午6:32:40
 * @Company www.waggag.cn
 */
public class testSpring {
	
	@Test
	public void testSpring() {
		//加载配置文件
		ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
		//获取对象
		UserService userService = applicationContext.getBean("accountService",UserService.class);
		//调用service方法
		userService.findAll();
		
	}

}

三、SpringMVC环境的搭建

3.1、web.xml配置前端控制器

     <!-- post乱码过滤器 -->
    <filter>
        <filter-name>CharacterEncodingFilter</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>CharacterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
     <!--配置SpringMVC-->
    <!--前端控制器-->
    <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:applicationContext.xml</param-value>
        </init-param>
        <!-- 配置servlet启动时加载对象 -->
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

3.2、创建springmvc.xml的配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:context="http://www.springframework.org/schema/context"
	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
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">

	<!--开启SpringMVC注解的支持 -->
	<mvc:annotation-driven />

	<!--配置包扫描器,扫描@Controller注解的类 -->
	<context:component-scan
		base-package="cn.waggag.controller">
		<context:include-filter type="annotation"
			expression="org.springframework.stereotype.Controller" />
	</context:component-scan>

	<!--配置的视图解析器对象 -->
	<bean id="internalResourceViewResolver"
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/pages/" />
		<property name="suffix" value=".jsp" />
	</bean>

	<!--过滤静态资源,谷歌可以正常浏览,火狐等必须配置资源映射才能访问静态资源文件 -->
	<mvc:resources location="/css/" mapping="/css/**" />
	<mvc:resources location="/images/" mapping="/images/**" />
	<mvc:resources location="/js/" mapping="/js/**" />

</beans>

3.3、UserController加上注解

package cn.waggag.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/user")
public class UserController {
    
    @RequestMapping("/findAll")
    public String testSpringMVC() {
        System.out.println("Controller的findAll");
        return "list";
    }
}
3.4、测试SpringMVC的搭建

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>TestSpringMVC</title>
</head>
<body>
    <a href="user/findAll">测试SpringMVC</a>
</body>
</html>

四、Spring整合SpringMVC

4.1、web.xml中在项目创建的时候加载Spring的配置文件

     <!--设置Spring的配置文件的路径-->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>
     <!--初始化spring容器,项目启动的时候加载Spring的配置文件-->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

4.2、Controller中注入UserService

package cn.waggag.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import cn.waggag.service.UserService;
@Controller
@RequestMapping("/user")
public class UserController {
	
	@Autowired
	private UserService userService;
	
	@RequestMapping("/findAll")
	public String testSpringMVC() {
		System.out.println("Controller的findAll");
		userService.findAll();
		return "list";
	}
}

五、Mybatis的环境搭建

5.1、UserDao使用注解,不提供映射文件

package cn.waggag.mapper;

import java.util.List;

import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;

import cn.waggag.domain.User;

/**
 * @description: 用户的mapper接口
 * @author waggag
 * @Data 2019年7月19日下午6:10:45
 * @Company www.waggag.cn
 */
@Repository
public interface UserMapper {
	
	//查询所有用户
	@Select("select * from ssm_user;")
	public List<User> findAll();
	
	//添加一个用户
	@Insert("insert into ssm_user(username,password) values(#{username},#{password})")
	public void addUser(User user);
	
}

5.2、创建配置文件SqlMapConfig.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>
    <!-- 配置连接数据库的信息 -->
    <properties resource="jdbc.properties"></properties>
    <!-- 配置mybatis的环境 -->
    <environments default="mysql">
        <environment id="mysql">
            <!-- 配置事务管理 -->
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.username}"/>
                <property name="password" value="${jdbc.password}"/>
            </dataSource>
        </environment>
    </environments>

    <!-- 指定映射文件位置 -->
    <mappers>
        <package name="cn.waggag.mapper"/>
    </mappers>
</configuration>

5.3、手动加载配置文件,测试Mybatis的环境。

package cn.waggag.test;

import java.io.InputStream;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;

import cn.waggag.mapper.UserMapper;

public class testMybatis {
	
	@Test
	public void testMybatis() throws Exception {
		//1.加载配置文件
		InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
		//2.获取SqlSessionFactory
		SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
		//3.获取SqlSession
		SqlSession sqlSession = sqlSessionFactory.openSession();
		//4.获取Dao对象
		UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
		//5.调用方法
        //更新删除的方法测试需要手动提交事务sqlSession.commit()
		userMapper.findAll();
		//6.释放资源
		inputStream.close();
		sqlSession.close();
	}
	
}

六、Spring整合Mybatis

6.1、applicationContext.xml整合Mybatis

        <!--spring整合Mybatis框架-->
	    <!--加载数据库配置文件-->
	    <context:property-placeholder location="classpath:jdbc.properties"/>
	    <!--配置连接池-->
	    <bean id="c3p0DataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
	        <property name="driverClass" value="${jdbc.driver}"></property>
	        <property name="jdbcUrl" value="${jdbc.url}"></property>
	        <property name="user" value="${jdbc.username}"></property>
	        <property name="password" value="${jdbc.password}"></property>
	    </bean>
	    <bean id="druidDataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close">
	        <property name="driverClassName" value="${jdbc.driver}"></property>
	        <property name="url" value="${jdbc.url}"></property>
	        <property name="username" value="${jdbc.username}"></property>
	        <property name="password" value="${jdbc.password}"></property>
	    </bean>
	    <!--配置SqlSessionFactory工厂-->
	    <!--让spring管理SqlSessionFactory 使用Mybatis和Spring整合包中的SqlSessionFactoryBean-->
	    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
	        <!-- 数据库连接池 -->
	        <property name="dataSource" ref="druidDataSource"></property>
	        <!--加载Mybatis的全局配置文件,保留Mybatis的配置文件 -->
	        <property name="configLocation" value="classpath:SqlMapConfig.xml" />
	    </bean>
	    <!--配置映射文件所在位置-->
	    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
	        <property name="basePackage" value="cn.waggag.*"></property>
	    </bean>

6.2、UserService中使用注解自动注入UserMapper。

@Autowired
private UserMapper userMapper;

6.3、配置Spring的声明式事务管理,在applicationContext.xml中配置声明式事务。

  <!--配置Spring框架的声明式事务管理-->
    <!--配置事务管理器-->
    <bean id="dataSourceTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="druidDataSource"></property>
    </bean>
    <!--配置事务通知-->
    <tx:advice id="txAdvice" transaction-manager="dataSourceTransactionManager">
        <tx:attributes>
            <!-- 传播行为,方法用这些开头,开启事务 -->
            <tx:method name="save*" propagation="REQUIRED" />
            <tx:method name="insert*" propagation="REQUIRED" />
            <tx:method name="add*" propagation="REQUIRED" />
            <tx:method name="create*" propagation="REQUIRED" />
            <tx:method name="delete*" propagation="REQUIRED" />
            <tx:method name="update*" propagation="REQUIRED" />
            <tx:method name="find*" propagation="SUPPORTS" read-only="true" />
            <tx:method name="select*" propagation="SUPPORTS" read-only="true" />
            <tx:method name="get*" propagation="SUPPORTS" read-only="true" />
        </tx:attributes>
    </tx:advice>
    <!--配置AOP增强-->
    <aop:config>
        <aop:advisor advice-ref="txAdvice"
                     pointcut="execution(* cn.waggag.service.*.*(..))"></aop:advisor>
    </aop:config>

七、总结。

       一步一步的配置测试,SSM框架的搭建也不算太过于麻烦,关键配置文件的配置,使用IDEA的可以添加模板,将常用的配置加入模板,以后使用很方便。个人推荐使用IDEA,用Myeclipse搭建Maven项目的,期间碰到了各种的问题,反正我以后是尽量不用Myeclipse了。

源码链接: https://share.weiyun.com/5V2XjpK (密码:pCpd)