SSM整合(二)
1.整合思路
SSM框架工作时,Spring、Spring MVC和MyBatis的分工如下。
(1)Spring负责事务管理,可以管理数据持久层的Mapper Bean和业务逻辑层的Service Bean。由于Mapper Bean和Service Bean都在Spring容器中,因此在业务逻辑层可以直接调用Mapper Bean。
(2)Spring MVC负责管理表现层的Controller Bean。由于Spring MVC容器是Spring容器的子容器,因此在表现层可以调用Spring容器中的Service Bean。
(3)MyBatis负责与数据库交互。
根据上述的分工描述,SSM框架的整合思路如下。
(1)搭建项目环境。首先在数据库中搭建项目对应的数据库环境,然后创建Web项目,并引入项目所需的依赖包。
(2)创建接口和类。首先创建实体类,然后创建数据持久层对应的接口或映射文件、业务逻辑层对应的接口及其实现类和表现层对应的控制器类。
(3)创建视图文件。创建表现层对应的视图文件,在浏览器中展示执行操作的结果。
(4)整合Spring和MyBatis。创建Spring的配置文件,配置Spring的相关信息,然后配置MyBatis的数据源信息和与MyBatis相关的Bean。
(5)整合Spring和Spring MVC。创建Spring MVC的配置文件,配置Spring MVC的相关信息,并在项目的web.xml文件中加载Spring和Spring MVC的配置文件。
2.搭建项目:
创建包:
控制层:controller
服务层:service
持久层:dao
实体类:domain
工具类:utils
3.导入jar包
<dependencies>
<!--单元测试-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!--spring-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.30</version>
</dependency>
<!--spring mvc-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.30</version>
</dependency>
<!--mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.4</version>
</dependency>
<!--spring 整合 mybatis 的 jar-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.4</version>
</dependency>
<!--mysql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.28</version>
</dependency>
<!--数据库连接池-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.6</version>
</dependency>
<!--lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.32</version>
</dependency>
<!--jdbc-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.30</version>
</dependency>
</dependencies>
4.准备测试数据
4.1创建数据库、表
DROP TABLE IF EXISTS `tb_student`;
CREATE TABLE `tb_student` (
`id` int NOT NULL AUTO_INCREMENT,
`stu_name` varchar(20) COLLATE utf8_bin NOT NULL,
`stu_pwd` varchar(20) COLLATE utf8_bin NOT NULL,
`stu_email` varchar(20) COLLATE utf8_bin NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb3 COLLATE=utf8_bin;
-- ----------------------------
-- Records of tb_student
-- ----------------------------
INSERT INTO `tb_student` VALUES ('3', '李白', '123', 'libai@123');
INSERT INTO `tb_student` VALUES ('4', '杜甫', '456', 'dufu@123');
4.2编写实体类
@Data
public class Student {
private Integer id;
private String stuName;
private String stuPwd;
private String stuEmail;
}
5.编写dao层的代码
@Repository
public interface StudentDao {
//查询所有的方法
@Select("select * from tb_student")
public List<Student> queryAll();
//添加
@Insert("insert into tb_student values (null,#{stuName},#{stuPwd},#{stuEmail})")
public int addStudent(Student stu);
//删除
@Delete("delete from tb_student where id = #{id}")
public int delStudent(int id);
//修改@Update()
public int updateStudent(Student stu);
@Select("select * from tb_student where id = #{id}")
public Student findById(int id);
}
6.编写service层
6.1编写接口(定义规范)
public interface StudentService {
//查询所有的方法
public List<Student> findAll();
//添加
public boolean addStudent(Student stu);
//删除
public boolean delStudent(int id);
//修改
public boolean updateStudent(Student stu);
public Student findById(int id);
}
6.2实现接口
@Service
public class StudentServiceImpl implements StudentService {
//注入 dao层的对象
@Autowired //自动类型注入
StudentDao studentDao;
public List<Student> findAll() {
//调用dao层的方法
List<Student> students = studentDao.queryAll();
return students;
}
//添加
public boolean addStudent(Student stu) {
return studentDao.addStudent(stu) >0;
}
//删除
public boolean delStudent(int id) {
return studentDao.delStudent(id)>0;
}
//修改
public boolean updateStudent(Student stu) {
return studentDao.updateStudent(stu)>0;
}
//通过Id查询
public Student findById(int id) {
return studentDao.findById(id);
}
}
7.编写controller
//controller---service----->dao
@Controller
public class StudentController {
//自动类型注入--- 多态
@Autowired
StudentService studentService;
@RequestMapping("list")
public String list(Model model){
System.out.println(123);
//调用service
List<Student> all = studentService.findAll();
//存数据
model.addAttribute("all",all);
//跳转页面
return "list";
}
@RequestMapping("add")
public String add(Student student){
//调用service
boolean b = studentService.addStudent(student);
return "redirect:list";
}
//删除
@RequestMapping("del/{id1}")
public String del(@PathVariable("id1") int id){
boolean b = studentService.delStudent(id);
return "redirect:/list";
}
//通过Id查询用户
@RequestMapping("findById")
public String findById(int id,Model model){
Student student = studentService.findById(id);
model.addAttribute("stu",student);
//转发到修改的页面
return "updateJsp";
}
//修改的方法
@RequestMapping("updateStdent")
public String updateStdent(Student student){
boolean b = studentService.updateStudent(student);
return "redirect:list";
}
}
8.编写springmvc的配置文件
<?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">
<!--包扫描-->
<context:component-scan base-package="com.yngm.ssm.controller"/>
<!--视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!--前缀-->
<property name="prefix" value="/WEB-INF/"/>
<!--后缀-->
<property name="suffix" value=".jsp"/>
</bean>
<!--注解驱动-->
<mvc:annotation-driven/>
</beans>
9.编写spring的配置文件
9.1数据源属性文件(db.properties)
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis_db
jdbc.username=root
jdbc.pwd=abc123
<?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">
<!--包扫描,除了controller的包,都需要扫描-->
<context:component-scan base-package="com.yngm.ssm">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!--引入属性文件-->
<context:property-placeholder location="classpath:db.properties"/>
<!--配置数据源-->
<bean class="com.alibaba.druid.pool.DruidDataSource" id="dataSource">
<!--驱动-->
<property name="driverClassName" value="${jdbc.driver}"/>
<!--路径-->
<property name="url" value="${jdbc.url}"/>
<!--用户名-->
<property name="username" value="${jdbc.username}"/>
<!--密码-->
<property name="password" value="${jdbc.pwd}"/>
</bean>
<!--配置sqlSession对象-->
<bean class="org.mybatis.spring.SqlSessionFactoryBean">
<!--加载数据源-->
<property name="dataSource" ref="dataSource"/>
<!--读取映射文件-->
<property name="mapperLocations" value="classpath:com/yngm/ssm/mapper/*.xml"/>
<!--配置类型别名-->
<property name="typeAliasesPackage" value="com.yngm.ssm.domain"/>
<!--配置开启驼峰命名-->
<property name="configuration">
<bean class="org.apache.ibatis.session.Configuration">
<!--开启驼峰命名-->
<property name="mapUnderscoreToCamelCase" value="true"/>
</bean>
</property>
</bean>
<!--配置dao层接口的代理对象-扫描dao层的包-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.yngm.ssm.dao"/>
</bean>
</beans>
10.编写映射文件
<?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="com.yngm.ssm.dao.StudentDao">
<!--修改 动态sql-->
<update id="updateStudent">
update tb_student
<set>
<if test="stuName!=null">
stu_name=#{stuName},
</if>
<if test="stuPwd!=null">
stu_pwd=#{stuPwd},
</if>
<if test="stuEmail!=null">
stu_email=#{stuEmail},
</if>
</set>
where id=#{id}
</update>
</mapper>
11.编写web.xml
加载spring和springmvc的配置文件
<?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">
<!--监听器,读spring的配置文件-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--配置Spring容器,指定Spring的配置文件-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:app.xml</param-value>
</context-param>
<!--前端控制器-->
<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:springmvc.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</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>
</web-app>
12.编写页面,启动项目
12.1首页
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<body>
<h2>理论+实践!SSM整合成功!</h2>
<a href="list">查询所有</a>
<form action="add" method="post">
账号:<input type="text" name="stuName" /> <br>
密码: <input type="text" name="stuPwd" /> <br>
邮箱: <input type="text" name="stuEmail" /> <br>
<input type="submit" value="提交">
</form>
</body>
</html>
12.2.展示数据
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<%--接收后台的数据 使用表格展示 --%>
<table border="1" cellspacing="0">
<tr>
<th>编号</th>
<th>用户名</th>
<th>密码</th>
<th>邮箱</th>
<th>操作</th>
</tr>
<c:forEach items="${all}" var="stu">
<tr>
<td>${stu.id}</td>
<td>${stu.stuName}</td>
<td>${stu.stuPwd}</td>
<td>${stu.stuEmail}</td>
<td>
<a href="del/${stu.id}">删除</a>
<a href="findById?id=${stu.id}">修改</a>
</td>
</tr>
</c:forEach>
</table>
</body>
</html>
12.3.修改页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>修改数据</h1>
<form action="updateStdent" method="post">
<input type="hidden" name="id" value="${stu.id}">
账号:<input type="text" name="stuName" value="${stu.stuName}" /> <br>
密码: <input type="text" name="stuPwd" value="${stu.stuPwd}" /> <br>
邮箱: <input type="text" name="stuEmail" value="${stu.stuEmail}" /> <br>
<input type="submit" value="提交">
</form>
</body>
</html>