SSM快速整合开发
- 首先创建一个maven的web项目,然后倒入依赖pom.xml
<!--
SSM整合的基础依赖
-->
<!-- 1.spring相关的依赖 -->
<!-- 1.1 ioc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.18</version>
</dependency>
<!--1.2 aop -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.7</version>
</dependency>
<!-- 1.3 声明式事务-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
<!-- 1.4 ssmtest001 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<!-- 2. mybatis相关依赖 -->
<!-- 2.1 mysql驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.11</version>
</dependency>
<!-- 2.2 数据源 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.6</version>
</dependency>
<!-- 2.3 mybatis核心包 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.5</version>
</dependency>
<!-- 3. springmvc相关依赖-->
<!-- 3.1 springmvc核心包 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
<!--3.2 servlet依赖 -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<!--3.3 jstl标签库-->
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- 4. log4j日志 -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<!-- 5. spring与mybatis整合包 *** -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.22</version>
</dependency>
搭建spring项目
- 准备好数据库\
CREATE TABLE `test01` (
`name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
`subject` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
`score` int(0) DEFAULT NULL
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of test01
-- ----------------------------
INSERT INTO `test01` VALUES ('zs', '语文', 11);
INSERT INTO `test01` VALUES ('zs', '数学', 22);
INSERT INTO `test01` VALUES ('ls', '语文', 33);
INSERT INTO `test01` VALUES ('ls', '数学', 44);
INSERT INTO `test01` VALUES ('ww', '语文', 55);
INSERT INTO `test01` VALUES ('ww', '数学', 66);
SET FOREIGN_KEY_CHECKS = 1;
- 编写一个实体类
@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class Student {
String name;
String subject;
String score;
}
-
创建service接口
public interface StudentService { /** * 查询所有学生 */ public List<Student> findAll(); }
-
创建service接口的实现类
@Service public class StudentServiceImpl implements StudentService { @Override public List<Student> findAll() { System.out.println("查询所有用户"); return null; } }
-
配置spring的配置文件,加入到ioc容器
<?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.xsd">
<!--扫描Service实现类-->
<context:component-scan base-package="com.xxx.ssmtest001.service"/>
</beans>
-
创建测试类进行测试,验证对象是否加入ioc容器
//@RunWith(SpringJUnit4ClassRunner.class)//开启spring的运行环境 //@ContextConfiguration("classpath:spring.xml")//加载spring的配置文件 public class StudentServiceImplTest { // @Autowired // StudentService studentService; @Test public void findAll() { //1.初始化SpringIOC容器,加载配置文件 ApplicationContext ac = new ClassPathXmlApplicationContext("spring.xml"); //2.从IOC容器取出对象 StudentService studentService = ac.getBean(StudentService.class); System.out.println(studentService.findAll()); } }
-
打印出结果,即搭建成功
搭建Spring mvc项目
- 编写controller
@Controller
@RequestMapping("/student")
public class StudentController {
@RequestMapping("findAll")
public String findAll(Model model){
model.addAttribute("list","测试");
return "list";
}
}
- 完成页面文件list.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
${list}
</body>
</html>
- springmvc的配置文件
<?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 http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- 1.扫描控制器 -->
<context:component-scan base-package="com.xxx.ssmtest001.controller"/>
<!-- 2.视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/"/>
<property name="suffix" value=".jsp"/>
</bean>
<!-- 3.创建处理器映射器和处理器适配器 -->
<mvc:annotation-driven/>
</beans>
- web.xml的配置
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>Archetype Created Web Application</display-name>
<!-- 配置核心控制器 -->
<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:springmvc.xml</param-value>
</init-param>
<!--用来标记是否在项目启动时就加在此Servlet,
0或正数表示容器在应用启动时就加载这个Servlet, 当是一个负数时或者没有指定时,
则指示容器在该servlet被选择时才加载.正数值越小启动优先值越高 -->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
- 部署到tomcat,进行测试,数据显示
spring和springmvc的整合
- web.xml的完善
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>Archetype Created Web Application</display-name>
<!--指定 Spring 配置文件的位置-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring.xml</param-value>
</context-param>
<!-- 配置spring监听器,用于加载context.xml(初始化SpringIOC容器) -->
<!-- 注册 ServletContext 监听器的实现类 ContextLoaderListener,
用于创建 Spring 容器及将创 建好的 Spring 容器对象放入到 ServletContext 的域属性空间中。-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 配置核心控制器 -->
<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:springmvc.xml</param-value>
</init-param>
<!--用来标记是否在项目启动时就加在此Servlet,
0或正数表示容器在应用启动时就加载这个Servlet, 当是一个负数时或者没有指定时,
则指示容器在该servlet被选择时才加载.正数值越小启动优先值越高 -->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
- controller的完善
@Controller
@RequestMapping("/student")
public class StudentController {
@Autowired
private StudentService studentService;
@RequestMapping("findAll")
public String findAll(Model model){
List<Student> all = studentService.findAll();
model.addAttribute("list",all);
return "list";
}
}
- 进行测试
mybatis的搭建
- dao层的编写
public interface StudentDao {
@Select("select * from test01")
public List<Student> findAll();
}
- jdbc.properties的属性配置
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost/test?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
jdbc.username=root
jdbc.password=123456
- 配置文件的编写
<?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>
<!-- 读取jdbc.properties -->
<properties resource="jdbc.properties"/>
<!--1.别名扫描,默认类名首字母小写的形式 -->
<typeAliases>
<package name="com.xxx.ssmtest001.entity"/>
</typeAliases>
<!--2.数据库连接 -->
<environments default="mysql">
<environment id="mysql">
<transactionManager type="jdbc"></transactionManager>
<dataSource type="pooled">
<property name="url" value="${jdbc.url}"/>
<property name="driver" value="${jdbc.driver}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments>
<!--3.映射关联 -->
<mappers>
<package name="com.xxx.ssmtest001.dao"/>
</mappers>
</configuration>
- 对mybatis进行测试,加载数据,代表成功
public class StudentDaoTest {
@Test
public void findAll() throws IOException {
//1.加载mybatis.xml
InputStream in = Resources.getResourceAsStream("mybatis.xml");
//2.创建SqlSessionFactory
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
SqlSessionFactory factory = builder.build(in);
//3.创建SqlSession
SqlSession sqlSession = factory.openSession();
//4.创建Dao代理对象
StudentDao studentDao = sqlSession.getMapper(StudentDao.class);
//5.执行方法
List<Student> list = studentDao.findAll();
System.out.println(list);
//6.释放资源
sqlSession.close();
in.close();
}
}
- mybatis的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">
<!--
namespace: 用于指定该映射文件需要映射的Dao接口
-->
<mapper namespace="com.xxx.ssmtest001.dao.StudentDao">
<!-- 为findAll方法映射SQL语句 -->
<!--
id: 需要映射的方法名称
resultType: 返回值需要封装的对象类型
注意:如果是集合类型,只需要指定集合中的存放元素类型即可
-->
<select id="findAll" resultType="student">
select * from test01
</select>
</mapper>
- 如果将两者分开,就要在pom.xml中进行修改
<!-- :默认情况下,Mybatis的xml映射文件不会编译到target的class目录下,
所以我们需要在pom.xml文件中配置resource-->
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
mybatis和spring的整合
- 完善spring的配置
<?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.xsd">
<!--扫描Service实现类-->
<context:component-scan base-package="com.xxx.ssmtest001.service"/>
<!-- 1. 创建数据源 -->
<context:property-placeholder location="classpath:jdbc.properties"/>
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="url" value="${jdbc.url}"/>
<property name="driverClassName" value="${jdbc.driver}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<!-- 2. 为了创建Dao代理对象,先创建SqlSessionFactory对象 -->
<!-- SqlSessionFactoryBean: 创建SqlSessionFactory对象的工具 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 注入数据源 -->
<property name="dataSource" ref="dataSource"/>
<!-- 扫描model包 使用别名 -->
<property name="typeAliasesPackage" value="com.xxx.ssmtest001.entity"/>
</bean>
<!-- 3. 扫描Dao接口所在包,扫描后用于创建Dao代理对象,把代理对象放入IOC容器 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- Dao扫描目录 -->
<property name="basePackage" value="com.xxx.ssmtest001.dao"/>
</bean>
</beans>
- 完善service的实现类
@Service
public class StudentServiceImpl implements StudentService {
//注入Dao对象
@Autowired
private StudentDao studentDao;
@Override
public List<Student> findAll() {
System.out.println("查询所有用户");
return studentDao.findAll();
}
}
- 完善controller
@Controller
@RequestMapping("/student")
public class StudentController {
@Autowired
private StudentService studentService;
@RequestMapping("findAll")
public String findAll(Model model){
List<Student> all = studentService.findAll();
model.addAttribute("list",all);
return "list";
}
}
- 完善list.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<table border="1">
<tr>
<td>姓名</td>
<td>科目</td>
<td>得分</td>
</tr>
<!--
items: 需要需要遍历的集合
var: 每个对象的变量名称
-->
<c:forEach items="${list}" var="stu">
<tr>
<td>${stu.name}</td>
<td>${stu.subject}</td>
<td>${stu.score}</td>
</tr>
</c:forEach>
</table>
</body>
</html>
- 进行测试最终的测试
Springboot快速开发
页面开发
- 实体类
@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class Student {
String name;
String subject;
String score;
}
- controller
@Controller
@RequestMapping("/student")
public class StudentController {
@RequestMapping("findAll")
public String findAll(Model model){
model.addAttribute("list","ssss");
return "list";
}
}
- list页面
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<span th:text="${list}"></span>
</body>
</html>
- 配置文件
server:
servlet:
context-path: /
port: 8081
整合mybatis
- 依赖
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.0.0</version>
</dependency>
<!--配置数据库连接池,非必要-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.2.6</version>
</dependency>
- 界面
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<!-- <span th:text="${list}"></span>-->
<table border="1">
<tr>
<td>姓名</td>
<td>科目</td>
<td>得分</td>
</tr>
<tr th:each="stu:${list}">
<td th:text="${stu.name}"></td>
<td th:text="${stu.subject}"></td>
<td th:text="${stu.score}"></td>
</tr>
</table>
</body>
</html>
- 配置文件
server:
servlet:
context-path: /
port: 8081
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost/test?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
username: root
password: 123456