整合ssm框架的步骤
一. 准备工作:创建一个存放学生数据的数据库表
CREATE DATABASE `ssm_student`;
USE `ssm_student`;
DROP TABLE IF EXISTS `student`;
# 建议前3句语句分开按顺序执行,不然可能会报错
CREATE TABLE `student` (
`stuId` INT(10) NOT NULL AUTO_INCREMENT COMMENT '学生id',
`stuName` VARCHAR(100) NOT NULL COMMENT '姓名',
`stuAge` INT(11) NOT NULL COMMENT '年龄',
KEY `stuId` (`stuId`)
) ENGINE=INNODB DEFAULT CHARSET=utf8
INSERT INTO `student`(`stuId`,`stuName`,`stuAge`)VALUES
(1,'zxx',18),
(2,'wmd',19),
(3,'lyf',18);
在数据库表里创建好之后,可以将idea与数据库关联起来,方便后面写mapper.xml文件的sql语句。步骤如下:
1.点击idea右侧Database
2.选择mysql
3.点击Text Connection,显示Succeeded
,则成功,点击Apply,等待数秒后点击ok
4.上面步骤都完成后,你便可以看见你的本地数据库localhost,点击0 of 21 ,勾选我们刚刚创建的那个表。
5.便可看见表中数据,到处关联完成。
二. 开始搭建
1.创建web的maven项目
2.添加目录结构:src下面创建java和resourses两个文件目录
3.添加maven依赖:在pom.xml里面添加项目所需坐标。(可能会随着开发添加更多)
<!--依赖注入:junit 数据库驱动,连接池,servlet,mybatis,mybatis-spring,spring -->
<dependencies>
<!--Junit-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<!--数据库驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<!-- 数据库连接池 -->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
</dependency>
<!--Servlet - JSP -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!--Mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.2</version>
</dependency>
<!--Spring-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.22</version>
</dependency>
<!--注意这个 -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.5</version>
</dependency>
</dependencies>
<!--静态资源导出问题 -->
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
4.搭建项目的基本结构和配置框架(这里dao层下不要mapper和xml的包了,我写着后面发现错误了,找了3h,大家注意哈!!!)
5.编写pojo实体类
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* @author jj
* @date2022/6/28 14:14
* 添加了lombok依赖,所以加上@Data就可以不用写get/set方法
* 添加了@AllArgsConstructor,@NoArgsConstructor就可以不用写有参和无参构造方法
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Student {
private int stuId;
private String stuName;
private int stuAge;
}
注意:如果不想自己写pojo的实体类的话,可以使用逆向工程,让idea自动生成。步骤如下:
- .点开database找到你的表右键选择Scripted Extensions–>Generate POJOs.groovy,然后选择pojo目录下即可。
6.编写Dao层的 Mapper接口
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.etime.dao.mapper.StudentMapper">
<insert id="addStudent" parameterType="Student">
insert into ssm_student.student(stuName, stuAge)
VALUES (#{stuName},#{stuAge});
</insert>
<delete id="deleteStudentById" parameterType="Student">
delete from ssm_student.student where stuId=#{stuId};
</delete>
<update id="updateStudent" parameterType="Student">
update ssm_student.student set stuName=#{stuName},stuAge=#{stuAge}
where stuId=#{stuId};
</update>
<select id="queryStudentById" resultType="Student">
select * from ssm_student.student where stuId=#{stuId};
</select>
<select id="queryAllStudent" resultType="Student">
select * from ssm_student.student;
</select>
</mapper>
7.编写Service层的接口和实现类
//StudentService接口:
package com.etime.service.impl;
import com.etime.pojo.Student;
import java.util.List;
public interface StudentService {
//增加一个Student
int addStudent(Student student);
//根据id删除一个Student
int deleteStudentById(int id);
//更新Student
int updateStudent(Student student);
//根据id查询,返回一个Student
Student queryStudentById(int id);
//查询全部Student,返回list集合
List<Student> queryAllStudent();
}
//StudentServiceimpl实现类:
package com.etime.service.stu;
import com.etime.dao.mapper.StudentMapper;
import com.etime.pojo.Student;
import com.etime.service.impl.StudentService;
import java.util.List;
public class StudentServiceImpl implements StudentService {
//调用dao层的操作,设置一个set接口,方便Spring管理
private StudentMapper studentMapper;
public void setStudentMapper(StudentMapper studentMapper) {
this.studentMapper = studentMapper;
}
@Override
public int addStudent(Student student) {
return studentMapper.addStudent(student);
}
@Override
public int deleteStudentById(int id) {
return studentMapper.deleteStudentById(id);
}
@Override
public int updateStudent(Student student) {
return studentMapper.updateStudent(student);
}
@Override
public Student queryStudentById(int id) {
return studentMapper.queryStudentById(id);
}
@Override
public List<Student> queryAllStudent() {
return studentMapper.queryAllStudent();
}
}
三.接下来就是最麻烦的配置了!!!
1.数据库配置文件 database.properties
jdbc.driver=com.mysql.jdbc.Driver
serverTimezone=Asia/Shanghai
jdbc.url=jdbc:mysql://localhost:3306/ssmbuild?useSSL=false&useUnicode=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=123456
2.配置mybatis-config.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>
<!-- 配置数据源,交给spring去做-->
<typeAliases>
<package name="com.etime.pojo"/>
</typeAliases>
<mappers>
<mapper class="com.etime.dao.mapper.StudentMapper"/>
</mappers>
</configuration>
3.配置spring-dao.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">
<!-- 1.关联数据库配置文件-->
<context:property-placeholder location="classpath:database.properties"/>
<!-- 2.连接池 dbcp C3P0 druid hikari-->
<bean id="dateSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driver}"/>
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="user" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
<!-- c3p0连接池的私有属性 -->
<property name="maxPoolSize" value="30"/>
<property name="minPoolSize" value="10"/>
<!-- 关闭连接后不自动commit -->
<property name="autoCommitOnClose" value="false"/>
<!-- 获取连接超时时间 -->
<property name="checkoutTimeout" value="10000"/>
<!-- 当获取连接失败重试次数 -->
<property name="acquireRetryAttempts" value="2"/>
</bean>
<!-- 3.sqlsessionFactory-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dateSource"/>
<property name="configLocation" value="classpath:mybatis-config.xml"/>
</bean>
<!--配置dao的扫描包 动态实现dao接口可以注入到spring容器中-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!--注入sqlsessionfactory -->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<!-- 要扫描的dao包-->
<property name="basePackage" value="com.etime.dao"/>
</bean>
</beans>
4.配置spring-service.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:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/cache"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd">
<!-- -->
<!--1.扫描service下的包 -->
<context:component-scan base-package="com.etime.service"/>
<!--2.将我们所有的业务类注入到spring 可以通过注解或者配置实现 -->
<bean id="StudentServiceImpl" class="com.etime.service.impl.StudentServiceImpl">
<property name="studentMapper" ref="studentMapper"/>
</bean>
<!-- 3.声明事物-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- 注入数据源-->
<property name="dataSource" ref="dateSource"/>
</bean>
</beans>
5.配置spring-mvc.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
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- 配置SpringMVC -->
<!-- 1.开启SpringMVC注解驱动 -->
<mvc:annotation-driven/>
<!-- 2.静态资源默认servlet配置-->
<mvc:default-servlet-handler/>
<!-- 3.配置jsp 显示ViewResolver视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<!-- 4.扫描web相关的bean -->
<context:component-scan base-package="com.etime.controller" />
</beans>
6.配置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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<import resource="classpath:spring-dao.xml"/>
<import resource="spring-service.xml"/>
<import resource="classpath:spring-mvc.xml"/>
</beans>
7.配置web.xml文件
<?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">
<!--DispatcherServlet-->
<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:applicationContext.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>DispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!--encodingFilter-->
<filter>
<filter-name>encodingFilter</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>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!--Session过期时间-->
<session-config>
<session-timeout>15</session-timeout>
</session-config>
</web-app>
到这里,一个ssm项目就已经基本配置完成了,现在就需要写Controller和视图层的内容即可
1、BookController 类编写 , 方法一:查询全部学生
import java.util.List;
/**
* @author jj
* @date2022/6/28 16:53
*/
@Controller
@RequestMapping("/student")
public class StudentController {
@Autowired
@Qualifier("StudentServiceImpl")
private StudentService studentService;
@RequestMapping("/all")
public String list(Model model){
List<Student> list = studentService.queryAllStudent();
model.addAttribute("list",list);
return "allstudent";
}
}
2.在jsp包下编写allstudent.jsp文件(注意要和上面的return返回的名字一样)
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--
Created by IntelliJ IDEA.
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<html>
<head>
<title>学生信息展示</title>
</head>
<body>
<div class="container">
<div class="row clearfix">
<div class="col-md-12 column"></div>
<div class="page-header">
<h1>
<small>学生管理 --- 显示所有学生信息</small>
</h1>
</div>
</div>
<div class="row">
<div class="row-md-4 column">
<br/>
<a class="btn btn-primary" href="#">添加书籍</a>
<a class="btn btn-primary" href="${pageContext.request.contextPath}/student/all">显示所有书籍</a>
</div>
</div>
<div class="row clearfix">
<div class="col-md-12 column">
<table class="table table-hover table-striped">
<thead>
<tr>
<th>学生编号</th>
<th>学生名称</th>
<th>学生年龄</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<c:forEach var="student" items="${list}">
<tr>
<td>${student.stuId}</td>
<td>${student.stuName}</td>
<td>${student.stuAge}</td>
<td>
<a href="#">修改</a>
|
<a href="#">删除</a>
</td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
</div>
</div>
</body>
</html>
3.配置tomcat,启动程序。
4.访问:localhost:8080/student/all 运行(这里加了点bootstrap框架的样式)。
到此,一个简单的ssm项目就已经整合完毕。其他的增删改查等功能只需要写好controller层和前端界面即可。
注意:此文章为学习记录文章,参考多篇文章,如有不正之处请指教