ssm整合
文章目录
此篇笔记主要参考黑马57期介绍的ssm搭建流程来完成的
项目创建
添加键值对archetypeCatalog
=internal
便于快速构建webapp
在main路径下新建java和resources路径
创建完目录如下
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-UOJNMr17-1592727190888)(…/…/pic/整合/image-20200620173427730.png)]
数据库
CREATE TABLE `account` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(20) DEFAULT NULL,
`money` double DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8
INSERT INTO `ssm`.`account`(`id`, `name`, `money`) VALUES (1, '吴一', 200);
INSERT INTO `ssm`.`account`(`id`, `name`, `money`) VALUES (2, '老王', 400);
INSERT INTO `ssm`.`account`(`id`, `name`, `money`) VALUES (4, '张三', 100000);
INSERT INTO `ssm`.`account`(`id`, `name`, `money`) VALUES (5, '王五', 1111);
INSERT INTO `ssm`.`account`(`id`, `name`, `money`) VALUES (6, '李四', 343);
INSERT INTO `ssm`.`account`(`id`, `name`, `money`) VALUES (7, '赵六', 3333);
INSERT INTO `ssm`.`account`(`id`, `name`, `money`) VALUES (8, '钱七', 3);
INSERT INTO `ssm`.`account`(`id`, `name`, `money`) VALUES (9, '孙八', 123);
INSERT INTO `ssm`.`account`(`id`, `name`, `money`) VALUES (10, '周九', 4);
依赖
这个笔记主要记录ssm整合流程,对依赖的版本不做过多解释。
<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>
<spring.version>5.0.2.RELEASE</spring.version>
<slf4j.version>1.6.6</slf4j.version>
<log4j.version>1.2.12</log4j.version>
<mysql.version>5.1.6</mysql.version>
<mybatis.version>3.4.5</mybatis.version>
</properties>
<dependencies>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.12</version>
</dependency>
<!-- spring -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.6.8</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- log start -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${slf4j.version}</version>
</dependency>
<!-- log end -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.0</version>
</dependency>
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
</dependencies>
创建包
package com.bing.domain;
import lombok.Data;
/**
* @Author: bing
* @Description: 实体类
* @Date: Created in 2020/6/19 16:24
*/
@Data
public class Account {
private Integer id;
private String name;
private Double money;
}
package com.bing.dao;
import com.bing.domain.Account;
import java.util.List;
/**
* @Author: bing
* @Description: 持久层接口
* @Date: Created in 2020/6/19 16:25
*/
public interface IAccountDao {
/**
* @author bing
* @Description: 用于查询所有的方法
* @date Created in 2020/6/19 16:26
*/
List<Account> findAll();
}
package com.bing.service;
import com.bing.domain.Account;
import java.util.List;
/**
* @Author: bing
* @Description: 用户的业务层接口
* @Date: Created in 2020/6/19 16:27
*/
public interface IAccountService {
List<Account> findAll();
}
package com.bing.service.impl;
import com.bing.domain.Account;
import com.bing.service.IAccountService;
import java.util.List;
/**
* @Author: bing
* @Description: 用户的业务层实现类
* @Date: Created in 2020/6/19 16:28
*/
public class AccountServiceImpl implements IAccountService {
@Override
public List<Account> findAll() {
return null;
}
}
package com.bing.controller;
/**
* @Author: bing
* @Description: 用户的表现层
* @Date: Created in 2020/6/19 16:29
*/
public class AccountController {
}
另外创建test目录用于测试spring和mybatis框架的运行情况。
创建完之后整体目录如下
spring
编写配置文件
在resources
目录下新建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"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
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/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
">
<!--开启注解扫描-->
<context:component-scan base-package="com.bing">
<!--配置不扫描Controller注解-->
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
</beans>
将service交给容器进行管理
在service实现类上添加注解和打印语句用于测试
@Service("accountService")
public class AccountServiceImpl implements IAccountService {
@Override
public List<Account> findAll() {
System.out.println("业务层查询所有用户的方法执行了……………");
return null;
}
}
编写测试类
package com.bing.test;
import com.bing.service.IAccountService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* @Author: bing
* @Description: 用于测试spring是否配置成功的测试类
* @Date: Created in 2020/6/19 16:38
*/
public class TestSpring {
@Test
public void TestFindAll() {
//加载配置文件
ApplicationContext context = new ClassPathXmlApplicationContext("ApplicationContext.xml");
//获取对象
IAccountService accountService = context.getBean("accountService", IAccountService.class);
//调用方法
accountService.findAll();
}
}
执行测试
运行测试类可以看到spring目前已经成功
springMVC
编写配置文件
在resources
目录下新建springmvc.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:mvc="http://www.springframework.org/schema/mvc"
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
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
">
<!--开启注解扫描-->
<context:component-scan base-package="com.bing">
<!--配置只扫描Controller注解-->
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!--配置视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/"/>
<property name="suffix" value=".jsp"/>
</bean>
<!--过滤静态资源-->
<mvc:resources mapping="/css/**" location="/css/"/>
<mvc:resources mapping="/images/**" location="/images/"/>
<mvc:resources mapping="/js/**" location="/js/"/>
<!--开启SpringMVC注解支持-->
<mvc:annotation-driven/>
</beans>
在web.xml
文件配置前端控制器
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<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>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!--配置中文乱码过滤器-->
<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>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/</url-pattern>
</filter-mapping>
</web-app>
新建前端页面
默认生成的index.jsp
不带头信息,所以删了重新建一个index.jsp
文件,添加一个a标签。
<%--
Created by IntelliJ IDEA.
User: bing
Date: 2020/6/19
Time: 16:05
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>
<a href="account/findAll">测试</a>
</body>
</html>
修改Controller
@Controller
@RequestMapping("/account")
public class AccountController {
@RequestMapping("/findAll")
public String findAll() {
System.out.println("表现层查询了所有的账户…………");
return "list";
}
}
编写前端页面
在WEB-INF
目录下新建pages
目录,再新建list.jsp
文件
<%--
Created by IntelliJ IDEA.
User: bing
Date: 2020/6/19
Time: 17:07
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>
<h3>这里将会显示查询的所有用户</h3>
</body>
</html>
配置tomcat服务器
测试
启动tomcat
点击测试超链接
成功跳转到list.jsp
页面
控制台打印输出语句
至此,springMVC配置完成
spring整合springMVC
【思考】:
刚才springMVC已经能够成功输出语句,现在只需要在输出语句的同时,调用service业务层的保存方法(业务层是由spring管理的),那spring和springMVC就整合成功了。
而要调用service
方法,就需要一个service
对象,这时候就需要用到依赖注入了。
【问题】:
最终这个项目是一个web项目,启动tomcat
服务器之后,web.xml
会在启动时帮我们加载springmvc
的配置文件
而在springmvc
配置文件中,配置了只扫描Controller
注解而不会扫描Service
注解
也就是说我们的spring
配置文件ApplicationContext.xml
一直都没有得到加载。
【解决】:
如果在启动tomcat
服务器的时候,加载spirng
配置文件,就能把Service
添加到容器中,完成依赖注入。
在web.xml文件中配置监听器
<display-name>Archetype Created Web Application</display-name>
<!--配置spring监听器,默认只加载WEB-INF目录下的applicationContext.xml的配置文件-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--所以下面要说明一下spring配置文件的路径-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:ApplicationContext.xml</param-value>
</context-param>
为什么要这么配?
查看ContextLoaderListener
源码,发现他实现了ServletContextListener
接口
ServletContext
是javaweb最大的域对象,一个项目应用只会有一个ServletContext
域对象,服务器启动的时候,就会创建这个对象,当服务器关闭时,它才会销毁。
ContextLoaderListener
是spring-web提供的监听器,监听ServletContext
域对象的创建和销毁,这个监听器可以加载Spring配置文件,创建一个WEB版本工厂,存储在ServletContext
对象中。
在Controller中注入accountService
@Controller
@RequestMapping("/account")
public class AccountController {
@Autowired
private IAccountService accountService;
@RequestMapping("/findAll")
public String findAll() {
System.out.println("表现层查询了所有的账户…………");
//需要在这里调用service的findALl方法
accountService.findAll();
return "list";
}
}
测试
重新点击a标签进行测试,
打印成功
mybatis
编写配置文件
在resources
路径下新建sqlMapConfig.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>
<environments default="mysql">
<environment id="mysql">
<transactionManager type="JDBC"></transactionManager>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql:///ssm"/>
<property name="username" value="root"/>
<property name="password" value="123"/>
</dataSource>
</environment>
</environments>
<mappers>
<package name="com.bing.dao"/>
</mappers>
</configuration>
在dao接口类方法上添加sql语句注解
@Select("select * from account")
List<Account> findAll();
编写测试类
在test包下编写测试类
package com.bing.test;
import com.bing.dao.IAccountDao;
import com.bing.domain.Account;
import com.bing.service.IAccountService;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
/**
* @Author: bing
* @Description:
* @Date: Created in 2020/6/19 19:39
*/
public class TestMybatis {
@Test
public void run() throws IOException {
InputStream inputStream = Resources.getResourceAsStream("sqlMapConfig.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
IAccountDao accountDao = sqlSession.getMapper(IAccountDao.class);
List<Account> accounts = accountDao.findAll();
for (Account account : accounts) {
System.out.println(account);
}
sqlSession.close();
inputStream.close();
}
}
测试
spring整合Mybatis
【思考】:
由spring管理的service层,可以正常打印,那只要在打印的时候,执行dao中方法就即为成功。
dao的实现类是由mybatis动态代理来生成的代理对象,只要把代理存放到ioc容器中,然后在service中注入dao对象就可以了。
【解决】:
编写配置文件
在ApplicationContext.xml中添加以下配置
<!--配置连接池-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"/>
<property name="jdbcUrl" value="jdbc:mysql:///ssm"/>
<property name="user" value="root"/>
<property name="password" value="123"/>
</bean>
<!--配置sqlSessionFactory工厂-->
<bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
</bean>
<!--配置AccountDao所在的包-->
<bean id="scannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.bing.dao"/>
</bean>
在Dao中加上注解
@Repository("accountDao")
public interface IAccountDao {
@Select("select * from account")
List<Account> findAll();
}
在Service中注入accountDao
@Service("accountService")
public class AccountServiceImpl implements IAccountService {
@Autowired
private IAccountDao accountDao;
@Override
public List<Account> findAll() {
System.out.println("业务层查询所有用户的方法执行了……………");
return accountDao.findAll();
}
}
测试
在Controller中,将查询出来的值放入model
@RequestMapping("/findAll")
public String findAll(Model model) {
System.out.println("表现层查询了所有的账户…………");
List<Account> accounts = accountService.findAll();
model.addAttribute("accounts", accounts);
return "list";
}
在list.jsp中循环输出accounts
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h3>这里将会显示查询的所有用户</h3>
<c:forEach items="${accounts}" var="account">
${account.name}<br/>
</c:forEach>
</body>
</html>
重新启动tomcat,点击测试
成功查询出来数据。
Controller中,将查询出来的值放入model
@RequestMapping("/findAll")
public String findAll(Model model) {
System.out.println("表现层查询了所有的账户…………");
List<Account> accounts = accountService.findAll();
model.addAttribute("accounts", accounts);
return "list";
}
在list.jsp中循环输出accounts
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h3>这里将会显示查询的所有用户</h3>
<c:forEach items="${accounts}" var="account">
${account.name}<br/>
</c:forEach>
</body>
</html>
重新启动tomcat,点击测试
成功查询出来数据。
至此,ssm三大框架整合完毕。