SSM整合
目的
大三上学期的ssm考试需要进行上机考试(别问我为啥不是大作业,我也想问),然而我学ssm已经是大二第一个学期的时候了,在大二第二个学期学到SpringBoot后就基本手动配置ssm整合的一些配置文件,趁复习正好写一篇博客来记录一下过程,顺便帮助一下刚刚学ssm的人,我当初学ssm整合的时候可是被网上的一些博客害惨了,呜呜呜┭┮﹏┭┮。
ssm整合的每一步操作我都会写的非常详细,我也会把相关的sql文件,jar以及源码都上传带gitee上(GitHub我们学校这边网络不稳定,经常会上不去),大家可以去下载下来观看。
准备工作
- mysql
- eclipse(没办法,考试要求要用这个)
- tomcat(任意版本都可以,我这边只是恰好电脑有8.5就不用去下载了)
- 各种jar包(我会把项目上传到gitee上,到时候直接下载项目去复制jar包就可以了)
一 、创建项目
- 创建动态web项目,版本选为2.5(个人习惯)
- 选择next
- 在选择next会出现下面图片那样,吧√选上,这样他会自动帮我们创建web.xml文件,完成后直接finish即可。
- 开启web开发视图界面(如果没有跳出来可忽略这一步)
- 创建项目后的结构如下
二、将项目添加我们的tomcat
- 看你得eclipse是否有在下图有黄色图块的server窗口,有的话点击是这样子的
如果没有的话:选择windows->show view->other,然后输入server,点击server即可跳出该窗口
- 在server界面中,右键->new->server,输入tomcat,选择你要用的版本
选择next,然后选择browse,选择你tomcat的位置,选好后直接选择finish。
做好第二步后你的server视图会出现你的tomcat
- 选择你的tomcat右键->选择add and remove,双击你的项目添加到tomcat中,点击finish
三、添加项目需要的jar包
相关jar包我和项目一起上传到gitee上了,点击链接自行获取
选择所有jar包,右键->build path->add to build path
四、创建数据库
/*
SQLyog Ultimate v12.09 (64 bit)
MySQL - 5.7.26-log : Database - ssmdemo
*********************************************************************
*/
/*!40101 SET NAMES utf8 */;
/*!40101 SET SQL_MODE=''*/;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
CREATE DATABASE /*!32312 IF NOT EXISTS*/`ssmdemo` /*!40100 DEFAULT CHARACTER SET utf8 */;
USE `ssmdemo`;
/*Table structure for table `student` */
DROP TABLE IF EXISTS `student`;
CREATE TABLE `student` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '自动编号',
`sno` varchar(20) NOT NULL COMMENT '学号',
`name` varchar(15) NOT NULL COMMENT '学生姓名',
`sex` varchar(2) DEFAULT NULL,
`birthday` date DEFAULT NULL,
`major` varchar(30) DEFAULT NULL,
`address` varchar(80) DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=214 DEFAULT CHARSET=utf8;
/*Data for the table `student` */
insert into `student`(`id`,`sno`,`name`,`sex`,`birthday`,`major`,`address`) values (1,'2017001001','张三','男','2000-02-01','计算机','广州越秀'),(2,'2017001002','李四','男','1992-01-01','会计','广州白云'),(3,'2017001003','王五','男','1993-01-01','工商管理','广州天河'),(4,'2017001004','黄蓉','女','1994-01-01','英语','广州海珠'),(5,'2017001005','杨幂','女','1995-01-01','自动化','广州黄埔'),(12,'2','31232','2','2020-12-08','2','2'),(100,'10086','星期二','男','2018-08-08','软件1班','天院'),(123,'123','Ngork学习','1','2020-12-04','软件1班','天院'),(213,'3213','213','男','2020-12-12','大王大威德','weqweqw');
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
五、创建对应的实体类
Student.java
package pojo;
import java.util.Date;
public class Student {
private int id;
private String sno;
private String name;
private String sex;
private Date birthday;
private String major;
private String address;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getSno() {
return sno;
}
public void setSno(String sno) {
this.sno = sno;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getMajor() {
return major;
}
public void setMajor(String major) {
this.major = major;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Student(int id, String sno, String name, String sex, Date birthday, String major, String address) {
super();
this.id = id;
this.sno = sno;
this.name = name;
this.sex = sex;
this.birthday = birthday;
this.major = major;
this.address = address;
}
public Student() {
super();
}
@Override
public String toString() {
return "Student [id=" + id + ", sno=" + sno + ", name=" + name + ", sex=" + sex + ", birthday=" + birthday
+ ", major=" + major + ", address=" + address + "]";
}
}
六、相关配置文件的创建
- 在src下面创建applicationContext.xml文件
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 http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="controller"></context:component-scan>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 这里的配置我的理解是自动给后面action的方法return的字符串加上前缀和后缀,变成一个 可用的url地址 -->
<property name="prefix" value="/views/" />
<property name="suffix" value=".jsp" />
</bean>
<!-- 加载配置文件db.properties文件 -->
<bean id="properties" class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer">
<property name="locations"><!-- 查看源码后发现为数组 -->
<array>
<value>classpath:db.properties</value>
</array>
</property>
</bean>
<!-- 从mybatis的conf配置文件中转过来的东西 -->
<bean id="datasource_1" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="${driver}" />
<property name="url" value="${url}" />
<property name="username" value="${username}" />
<property name="password" value="${password}" />
</bean>
<!-- mybatis的核心类SqlSessionFactory的配置 -->
<bean id="SqlSessionFactory_1" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="datasource_1"></property>
<!-- 加载mapper.xml的文件路径 -->
<property name="mapperLocations">
<list>
<value>classpath:mapper/*.xml</value>
</list>
</property>
</bean>
<!-- 将sqlSessionFactory交给spring -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="mapper"/><!-- 找到mapper接口 -->
<property name="sqlSessionFactoryBeanName" value="SqlSessionFactory_1"/>
</bean>
<!-- service接口和实现类注入到Spring容器的bean中 -->
<!-- 查找默认构造函数 必须要有默认构造函数 -->
<bean id="istudent" class="service.imp.StudentImp"></bean>
</beans>
- 在src创建db.properties的数据库信息文件
db.properties
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/ssmdemo?characterEncoding=UTF-8
username=root
password=123456
七、三层代码的编写
- mapper层
StudentMapper.java
package mapper;
import java.util.List;
import pojo.Student;
public interface StudentMapper {
public List<Student> QueryStudentList();
public Boolean AddStudent(Student student);
}
StudentMapper.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="mapper.StudentMapper">
<select id="QueryStudentList" resultType="pojo.Student">
select * from student
</select>
<insert id="AddStudent" parameterType="pojo.Student">
insert into student(id,sno,name,sex,birthday,major,address) values(#{id},#{sno},#{name},#{sex},#{birthday},#{major},#{address})
</insert>
</mapper>
- service层
service接口的Istudent.java
package service;
import java.util.List;
import pojo.Student;
public interface IStudent {
public List<Student> QueryStudentList();
public Boolean AddStudent(Student student);
}
service实现类的StudentImp.java
package service.imp;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import mapper.StudentMapper;
import pojo.Student;
import service.IStudent;
public class StudentImp implements IStudent{
@Autowired
StudentMapper studentMapper;
@Override
public List<Student> QueryStudentList() {
return studentMapper.QueryStudentList();
}
@Override
public Boolean AddStudent(Student student) {
return studentMapper.AddStudent(student);
}
}
- controller层
package controller;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import pojo.Student;
import service.IStudent;
@Controller
public class StudentController {
@Autowired
IStudent istudent;
@RequestMapping({"/QueryStudentList","/"})
public String QueryStudentList(Model model) {
List<Student> list = istudent.QueryStudentList();
model.addAttribute("studentList", list);
return "StudentList";
}
@RequestMapping("/toAddStudentView")
public String ToAddStudentView() {
return "AddStudent";
}
@RequestMapping("/addStudent")
public String AddStudent(Model model,Student student,@Param("birthdayTime")String birthdayTime) {
DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date date;
try {
date = format.parse(birthdayTime);
student.setBirthday(date);
} catch (ParseException e) {
model.addAttribute("addResult", "日期格式不对");
return "StudentList";
}
Boolean isTrue = istudent.AddStudent(student);
model.addAttribute("addResult", "添加结果:"+isTrue);
return "forward:/QueryStudentList";
}
}
- 设置显示界面,在WebContent下面新建一个views文件夹(我springmvc设置的前后缀设定在这个位置的jsp文件),在这个文件夹中,新建2个jsp文件。
AddStudent.jsp
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Insert title here</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/addStudent" method="post">
id:<input name="id"><br/>
sno:<input name="sno"><br/>
name:<input name="name"><br/>
sex:<input name="sex" maxlength="1"><br/>
birthday:<input name="birthdayTime" type="date"><br/>
major:<input name="major"><br/>
address:<input name="address"><br/>
<input type="submit" value="添加">
</form>
</body>
</html>
StudentList.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<a href="${pageContext.request.contextPath}/toAddStudentView">添加学生信息</a><br/>
${addResult}<br/>
<table border="1px">
<thead>学生信息</thead>
<tbody>
<tr>
<td>id</td>
<td>sno</td>
<td>name</td>
<td>sex</td>
<td>birthday</td>
<td>major</td>
<td>address</td>
</tr>
<c:forEach var="stu" items="${requestScope.studentList}">
<tr>
<td>${stu.id}</td>
<td>${stu.sno}</td>
<td>${stu.name}</td>
<td>${stu.sex}</td>
<td>${stu.birthday}</td>
<td>${stu.major}</td>
<td>${stu.address}</td>
</tr>
</c:forEach>
</tbody>
</table>
</body>
</html>
八、启动项目
运行项目,在浏览器输入localhost:8888/Pning_SSM/QueryStudentList得到结果
ssm至此整合成功
源码和相关的资源文件自取
SSM整合
黄色图块的就是这次的源码的