SSM框架整合
SSM框架整合
SSM整合思路
Spring+SpringMVC+MyBatis,就是使用这三个框架的优势完成一些项目的构建。三个框架分贝对应了三层架构中的一层。
- Spring:业务逻辑层
- SpringMVC:视图层
- MyBatis:持久层
SSM整合,就需要把对象交给容器,让容器去创建项目中要使用的对象,让容器去创建项目中要使用的Java对象,目前有两个容器。
- Spring容器,管理service对象和dao对象,是业务逻辑层对象的容器
- SpringMVC容器,这个容器是管理控制器对象,也就是视图层对象。
两个容器的创建
Spring容器的创建:在web.xml文件中声明监听器 ContextLoaderListener,这个功能框架已经写好了,就是创建Spring的容器对象WebApplicationContext,在创建WebApplicationContext对象时,读取Spring配置文件,遇到<bean>标签或者注解,就可以创建service、dao对象,这些对象最终都放在Spring容器中。
SpringMVC容器的创建:在web.xml文件中声明中央调度器 DispatcherServlet,在这个servlet的init()方法中,创建了容器对象WebApplicationContext,在创建WebApplicationContext对象时,读取SpringMVC的配置文件,如果遇到相应的注解,则使用控制器对象,创建好的对象放到SpringMVC容器中。
SSM整合开发步骤
- 创建相应的数据库和表(命令行方式或者通过可视化工具都可)
- 在IDEA中使用maven、创建一个web项目
- 加入相关的依赖
- 在web.xml文件中声明容器对象
- 声明spring的监听器ContextLoaderListener:创建spring容器对象(service,dao)
- 声明springmvc的中央调度器DispatcherServlet:创建springmvc容器的对象(controller)
- 声明字符集过滤器CharacterEncodingFilter,解决post请求乱码的问题。
具体步骤
创建相应的表和数据库
创建一个add数据库,和一个student表,只有三个数据(id,name,age)
项目整体结构
加入相关依赖
<!-- servlet依赖 -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<!-- jsp依赖 -->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2.1-b03</version>
<scope>provided</scope>
</dependency>
<!-- jackson依赖 -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.0</version>
</dependency>
<!-- spring依赖 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
<!-- spring事务依赖 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
<!-- springmvc依赖 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
<!-- mybatis依赖 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.1</version>
</dependency>
<!-- mybatis-spring集成依赖 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.25</version>
</dependency>
<!-- mysql驱动依赖 -->
<!-- druid连接池依赖 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.6</version>
</dependency>
</dependencies>
使用的时候要和自己的版本一样呀,尤其是mysql的版本
在web.xml文件中,声明容器对象
<!-- 声明字符集过滤器 -->
<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>
<init-param>
<param-name>forceRequestEncoding</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>forceResponseEncoding</param-name>
<param-value>true</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:/conf/dispatcherServlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>DispatcherServlet</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<!-- 声明spring监听器 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:/conf/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
注意:字符集过滤器放到声明的第一个
创建包
dao,controller,service,entity(model,pojo)
编写mybatis,spring,springmvc的配置文件
- 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>
<!-- 设置日志 -->
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
<mappers>
<!-- 加载dao包下的所有mapper文件 -->
<package name="com.wang.dao"/>
</mappers>
</configuration>
这里有一个易错点,加载了相应的mapper文件,但是并没有把他放进编译后的文件中去,后续进行MyBatis的数据库操作时会找不到XxxxDao.xml文件的错误,给出的解决建议是将下面的代码复制到pom.xml文件中,是为了将src/main/java目录下的xml、properties文件都能被扫描到。
<build>
<resources>
<resource>
<directory>src/main/java</directory><!--所在的目录-->
<includes><!--包括目录下的.properties,.xml文件都会扫描到-->
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
</build>
- spring配置文件
<?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">
<!-- spring配置文件:声明service、dao、工具类、事务配置 -->
<!-- <!– 加载外部属性配置文件 –>-->
<!-- 声明组件扫描器 -->
<context:component-scan base-package="com.wang.service" />
<!-- 创建数据源 -->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="url" value="你应该会" />
<property name="username" value="你应该会" />
<property name="password" value="你应该会" />
</bean>
<!-- 创建SqlSessionFactory对象 -->
<bean id="factory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="classpath:/conf/mybatis.xml" />
</bean>
<!-- 创建SqlSession对象,通过反射机制加载dao接口对应的mapper文件 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="sqlSessionFactoryBeanName" value="factory" />
<property name="basePackage" value="com.wang.dao" />
</bean>
<!-- 事务配置 -->
</beans>
- 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: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 https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- springmvc配置文件:声明controller、视图解析器等web开发中的对象 -->
<!-- 声明组件扫描器 -->
<context:component-scan base-package="com.wang.controller" />
<!-- 声明视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<!-- 声明springmvc注解驱动 -->
<mvc:annotation-driven />
</beans>
编写java代码
- 实体类
public class Student {
private Integer id;
private String name;
private Integer age;
@Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
'}';
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
- dao接口和mapper文件
public interface StudentDao {
int insertStudent(Student student);
List<Student> selectStudent();
}
<?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.wang.dao.StudentDao">
<!-- 使用insert、update、delete、select标签编写sql语句 -->
<insert id="insertStudent">
insert into student(name,age) values (#{name},#{age})
</insert>
<select id="selectStudent" resultType="com.wang.entity.Student">
select id,name,age from student order by id
</select>
</mapper>
- service接口和实现类
public interface StudentService {
int addStudent(Student student);
List<Student> queryStudent();
}
@Service
public class StudentServiceImpl implements StudentService {
/**
* studentDao是引用类型,其对象是在spring配置文件中创建
* 引用类型自动注入,这里使用注解 @Autowired 或者 @Resource
*/
@Autowired
private StudentDao studentDao;
@Override
public int addStudent(Student student) {
int rows = studentDao.insertStudent(student);
return rows;
}
@Override
public List<Student> queryStudent() {
List<Student> list = studentDao.selectStudent();
return list;
}
}
创建一个控制器类(接受并处理请求)
@Controller
@RequestMapping(value = "/student")
public class StudentController {
/**
* 声明service对象,调用其中的方法
* 引用类型自动注入,这里使用注解 @Autowired 或者 @Resource
*/
@Autowired
private StudentService studentService;
//添加学生
@RequestMapping(value = "/addStudent.do")
public ModelAndView addStudent(Student student) {
ModelAndView mv=new ModelAndView();
//调用service,处理业务逻辑方法,把处理结果返回给用户
int rows=studentService.addStudent(student);
String msg="";
if (rows>0) {
msg="注册成功!!!";
mv.addObject("msg",student.getName() + "," + student.getAge());
mv.setViewName("success");
}else {
msg="注册失败!!!";
mv.addObject("msg",msg);
mv.setViewName("fail");
}
return mv;
}
@RequestMapping(value = "/queryStudent.do")
@ResponseBody
public List<Student> queryStudent() {
return studentService.queryStudent();
}
}
创建视图文件(直接贴代码)
- 首页(index.jsp)
<%@ page contentType="text/html;charset=utf-8" language="java" %>
<%
String basePath=request.getScheme() + "://" + request.getServerName()
+ ":" + request.getServerPort() + request.getContextPath() + "/";
%>
<html>
<head>
<base href="<%=basePath%>">
<title>SSM</title>
</head>
<body>
<div align="center">
<p>SSM整合开发的例子</p>
<table>
<tr>
<td><a href="addStudent.jsp">注册学生</a></td>
<td><br/></td>
<td><a href="queryStudent.jsp">查询学生</a></td>
</tr>
</table>
</div>
</body>
</html>
- 注册学生页面(addStudent.jsp)
<%@ page contentType="text/html;charset=utf-8" language="java" %>
<html>
<head>
<title>添加学生</title>
</head>
<body>
<div align="center">
<p>注册学生</p>
<form action="student/addStudent.do" method="post">
<table>
<tr>
<td>姓名:</td>
<td><input type="text" name="name"></td>
</tr>
<tr>
<td>年龄:</td>
<td><input type="text" name="age"></td>
</tr>
<tr>
<td>提交:</td>
<td><input type="submit" value="注册"></td>
</tr>
</table>
</form>
</div>
</body>
</html>
- 查询学生页面(queryStudent.jsp)
<%@ page contentType="text/html;charset=utf-8" language="java" %>
<%
String basePath=request.getScheme() + "://" + request.getServerName()
+ ":" + request.getServerPort() + request.getContextPath() + "/";
%>
<html>
<head>
<base href="<%=basePath%>">
<title>查询学生</title>
<script type="text/javascript" src="js/jquery-3.6.0.js"></script>
<script type="text/javascript">
$(function () {
$("#myBtn").on("click",function () {
$.ajax({
url: "student/queryStudent.do",
dataType: "json",
success : function (resp) {
$("#stuinfo").empty();
$.each(resp,function (i,n) {
$("#stuinfo").append("<tr><td>" + n.id + "</td>" +
"<td>" + n.name + "</td>" +
"<td>" + n.age + "</td></tr>");
})
}
})
})
})
</script>
</head>
<body>
<div align="center">
<p>查询学生 <button id="myBtn">获取学生信息</button></p>
<table>
<thead>
<tr>
<td>id</td>
<td>姓名</td>
<td>年龄</td>
</tr>
</thead>
<tbody id="stuinfo">
</tbody>
</table>
</div>
</body>
</html>
- 注册成功和失败的页面(succes.jsp fail.jsp),两者代码一样
<%@ page contentType="text/html;charset=utf-8" language="java" %>
<html>
<head>
<title>$</title>
</head>
<body>
<h3>结果:${msg}</h3>
</body>
</html>
运行即可
注:
本篇文章完全参考:
SSM整合——简单的小项目实战_张起灵-小哥的博客-CSDN博客_ssm项目
部分参考:
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】Flutter适配HarmonyOS 5知识地图,实战解析+高频避坑指南
【推荐】凌霞软件回馈社区,携手博客园推出1Panel与Halo联合会员
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· C#多线程编程精要:从用户线程到线程池的效能进化论
· 如何反向绘制出 .NET程序 异步方法调用栈
· 领域驱动设计实战:聚合根设计与领域模型实现
· 突破Excel百万数据导出瓶颈:全链路优化实战指南
· 如何把ASP.NET Core WebApi打造成Mcp Server
· C#开发的Panel滚动分页控件 - 开源研究系列文章
· ShadowSql之开源不易
· 如何反向绘制出 .NET程序 异步方法调用栈
· C#多线程编程精要:从用户线程到线程池的效能进化论
· 上周热点回顾(5.5-5.11)