目录

  • 前言
  • 一、搭建 SSM 开发环境
    • Maven pom.xml
    • 配置 web.xml
  • 二、SSM 整合注解式开发
    • 建表
    • 定义包、组织程序的结构
    • 编写配置文件
    • 定义 web.xml
    • 实体类 Student
    • 定义 Dao 接口 与 sql 映射文件
    • 定义 Service 接口与实现类
    • 处理器定义
    • 定义视图-首页文件 --- index.jsp
    • 注册学生页面 --- addStudent.jsp
    • 浏览学生页面 --- listStudent.jsp
    • 注册成功与失败界面
  • 三、测试

前言

SSM 编程,即 SpringMVC + Spring + MyBatis 整合,是当前最为流行的 JavaEE 开发技术架构。其实 SSM 整合的实质,仅仅就是将 MyBatis整合入 Spring。因为 SpringMVC原本就是Spring的一部分,不用专门整合。

SSM 整合的实现方式可分为两种:基于 XML 配置方式,基于注解方式。


一、搭建 SSM 开发环境

Maven pom.xml

  • 依赖
 <!--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>
<!--springmvc-->
<dependency><groupId>org.springframework</groupId><artifactId>spring-webmvc</artifactId><version>5.2.5.RELEASE</version>
</dependency>
<!--事务的-->
<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>
<!--aspectj 依赖-->
<dependency><groupId>org.springframework</groupId><artifactId>spring-aspects</artifactId><version>5.2.5.RELEASE</version>
</dependency>
<!--jackson-->
<dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-core</artifactId><version>2.9.0</version>
</dependency>
<dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId><version>2.9.0</version>
</dependency>
<!--mybatis 和 spring 整合的-->
<dependency><groupId>org.mybatis</groupId><artifactId>mybatis-spring</artifactId><version>1.3.1</version>
</dependency>
<!--mybatis-->
<dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.5.1</version>
</dependency>
<!--mysql 驱动-->
<dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.28</version>
</dependency>
<!--druid-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId><version>1.1.12</version>
</dependency>
  • 插件

用来定义除了 .java 文件之外,其他资源文件位置,放在 <bulid/>

<resources><resource><directory>src/main/java</directory><includes><include>**/*.xml</include><include>**/*.properties</include></includes></resource><resource><directory>src/main/resources</directory><includes><include>**/*.xml</include><include>**/*.properties</include></includes></resource>
</resources>

配置 web.xml

  • 注册 ContextLoaderListener 监听器
<!-- 注册 spring 的监听器  -->
<context-param><param-name>contextConfigLocation</param-name><param-value>classpath:applicationContext.xml</param-value>
</context-param>
<listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

注册 ServletContext 监听器的实现类 ContextLoaderListener,用于创建 Spring 容器及将创建好的 Spring 容器对象放入到 ServletContext 的作用域中。

  • 注册字符集过滤器
