一、整合思路
SSM框架即SpringMVC + Spring + MyBati框架集,是一种轻量级的Web开源框架。它们各自在JAVA三层架构中负责的模块如下图所示:
其中,SpringMVC与Spring之间本就存在包含关系,所以它们之间并不需要整合,只需要在web.xml中配置使用即可。而SpringMVC并不和MyBatis直接交互,因此它们之间也不需要进行配置。只有Spring和MyBatis二者之间,我们需要用Spring来将MyBatis整合进来。
因此,我们只需要对web.xml和Spring的配置文件进行一些额外的配置即可。
下面,我们通过实现一个简单的转账系统,来展示SSM框架的整合和使用。
二、SSM框架整合
首先新建一个JavaWeb项目,导入SpringMVC、Spring、MyBatis三个框架的jar包和它们之间整合所需要的jar包。
在src目录下创建controller、dao、service、pojo四个包,分别用来存放控制层、持久层、业务层、普通java类的代码。
配置web.xml,使项目加载SpringMVC和Spring。
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0">
<display-name>SSM</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<!-- 配置服务器启动时加载SpringMVC的调度器 -->
<servlet>
<servlet-name>SpringMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<!-- 配置由调度器处理的URL -->
<servlet-mapping>
<servlet-name>SpringMVC</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- 配置监听器启动Spring -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 指定Spring配置文件路径 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!-- 配置过滤器避免中文乱码 -->
<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>
</web-app>
在WEB-INF中创建SpringMVC配置文件SpringMVC-servlet.xml(也可以将配置文件放到其他位置,但需要在web.xml中指明配置文件的路径)和jsp文件夹,jsp文件夹用来存放jsp页面。
<?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.xsd">
<!-- 配置需要注解扫描的控制层包 -->
<context:component-scan base-package="controller" />
<!-- 配置视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
在src目录下创建Spring的配置文件applicationContext.xml(文件路径在web.xml中指定),配置Spring并加载MyBatis。
<?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:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://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/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- 配置需要注解扫描的业务层包 -->
<context:component-scan base-package="service"/>
<!-- 配置数据源 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/user?serverTimezone=Asia/Shanghai"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean>
<!-- 配置MyBatis工厂 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="configLocation" value="classpath:dao/mybatis-config.xml"/>
</bean>
<!-- 配置Spring扫描MyBatis的接口 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="dao"/>
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
</bean>
<!-- 添加事务支持 -->
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- 开启事务注解扫描 -->
<tx:annotation-driven transaction-manager="txManager"/>
</beans>
在dao包里创建MyBatis的配置文件mybatis-config.xml(文件路径在Spring配置文件中指定),指明MyBatis映射文件的路径。
<?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>
<mappers>
<mapper resource="dao/UserMapper.xml"/>
</mappers>
</configuration>
在dao包中创建MyBatis的映射文件UserMapper.xml,用来后面实现转账系统时使用。
到了这里,SSM框架环境就已经搭建完成了,可以开始编写代码来实现转账系统了。整合后总的目录结构如下所示:
三、转账系统实现
我们要实现的转账系统很简单,该系统具体的操作流程就是“注册——登录——转账”,用户注册后,默认有100元的余额,然后就可以登陆系统,给指定的用户转账。虽然系统简单,但包含了SSM框架中最基础的部分。
1、实现持久层
经过分析,我们要实现这样的转账系统,首先需要一个记录用户信息的表,因此我们在数据库中,创建一个user库和一个user表,表定义如下:
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(10) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
`password` varchar(10) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
`sum` int(11) NOT NULL DEFAULT 100,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 10 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
并插入几条初始数据。
在pojo包中,创建一个跟user表字段对应的类User.java,便于我们传递数据。
package pojo; public class User { private int id; private String username; private String password; private int sum; public int getId() {
return id;
} public void setId(int id) {
this.id = id;
} 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;
} public int getSum() {
return sum;
} public void setSum(int sum) {
this.sum = sum;
} @Override
public String toString() {
return "User [id=" + id + ", username=" + username + ", password=" + password + ", sum=" + sum + "]";
} }
在前面创建的MyBatis映射文件UserMapper.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="dao.UserDao">
<select id="selectUserByNameAndPass" resultType="pojo.User" parameterType="pojo.User">
select * from user where username = #{username} and password = #{password}
</select>
<select id="selectUserByName" resultType="pojo.User" parameterType="pojo.User">
select * from user where username = #{username}
</select>
<insert id="addUser" parameterType="pojo.User">
insert into user (username,password) values (#{username},#{password})
</insert>
<update id="updateSumByName" parameterType="pojo.User">
update user set sum = #{sum} where username = #{username}
</update>
</mapper>
在dao包中创建UserDao.java接口,编写MyBatis映射接口。
package dao; import org.apache.ibatis.annotations.Mapper; import pojo.User; @Mapper
public interface UserDao { public User selectUserByNameAndPass(User user); public int addUser(User user); public User selectUserByName(User user); public int updateSumByName(User user);
}
到这里持久层就编写完成了,此时的目录结构如下:
2、实现业务层
经过分析,该系统需要实现的业务有三个,分别是“登录”、“注册”和“转账”。我们可以在service包下创建UserService.java类,用三个方法来实现这些业务。代码如下:
package service; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import dao.UserDao;
import pojo.User; @Service
public class UserService { @Autowired
private UserDao userDao; @Autowired
private HttpSession httpSession; public boolean login(User user) {
//验证账号密码
user = userDao.selectUserByNameAndPass(user);
if (user == null) {
return false;
}
//设置Session
httpSession.invalidate();
httpSession.setAttribute("username", user.getUsername());
return true;
} public boolean register(User user) {
//检查用户名是否重复
if (userDao.selectUserByName(user) != null) {
return false;
}
userDao.addUser(user);
return true;
} @Transactional
public boolean transfer(User user_in) {
//检查是否自己向自己转账
if (((String) httpSession.getAttribute("username")).equals(user_in.getUsername())) {
return false;
}
//检查转账金额是否为正数
int transferSum = user_in.getSum();
if (transferSum <= 0) {
return false;
}
//检查转账目标用户是否存在
user_in = userDao.selectUserByName(user_in);
if (user_in == null) {
return false;
}
//检查用户是否有足够的余额进行转账
User user_out = new User();
user_out.setUsername((String) httpSession.getAttribute("username"));
user_out = userDao.selectUserByName(user_out);
int remainSum = user_out.getSum() - transferSum;
if ( remainSum < 0) {
return false;
}
//开始转账
user_out.setSum(remainSum);
userDao.updateSumByName(user_out);
user_in.setSum(user_in.getSum() + transferSum);
userDao.updateSumByName(user_in);
return true;
}
}
三、实现控制层
跟业务层一样,控制层也需要三个控制器来调用业务层。我们在controller包中创建UserController.java类,同样需要编写三个方法,代码如下:
package controller; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping; import pojo.User;
import service.UserService; @Controller
public class UserController { @Autowired
private UserService userService; @RequestMapping("/login")
public String login(User user) {
if(!userService.login(user)) {
return "LoginError";
}
return "Transfer";
} @RequestMapping("/register")
public String register(User user) {
if(userService.register(user)) {
return "RegisterSuccess";
}
return "RegisterError";
} @RequestMapping("/transfer")
public String transfer(User user) {
if (userService.transfer(user)) {
return "TransferSuccess";
}
return "TransferError";
}
}
4、实现视图层
根据控制层中的定义,我们总共需要编写七个jsp页面,分别如下:
登录注册页面login.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>登录</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/login" method="post">
<table>
<tr>
<td align="right">用户名:</td>
<td><input type="text" name="username"/></td>
</tr>
<tr>
<td align="right">密码:</td>
<td><input type="password" name="password"/></td>
</tr>
<tr>
<td align="center" colspan="2"><input type="submit" value="登录"/><input type="submit" value="注册" formaction="${pageContext.request.contextPath}/register"/></td>
</tr>
</table>
</form>
</body>
</html>
登录失败页面LoginError.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>登录失败</title>
</head>
<body>
用户名或密码错误!
</body>
</html>
登录成功后的转账页面Transfer.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>转账</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/transfer" method="post">
<table>
<tr>
<td align="center" colspan="2">欢迎你!${user.username}</td>
</tr>
<tr>
<td align="right">用户名:</td>
<td><input type="text" name="username"/></td>
</tr>
<tr>
<td align="right">金额:</td>
<td><input type="text" name="sum"/></td>
</tr>
<tr>
<td/>
<td align="right"><input type="submit" value="转账"/></td>
</tr>
</table>
</form>
</body>
</html>
注册失败页面RegisterError.jsp:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>注册失败</title>
</head>
<body>
注册失败!
</body>
</html>
注册成功页面RegisterSuccess.jsp:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>注册成功</title>
</head>
<body>
注册成功!
</body>
</html>
转账失败页面TransferError.jsp:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>转账失败</title>
</head>
<body>
转账失败!
</body>
</html>
转账成功页面TransferSuccess.jsp:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>转账成功</title>
</head>
<body>
转账成功!
</body>
</html>
到这里,该转账系统基本实现,最终的目录结构如下:
运行截图:
可见admin账户成功向ysy账户转账50元。