阅读本文前,请您先点击上面的蓝色字体,再点击“关注”,这样您就可以继续免费收到最新文章了。每天都有分享。完全是免费订阅,请放心关注。注:本文转载自网络,不代表本平台立场,仅供读者参考,著作权属归原创者所有。我们分享此文出于传播更多资讯之目的。如有侵权,请在后台留言联系我们进行删除,谢谢!
一、整体思路
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.0modelVersion>
<groupId>com.mdgroupId>
<artifactId>07-ssmartifactId>
<version>1.0-SNAPSHOTversion>
<packaging>warpackaging>
<properties>
<project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
<maven.compiler.source>1.8maven.compiler.source>
<maven.compiler.target>1.8maven.compiler.target>
properties>
<dependencies>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.11version>
<scope>testscope>
dependency>
<dependency>
<groupId>javax.servletgroupId>
<artifactId>javax.servlet-apiartifactId>
<version>3.1.0version>
<scope>providedscope>
dependency>
<dependency>
<groupId>javax.servlet.jspgroupId>
<artifactId>jsp-apiartifactId>
<version>2.2.1-b03version>
<scope>providedscope>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webmvcartifactId>
<version>5.2.5.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-txartifactId>
<version>5.2.5.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-jdbcartifactId>
<version>5.2.5.RELEASEversion>
dependency>
<dependency>
<groupId>com.fasterxml.jackson.coregroupId>
<artifactId>jackson-coreartifactId>
<version>2.9.0version>
dependency>
<dependency>
<groupId>com.fasterxml.jackson.coregroupId>
<artifactId>jackson-databindartifactId>
<version>2.9.0version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatis-springartifactId>
<version>1.3.1version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.5.1version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>5.1.9version>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>druidartifactId>
<version>1.1.12version>
dependency>
dependencies>
<build>
<resources>
<resource>
<directory>src/main/javadirectory>
<includes>
<include>**/*.propertiesinclude>
<include>**/*.xmlinclude>
includes>
<filtering>falsefiltering>
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">
<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>
<bean id="SqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="myDataSource"/>
<property name="configLocation" value="classpath:/conf/mybatis.xml"/>
bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="sqlSessionFactoryBeanName" value="SqlSessionFactory"/>
<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">
<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>
<mvc:annotation-driven/>
beans>
mybatis的配置文件 , mybatis.xml
<?xml version="1.0" encoding="UTF-8" ?>
span style="box-sizing: border-box;border-width: 0px;border-style: initial;border-color: initial;">configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<typeAliases>
<package name="com.md.domain"/>
typeAliases>
<mappers>
<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>springmvcservlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
<init-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:conf/dispatcherServlet.xmlparam-value>
init-param>
<load-on-startup>1load-on-startup>
servlet>
<servlet-mapping>
<servlet-name>springmvcservlet-name>
<url-pattern>*.dourl-pattern>
servlet-mapping>
<context-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:conf/applicationContext.xmlparam-value>
context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
listener>
<filter>
<filter-name>characterEncodingFilterfilter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
<init-param>
<param-name>encodingparam-name>
<param-value>utf-8param-value>
init-param>
<init-param>
<param-name>forceRequestEncodingparam-name>
<param-value>trueparam-value>
init-param>
<init-param>
<param-name>forceResponseEncodingparam-name>
<param-value>trueparam-value>
init-param>
filter>
<filter-mapping>
<filter-name>characterEncodingFilterfilter-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);
ListselectStudents();
}
StudentDao.xml
<?xml version="1.0" encoding="UTF-8" ?>
span style="box-sizing: border-box;border-width: 0px;border-style: initial;border-color: initial;">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);
ListfindStudents();
}
实现类
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 ListfindStudents() {
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 queryStudent(){
List 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="">
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="">
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>Titletitle>head><body><h1>注册结果:${tips}h1>body>html>
14. 浏览页面
listStudent.jsp
<%--Created by IntelliJ IDEA.User: MDDate: 2020/8/13Time: 21:10To 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="">
<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("")
.append(""+n.id+"")
.append(""+n.name+"")
.append(""+n.age+"")
.append("")
})
}
});
}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运行即可,之后再添加新的功能