一. SSM框架架构及流程介绍
SSM框架,通常是指将spring mvc+spring+mybatis三个框架整合在一起进行工作,spring mvc本身就是spring的一部分,所以这两者之间不用整合,这里主要做的事情就是将spring与mybatis框架进行整合,实际上就是将SqlSessionFactory对象交由spring来管理,事务方面也交由spring来管理。
1、SSM架构
SSM框架主要分为bean/entity层,mapper/dao层,service层,controller层。
(1)bean层(也叫entity/pojo/ model层) 用于存放我们的实体类,与数据库中的属性值基本保持一致。在bean创建具体的实体类对象,便于其他层对实体类对象进行直接操作
(2)dao层(mapper层) 负责与数据库进行联络的一些任务都封装在此,具体到对于某个表、某个实体的增删改查
(3)service层 service层主要负责业务模块的逻辑应用设计,可以细分为service接口和serviceImpl实现类
(4)controller层
控制器,导入service层,负责具体的业务模块流程的控制,在此层里面要调用Service层的接口来控制业务流程
2、SSM流程
调用流程: 前端JSP /html——> Controller ——> Service ——> Dao ——> 数据库
controller层使用ajax+json与前端的html文件进行交互,获取前端请求和返回数据给前端。前端页面用户请求通过ajax传到controller层调用相应的方法处理,然后反馈数据到html文件,把处理后数据显示在页面上,反馈给用户。
controller 层在执行相应的方法时,实际上是去调用service层对应的接口,从而service层获取实现类中的方法去完成对应业务,service层一般用事务来进行方法操作,保证操作的一致性。
service层实现类包含业务实现方法,也包含一些关于数据库处理的操作,但不是直接和数据库打交道。service层的方法如果需要操作数据库,那么就需要去调用dao层的接口。
dao层中mybatis框架常用mapper动态代理,所以dao层接口会对应mapper映射文件里面相应的sql语句,从而实现对数据库的操作。
这里还有bean层,bean层通常存放我们的实体类,与数据库中的属性值基本保持一致。在bean创建具体的实体类对象,便于其他层对实体类对象进行直接操作。最终在dao层中这些实体类对象的操作会直接映射到对应的sql语句,操作对应的数据库里面的数据。
反过来理解:启动项目的时候会解析mapper.xml文件,xml中有一个命名空间namespace指向dao,用动态代理和反射技术会生成一个dao层的实现类。dao层用来操作数据库,返回数据,service调用dao层获取的数据,根据具体的业务做一些处理,controller层调用service层,一般用来接收前台传来的数据,再将从service层获取的数据传给前台。
二. SSM框架搭建
1、创建一个maven项目,在里面新建常用的包,bean、controller、service、dao等;
2、完成各配置文件配置
(1)添加依赖,在工程的pom.xml文件中添加项目需要的jar包(主要是spring mvc+spring+mybatis3个框架涉及的jar包)
<?xml version="1.0" encoding="UTF-8"?>
<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">
<parent>
<artifactId>learn</artifactId>
<groupId>test</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>_11_ssm_crud</artifactId>
<packaging>war</packaging>
<name>_11_ssm_crud</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.0.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.13</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>5.0.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.0.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.0.4.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jsp-api</artifactId>
<version>2.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.46</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.25</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.25</version>
</dependency>
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>2.10.0</version>
</dependency>
<dependency>
<groupId>org.mybatis.caches</groupId>
<artifactId>mybatis-ehcache</artifactId>
<version>1.1.0</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.4</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.4</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.9.4</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.module</groupId>
<artifactId>jackson-module-parameter-names</artifactId>
<version>2.9.4</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jdk8</artifactId>
<version>2.9.4</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<version>2.9.4</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.10</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.46</version>
</dependency>
</dependencies>
<build>
<finalName>_11_ssm_crud</finalName>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
</build>
</project>
(2)完成spring-mvc部分的配置
a. resouce文件夹下添加spring-mvc.xml文件,完成spring-mvc部分配置文件配置。在spring-mvc.xml完成注册组件扫描器、视图解析器、内部视图解析器、静态资源、解决返回json数据乱码问题的配置。
<?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:p="http://www.springframework.org/schema/p"
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 http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--解决返回json数据乱码问题-->
<bean id="stringHttpMessageConverter"
class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/plain;charset=UTF-8</value>
<value>application/json;charset=UTF-8</value>
</list>
</property>
</bean>
<mvc:annotation-driven>
<mvc:message-converters>
<ref bean="stringHttpMessageConverter" />
</mvc:message-converters>
</mvc:annotation-driven>
<!--静态资源-->
<mvc:resources mapping="/images/**" location="/images/" />
<mvc:resources mapping="/js/**" location="/js/" />
<mvc:resources mapping="/css/**" location="/css/" />
<mvc:resources mapping="/html/**" location="/html/" />
<!-- 注册组件扫描器 ,组件扫描器只扫描controller包,不要扫描service等其他包,否则事务配置会失效-->
<context:component-scan base-package="test.controller"/>
<!-- 视图解析器 -->
<bean class="org.springframework.web.servlet.view.BeanNameViewResolver"/>
<!--内部视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/html/"/>
<property name="suffix" value=".html"/>
</bean>
</beans>
b. 完成WEB-INF/web.xml配置
完成指定spring配置文件的路径、注册spring监听器、注册字符集过滤器、注册spring mvc中央控制器的配置。
<?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_3_1.xsd"
version="3.1">
<!--指定spring配置文件的位置-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-*.xml</param-value>
</context-param>
<!--注册监听器-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--配置spring MVC配置项-->
<!--字符编码过滤器-->
<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>
<!--强制指定字符编码,即如果在request中指定了字符编码,那么也会为其强制指定当前设置的字符编码-->
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 注册spring MVC中央控制器 -->
<servlet>
<servlet-name>springMVC</servlet-name>
<!-- spring MVC中的核心控制器 -->
<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>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springMVC</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
(3)完成mybatis部分的配置
a. 添加数据库配置文件db.properties
#驱动
jdbc.driver=com.mysql.jdbc.Driver
#数据库连接地址
jdbc.url=jdbc:mysql://127.0.0.1:3306/ssm?useSSL=false
#用户名及数据库密码,这里需要修改,每个数据库的密码都不一样
jdbc.user=root
jdbc.password=mysql
b. 添加数据库日志配置文件log4j.properties
log4j.rootLogger=debug,console
log4j.appender.console = org.apache.log4j.ConsoleAppender
log4j.appender.console.Target = System.out
log4j.appender.console.layout = org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern= [%-5p][%d{yyyy-MM-dd HH:mm:ss}]%m%n
c. 添加数据库缓存配置文件ehcache.xml
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../config/ehcache.xsd">
<diskStore path="java.io.tmpdir"/>
<defaultCache
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
maxElementsOnDisk="10000000"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU">
<persistence strategy="localTempSwap"/>
</defaultCache>
</ehcache>
d. 添加mybatis.xml配置文件
这里只需要注册bean即可,mapper 映射文件的注册来使用spring的 MapperScannerConfigurer扫描器进行扫描,SqlSessionFactory交由spring管理,数据源也交由spring管理,所以都不需要配置。
<?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>
<typeAliases>
<package name="test.bean"/>
</typeAliases>
</configuration>
e. 添加spring-mybatis.xml配置文件
加载数据源,将sqlsessionfactory交由spring管理,使用MapperScannerConfigurer将将Mapper接口生成代理对象。需要注意的是,在注册组件扫描器的时候无需再扫描controller包下的类了,因为已经在springmvc的配置文件中扫描过了。
<?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:aop="http://www.springframework.org/schema/aop"
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/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 加载配置文件 -->
<context:property-placeholder location="classpath:db.properties"/>
<!-- 注册组件扫描器 -->
<context:component-scan base-package="test">
<!--不再扫描controller注解-->
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"
</context:component-scan>
<!-- 数据库连接池 -->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close">
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.user}" />
<property name="password" value="${jdbc.password}" />
<property name="driverClassName" value="${jdbc.driver}" />
<property name="maxActive" value="10" />
<property name="minIdle" value="5" />
</bean>
<!-- 让spring管理sqlsessionfactory 使用mybatis和spring整合包中的 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 数据库连接池 -->
<property name="dataSource" ref="dataSource" />
<!-- 加载mybatis的全局配置文件 -->
<property name="configLocation" value="classpath:mybatis.xml" />
</bean>
<!-- 自动扫描 将Mapper接口生成代理对象 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!--Mapper文件所在路径-->
<property name="basePackage" value="monmkey1024.dao" />
</bean>
</beans>
(4)完成spring部分的配置
添加spring-tx.xml文件进行事务的管理,采用AOP注解方式进行事务管理
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
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/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
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 事务管理器 -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- 数据源 -->
<property name="dataSource" ref="dataSource" />
</bean>
<!--开启注解事务驱动-->
<tx:annotation-driven transaction-manager="transactionManager"/>
</beans>
3、完成各层接口及实现类
(1)创建对应的数据库表t_user,包含id(主键)、name、phone、address、birthday字段
(2)bean层,创建User类--用户类对象
package test1.bean;
import org.springframework.format.annotation.DateTimeFormat;
import java.time.LocalDate;
public class User {
private int id;
private String name;
private String phone;
private String address;
@DateTimeFormat(pattern = "yyyy-mm-dd")
private LocalDate birthday;
public User() {
}
public User(String name, String phone, String address, LocalDate birthday) {
this.name = name;
this.phone = phone;
this.address = address;
this.birthday = birthday;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public LocalDate getBirthday() {
return birthday;
}
public void setBirthday(LocalDate birthday) {
this.birthday = birthday;
}
}
(3)dao层,创建UserDao接口文件和UserDao对应mapper文件UserDao.xml
UserDao接口文件
package test.dao;
import test.bean.User;
import java.util.List;
public interface UserDao {
void addUser(User user);
void updateUser(User user);
List<User> selectUsers();
User selectUserById(int id);
void deleteUser(int id);
}
UserDao.xml(具体对数据库操作的sql语句在此编辑)
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="test.dao.UserDao">
<cache type="org.mybatis.caches.ehcache.EhcacheCache"/>
<insert id="addUser">
INSERT INTO t_user
(name,phone,address,birthday)
VALUES
(#{name},#{phone},#{address},#{birthday});
<selectKey resultType="int" keyProperty="id" order="AFTER">
SELECT @@identity
</selectKey>
</insert>
<delete id="deleteUser">
DELETE FROM t_user where id=#{id}
</delete>
<update id="updateUser">
UPDATE t_user set name=#{name},phone=#{phone},address=#{address},birthday=#{birthday} where id=#{id}
</update>
<select id="selectUsers" resultType="user">
SELECT id,name,phone,address,birthday FROM t_user
</select>
<select id="selectUserById" resultType="user">
SELECT id,name,phone,address,birthday FROM t_user where id=#{id}
</select>
</mapper>
(4)service层:创建UserService接口和实现类
UserService接口
package test.service;
import test.bean.User;
import java.util.List;
public interface UserService {
void addUser(User user);
void updateUser(User user);
List<User> selectUsers();
User selectUserById(int id);
void deleteUser(int id);
}
UserServiceImpl实现类()
package test.service.impl;
import test.bean.User;
import test.dao.UserDao;
import test.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Service //用于对 Service 实现类进行注解,Spring会去自动创建UserServiceImpl的对象,并且通过注解,容器会查找UserService类型的实例userService将其注入,也可以用@Component
@Transactional //使用注解配置事务
public class UserServiceImpl implements UserService {
@Autowired //自动注入注解,该注解默认使用按类型自动装配,即容器会查找UserDao类型的实例将其注入,初始化其对象,然后可以直接使用对象中的方法如 userDao.addUser(user),不用再用new创建对象
private UserDao userDao;
@Override
public void addUser(User user) {
userDao.addUser(user);
}
@Override
public void updateUser(User user) {
userDao.updateUser(user);
}
@Override
public List<User> selectUsers() {
return userDao.selectUsers();
}
@Override
public User selectUserById(int id) {
return userDao.selectUserById(id);
}
@Override
public void deleteUser(int id) {
userDao.deleteUser(id);
}
}
(5)controller层:创建controller类,使用restful风格:
package test.controller;
import com.alibaba.fastjson.JSON;
import test.bean.User;
import test.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController //restful风格中spring mvc常用注解
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/users") //该注解用来替代RequestMapping,特点是@GetMapping只处理get方式的请求,//注解后面要加上URL地址
public String selectUsers(){
List<User> users = userService.selectUsers();
return JSON.toJSONString(users);
}
@GetMapping("/users/{id}")//注解后面要加上URL地址,地址中包含所需要的资源,比如这里的id
public String selectUserById(@PathVariable int id) {
User user = userService.selectUserById(id);
return JSON.toJSONString(user);
}
@PostMapping("/users")
public String addUser(@RequestBody User user) {
try {
userService.addUser(user);
return JSON.toJSONString("success");
} catch (Exception e) {
e.printStackTrace();
return JSON.toJSONString("fail");
}
}
@PutMapping("/users/{id}")
public String updateUser(@PathVariable int id, @RequestBody User user) {
try {
user.setId(id);
userService.updateUser(user);
return JSON.toJSONString("success");
} catch (Exception e) {
e.printStackTrace();
return JSON.toJSONString("fail");
}
}
@DeleteMapping("/users/{id}")
public String deleteUser(@PathVariable int id) {
try {
userService.deleteUser(id);
return JSON.toJSONString("success");
} catch (Exception e) {
e.printStackTrace();
return JSON.toJSONString("fail");
}
}
}
4、最后根据需要在webapp/html文件夹下创建需要的html前端文件即可。
以上就是搭建SSM框架组合完成简单增删改查的功能,大家可以根据这个思路自己去实践下。
demo文件后续会附上。
参考资料:
https://www.cnblogs.com/wmyskxz/p/8916365.html
相应的SSM框架入门教程