<!-- 注册字符集过滤器 -->
<filter><filter-name>charaterEncodingFilter</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>charaterEncodingFilter</filter-name><url-pattern>/*</url-pattern>
</filter-mapping>

注册字符集过滤器,用于解决请求参数中携带中文时产生乱码问题。

  • 配置中央调度器

配置中央调度器时需要注意,SpringMVC 的配置文件名与其它 Spring 配置文件名不相同。这样做的目的是 Spring 容器创建管理 Spring 置文件中的 bean, SpringMVC 容器中负责视图层 bean 的初始化。

<!-- 注册 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: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>

二、SSM 整合注解式开发

项目:ssm

需求:完成学生注册和信息浏览

建表

建立 student 表

定义包、组织程序的结构

jsp文件

编写配置文件

JDBC 属性配置文件 db.properties

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/ssm?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone = GMT
user=root
password=aszhuo123

Spring 配置文件 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"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"><!-- 注册组件扫描器    --><context:component-scan base-package="com.fancy.service"></context:component-scan><!-- 引入属性配置文件   --><context:property-placeholder location="db.properties"></context:property-placeholder><!-- 配置阿里的Druid数据库连接池    --><bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"><property name="url" value="${url}"></property><property name="username" value="${user}"></property><property name="password" value="${password}"></property></bean><!-- 注册 SqlSessionFactoryBean   --><bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"><property name="dataSource" ref="dataSource"></property><property name="configLocation" value="mybatis.xml"></property></bean><!-- 动态代理对象   --><bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"><property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property><property name="basePackage" value="com.fancy.dao"></property></bean>
</beans>

Springmvc 配置文件 dispatcherServlet.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:mvc="http://www.alibaba.com/schema/stat"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.alibaba.com/schema/stat http://www.alibaba.com/schema/stat.xsd"><!-- 注册组件扫描器base-package : 指定 @Controller 注解所在包--><context:component-scan base-package="com.fancy.controller"></context:component-scan><!--  指定视图解析器   --><bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"><!-- 前缀与后缀   --><property name="prefix" value="/WEB-INF/view"></property><property name="suffix" value=".jsp"></property></bean><!-- 注册注解驱动  --><mvc:annotation-driven/>
</beans>

MyBatis 配置文件 mybatis.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration><!--  配置别名  --><typeAliases><package name="com.fancy.domain"/></typeAliases><!-- 指定sql映射文件    --><mappers><package name="com.fancy.dao"/></mappers>
</configuration>

定义 web.xml

分为以下四步

1)注册 ContextLoaderListener
2)注册 DisatcherServlet
3)注册字符集过滤器
4)同时创建 Spring 的配置文件和 SpringMVC 的配置文件

我们之前已经定义好了

实体类 Student

package com.fancy.domain;public class Student {private Integer id;private String name;private int age;public Student() {}public Student(Integer id, String name, int age) {this.id = id;this.name = name;this.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 int getAge() {return age;}public void setAge(int age) {this.age = age;}
}

定义 Dao 接口 与 sql 映射文件

Dao 接口

package com.fancy.dao;import com.fancy.domain.Student;import java.util.List;public interface StudentDao {int insertStudent(Student student);List<Student>  selectAllStudents();
}

sql 映射文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.fancy.dao.StudentDao"><insert id="insertStudent">insert into student(name, age) values(#{name}, #{age})</insert><select id="selectStudentByPage" resultType="Student">select id, name, age from student order by id  desc </select>
</mapper>

定义 Service 接口与实现类

Service 接口

package com.fancy.service;import com.fancy.domain.Student;import java.util.List;public interface StudentService {int addStudent(Student student);List<Student> findStudents();
}

Service 实现类

package com.fancy.service;import com.fancy.dao.StudentDao;
import com.fancy.domain.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;import java.util.List;@Service(value = "studentService")
public class StudentServiceImpl implements StudentService {// 引用类型 @Autowired , @Resource, byType | byName// byType@Autowiredprivate StudentDao stuDao;@Overridepublic int addStudent(Student student) {return stuDao.insertStudent(student);}@Overridepublic List<Student> findStudents(){return stuDao.selectAllStudents();}
}

处理器定义

package com.fancy.controller;import com.fancy.domain.Student;
import com.fancy.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;@Controller
@RequestMapping("/student")
public class StudentController {@Autowiredprivate StudentService studentService;@RequestMapping("/addStudent.do")public ModelAndView addStudent(Student student) {ModelAndView mv = new ModelAndView();// 调用 Service 处理业务, 将结果放入到 ModelAndView 中int rows = studentService.addStudent(student);if (rows > 0) {mv.addObject("msg", "注册成功");mv.setViewName("success");} else {mv.addObject("msg", "注册失败");mv.setViewName("fail");}return mv;}
}

定义视图-首页文件 — index.jsp

指定路径

<% String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/"; %>

指定base标签

<base href="<%=basePath%>">

页面总代码

<%@ 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</title>
</head>
<body><div align="center"><p>SSM整合开发 -- 实现 student 表的操作</p><img src="data:images/ssm.jpg"><table cellpadding="0" cellspacing="0"><tr><td><a href="addStudent.jsp">注册学生</a></td></tr><tr><td>&nbsp;</td></tr><tr><td><a href="listStudent.jsp">查询学生</a></td></tr></table></div>
</body>
</html>

注册学生页面 — addStudent.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><title>Title</title>
</head>
<body><div align="center"><p>学生注册界面</p><form action="/MyWeb/student/addStudent.do"><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> &nbsp; </td><td><input type="submit" value="注册"></td></tr></table></form></div>
</body>
</html>

浏览学生页面 — listStudent.jsp

页面代码

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><title>Title</title>
</head>
<body><div align="center"><p>查询学生数据</p><table><thead><tr><td>id</td><td>姓名</td><td>年龄</td></tr></thead><tbody id="stubody"></tbody></table></div>
</body>
</html>

引入 JQuery


js 发起 ajax

<script type="text/javascript">$(function (){stuinfo();})function stuinfo() {$.ajax({url:"student/queryStudent.do",type:"post",dataType:"json",success:function (resp) {$("#stubody").html("");$.each(resp, function(i, n){$("#stubody").append("<tr>").append("<td>" + n.id + "</td>").append("<td>" + n.name + "</td>").append("<td>" + n.age + "</td>").append("</tr>")})}})}
</script>

注册成功与失败界面

view 目录下的页面结构


success.jsp 页面


fail.jsp 页面

三、测试

首页

注册界面

注册结果

查询界面

如果出现 500 错误,检查 maven 依赖是否冲突

无红线即没有冲突

SpringMVC(三) --------- SSM 整合开发案例相关推荐

  1. 阿里开发规范文档_华为阿里等技术专家15年开发经验总结:SSM整合开发实战文档...

    前言 Spring自2002年诞生至今,已有近20年的历史,虽然几经变迁,但始终在继续发展和精进.Spring目前由Pivotal维护和开发. Pivotal是PaaS(平台即服务)的领导者,也是消息 ...

  2. 框架-springmvc(ssm整合)

    第一天 课程安排: 1.什么是springMVC? 2.springMVC框架原理前端控制器.处理器映射器.处理器适配器.视图解析器. 3.springMVC入门程序目的:对前端控制器.处理器映射器. ...

  3. SpringMVC和SSM整合步骤(最详细)

    文章目录 一.MVC架构 1.概念 2.好处 二.SpringMVC的具体实现步骤 1.xml配置版 1.1 在pom.xml文件中添加依赖 1.2 配置web.xml 1.3 配置springmvc ...

  4. SpringMVC以及SSM整合

    本人才疏学浅,如有错误欢迎批评!转载请注明出处:https://www.cnblogs.com/lee-yangyaozi/p/11226145.html SpringMVC概述 Spring Web ...

  5. SSM整合开发学习笔记

    1. 整合配置 1.1 配置项目依赖 <?xml version="1.0" encoding="UTF-8"?><project xmlns ...

  6. 手把手教你SSM整合开发办公系统(OA)——报销单(含源码)

    文章目录 前言 项目展示 技能要求 一.开始前的准备 1.OA系统是什么? 2.人员权利与报销流程 3.数据库设计 4.创建项目及作用说明 5.包与全局变量配置 6.编写过滤器 7.静态资源的复制与请 ...

  7. SSM 整合开发初见面

    SpringMVC是Spring其中的一个模块,我们直接使用即可: SSM的整合:将Mybatis 和 Spring进行整合: >类的根路径:classpath,也就是classes文件夹 sr ...

  8. spring + springmvc + mybatis + mysql 整合使用案例

    ssm框架对于大多数的java开发的小伙伴们并不陌生吧,已经成为各类java开发的首选框架,想当初,为了整合一个通用的ssm框架模板煞费苦心,一度陷入各种配置文件,各种xml的配置苦海里不能自拔,一旦 ...

  9. liferay + struts2 + spring + ibatis整合开发案例

    1 首先 开发的工程和案例是根据另外一个人博客进行开发的 开发地址如下:  http://sweat89.iteye.com/blog/1686206 2 按照这位前辈的开发,搭建好后发现有很多问题, ...

  10. OA办公自动化系统~~~SSM整合开发

    简介:    OA( Office Automation System)办公自动化系统是一个企业用来管理日常事务的系统,它一般用来管理各种流程(报销.请假. . .)审批,通讯录.日程.文件管理.通知 ...

最新文章

  1. 这或许是东半球分析十大排序算法最好的一篇文章
  2. Selenium启动不同浏览器
  3. pythonurllib模块-Python中的urllib模块使用详解
  4. leetcode 之Single Number(13)
  5. 将一个压缩文件分成多个压缩文件;RAR文件分卷
  6. 【校招面试 之 C/C++】第12题 C++ 重载、重写和重定义
  7. android 获取默认程序图标,android – PackageManager.getApplicationIcon()返回默认图标?...
  8. 来,我们谈谈怎么学好计算机科学与技术
  9. 数据结构期末复习之交换排序
  10. 编程的本质--深入理解类型系统/泛型/函数式编程/面向对象编程
  11. Linux内核小笔记:spin_lock锁内不能使用sleep休眠
  12. mysql 5.7 升级 8.0_MySQL5.7升级到8.0过程详解
  13. 【动态主席树】ZOJ 2112【树状数组+主席树】
  14. linux pwm 调屏_linux驱动---bl_pwm驱动与backlight class实现背光调整
  15. Essay Writing Guide
  16. 父亲节手抄报内容大全
  17. 同为标准版 OPPO Reno7和华为nova9怎么选,这几点要搞清楚
  18. 11台计算机的英语,世界第一台计算机英文缩写名为
  19. 2023-02-11:给你两个整数 m 和 n 。构造一个 m x n 的网格,其中每个单元格最开始是白色, 请你用 红、绿、蓝 三种颜色为每个单元格涂色。所有单元格都需要被涂色, 涂色方案需要满足:
  20. 大数据算法培养计划!

热门文章

  1. 无法启动此程序,因为计算机中丢失MSVCR71.dll.丢失的解决方法分享
  2. ShaderForge - 纹理旋转
  3. 如何将pdf文件压缩变小?
  4. 拼多多token是什么?如何提取及写入?
  5. myeclipse出现Severs栏不显示Tomcat
  6. 现代ADC中采样率往往远低于输入信号带宽
  7. 薇娅直播卖火箭,B 站酒泉发卫星,航天贴标生意凭什么?
  8. 《python3网络爬虫开发实战》学习笔记:pyspider报错Exception: HTTP 599: SSL certificate problem...
  9. jdbc——mysql学习
  10. 舒尔特 Pro ,专业训练注意力专注力