SSM整合开发
一、整体思路
SSM: SpringMVC + Spring + MyBatis.
SpringMVC:视图层,界面层,负责接收请求,显示处理结果的。
Spring:业务层,管理service,dao,工具类对象的。
MyBatis:持久层, 访问数据库的
用户发起请求--SpringMVC接收--Spring中的Service对象--MyBatis处理数据
SSM整合也叫做SSI (IBatis也就是mybatis的前身), 整合中有容器。
- 第一个容器SpringMVC容器, 管理Controller控制器对象的。
- 第二个容器Spring容器,管理Service,Dao,工具类对象的
我们要做的把使用的对象交给合适的容器创建,管理。 把Controller还有web开发的相关对象交给springmvc容器, 这些web用的对象写在springmvc配置文件中
service,dao对象定义在spring的配置文件中,让spring管理这些对象
springmvc容器和spring容器是有关系的,关系已经确定好了
springmvc容器是spring容器的子容器, 类似java中的继承。 子可以访问父的内容
在子容器中的Controller可以访问父容器中的Service对象, 就可以实现controller使用service对象
实现步骤:
-
使用ssm的mysql库, 表使用student(id auto_increment, name, age)
-
新建maven web项目
-
加入依赖
springmvc,spring,mybatis三个框架的依赖,jackson依赖,mysql驱动,druid连接池
jsp,servlet依赖 -
写web.xml
- 注册DispatcherServlet ,目的:1.创建springmvc容器对象,才能创建Controller类对象。2.创建的是Servlet,才能接受用户的请求。
- 注册spring的监听器:ContextLoaderListener,目的: 创建spring的容器对象,才能创建service,dao等对象。
- 注册字符集过滤器,解决post请求乱码的问题
-
创建包, Controller包, service ,dao,实体类包名创建好
-
写springmvc,spring,mybatis的配置文件
- springmvc配置文件
- spring配置文件
- mybatis主配置文件
- 数据库的属性配置文件
-
写代码, dao接口和mapper文件, service和实现类,controller, 实体类。
-
写jsp页面
二、SSM整合注解开发
需求:完成学生的注册和信息浏览
1. 建立Student
2. 建立Web工程
通过maven
3. maven依赖
<?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">
<modelVersion>4.0.0</modelVersion>
<groupId>com.md</groupId>
<artifactId>07-ssm</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<!--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>
<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>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.9</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.12</version>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>src/main/java</directory><!--所在的目录-->
<includes><!--包括目录下的.properties,.xml 文件都会扫描到-->
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
</build>
</project>
4. 定义程序结构
5. 编写配置文件
jdbc属性配置文件jdbc.properties
jdbc.url=jdbc:mysql://localhost:3306/ssm
jdbc.username=root
jdbc.password=123456
jdbc.maxActive=20
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">
<!--spring的配置文件,声明service、dao、工具类对象-->
<!--注册组件扫描器-->
<!--声明service的注解@Service所在的包名位置-->
<context:component-scan base-package="com.md.service"/>
<!--声明数据源,连接数据库-->
<context:property-placeholder location="classpath:conf/jdbc.properties"/>
<bean id="myDataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}" />
<property name="maxActive" value="${jdbc.maxActive}" />
</bean>
<!--SqlSessionFactory-->
<bean id="SqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="myDataSource"/>
<property name="configLocation" value="classpath:/conf/mybatis.xml"/>
</bean>
<!--创建 dao对象-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="sqlSessionFactoryBeanName" value="SqlSessionFactory"/>
<!--指定包名,包名是dao接口所在的包名,dao默认对象的名称:是接口名字的首字母小写-->
<property name="basePackage" value="com.md.dao"/>
</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.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相关的对象-->
<!-- 注册组件扫描器,指定@Controller注解所在的类-->
<context:component-scan base-package="com.md.controller"/>
<!-- 指定视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
<!--注册注解驱动
1. 响应ajax请求,返回json
2. 解决静态资源访问问题
-->
<mvc:annotation-driven/>
</beans>
mybatis的配置文件 , mybatis.xml
<?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>-->
<!--设置别名,在mapper.xml文件中,返回值不用在写包名了,直接写类名即可-->
<typeAliases>
<package name="com.md.domain"/>
</typeAliases>
<!-- sql映射文件的位置 -->
<mappers>
<!--name是包名,这个包中所有mapper.xml一次加载
使用package的要求
1. mapper文件名称和dao接口名称必须完全一样
2. mapper文件和dao接口必须在同一目录
-->
<package name="com.md.dao"/>
</mappers>
</configuration>
6. 定义web.xml
由于自动生成的是这样的,版本太低,需要换成现在高的版本,直接把之前写好的复制过来就行
换成这样
- 注册 ContextLoaderListener
- 注册 DisatcherServlet
- 注册字符集过滤器
- 同时创建 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">
<!--注册中央调度器-->
<servlet>
<servlet-name>springmvc</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>springmvc</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>
<!--注册字符集过滤器-->
<!--声明过滤器,解决post请求乱码的问题-->
<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>
</web-app>
7. 实体类
package com.md.domain;
/**
* @author MD
* @create 2020-08-13 20:21
*/
public class Student {
private Integer id;
private String name;
private Integer age;
public Student() {
}
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;
}
@Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
'}';
}
}
8. Dao接口和映射文件
都在是dao包下,且文件名相同
package com.md.dao;
import com.md.domain.Student;
import java.util.List;
/**
* @author MD
* @create 2020-08-13 20:22
*/
public interface StudentDao {
int insertStudent(Student student);
List<Student> selectStudents();
}
StudentDao.xml
<?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.md.dao.StudentDao">
<insert id="insertStudent" >
insert into student(name,age) values(#{name} , #{age})
</insert>
<!--设置了别名,这里返回值直接写类名-->
<select id="selectStudents" resultType="Student">
select id, name , age from student
</select>
</mapper>
9. Service接口和实现类
package com.md.service;
import com.md.domain.Student;
import java.util.List;
/**
* @author MD
* @create 2020-08-13 20:31
*/
public interface StudentService {
int addStudent(Student student);
List<Student> findStudents();
}
实现类
package com.md.service.impl;
import com.md.dao.StudentDao;
import com.md.domain.Student;
import com.md.service.StudentService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
/**
* @author MD
* @create 2020-08-13 20:32
*/
@Service
public class StudentServiceImpl implements StudentService {
// 引用数据类型的自动注入@Resource、@Autowired
@Resource
private StudentDao studentDao;
@Override
public int addStudent(Student student) {
int nums = studentDao.insertStudent(student);
return nums;
}
@Override
public List<Student> findStudents() {
return studentDao.selectStudents();
}
}
10. 处理器
在controller包下
package com.md.controller;
import com.md.domain.Student;
import com.md.service.StudentService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import javax.annotation.Resource;
import java.util.List;
/**
* @author MD
* @create 2020-08-13 20:37
*/
@Controller
@RequestMapping("/student")
public class StudentController {
// 自动注入
@Resource
private StudentService service;
// 注册学生
@RequestMapping("/addStudent.do")
public ModelAndView addStudent(Student student){
ModelAndView mv = new ModelAndView();
String tips = "注册失败";
// 调用service处理student
int nums = service.addStudent(student);
if (nums > 0){
tips = "注册成功";
}
// 添加数据,指定页面
mv.addObject("tips",tips);
mv.setViewName("result");
return mv;
}
// 处理查询,响应ajax
@RequestMapping("/queryStudent.do")
@ResponseBody
public List<Student> queryStudent(){
List<Student> students = service.findStudents();
// 会被框架转为json的数组
return students;
}
}
11. 首页
index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
String basePath = request.getScheme() + "://" +
request.getServerName() + ":" + request.getServerPort() +
request.getContextPath() + "/";
%>
<html>
<head>
<title>功能入口</title>
<base href="<%=basePath%>">
</head>
<body>
<div align="center">
<h2>SSM整合</h2>
<table>
<tr>
<td> <a href="addStudent.jsp">学生注册</a> </td>
</tr>
<br>
<tr>
<td><a href="listStudent.jsp">学生信息</a> </td>
</tr>
</table>
</div>
</body>
</html>
12. 注册页面
addStudent.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
String basePath = request.getScheme() + "://" +
request.getServerName() + ":" + request.getServerPort() +
request.getContextPath() + "/";
%>
<html>
<head>
<title>学生注册</title>
<base href="<%=basePath%>">
</head>
<body>
<div align="center">
<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>
13. 注册结果
在/WEB-INF/jsp/result.jsp
<%--
Created by IntelliJ IDEA.
User: MD
Date: 2020/8/13
Time: 20:45
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>注册结果:${tips}</h1>
</body>
</html>
14. 浏览页面
listStudent.jsp
<%--
Created by IntelliJ IDEA.
User: MD
Date: 2020/8/13
Time: 21:10
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
String basePath = request.getScheme() + "://" +
request.getServerName() + ":" + request.getServerPort() +
request.getContextPath() + "/";
%>
<html>
<head>
<title>学生信息</title>
<base href="<%=basePath%>">
<script type="text/javascript" src="js/jquery-3.4.1.js"></script>
<script type="text/javascript" >
$(function () {
// 在当前的页面加载后执行loadStudent函数
loadStudent();
$("#btn").click(function () {
loadStudent();
});
});
// 自定义函数
function loadStudent() {
$.ajax({
url:"student/queryStudent.do",
type:"get",
dataType:"json",
success:function (data) {
// 清除旧数据
$("#info").html("");
$.each(data,function (i,n) {
// 添加新数据
$("#info").append("<tr>")
.append("<td>"+n.id+"</td>")
.append("<td>"+n.name+"</td>")
.append("<td>"+n.age+"</td>")
.append("</tr>")
})
}
});
}
</script>
</head>
<body>
<div align="center">
<table>
<thead>
<tr>
<td>学号</td>
<td>姓名</td>
<td>年龄</td>
</tr>
</thead>
<tbody id="info">
</tbody>
</table>
<input type="button" id="btn" value="查询数据">
</div>
</body>
</html>
此时再配置Tomcat运行即可,之后再添加新的功能
-------------------------------------------
你闻讯而来,我大喜过望,我在这等你,你又在哪呢?喜欢的话加一个“关注”呗!
如果觉得这篇文章对你有小小的帮助的话,记得在右下角点个“推荐”哦,博主在此感谢!