文章目录
一、单独配置Spring并运行测试
1.导入依赖
测试依赖:
<!--junit-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
<scope>test</scope>
</dependency>
<!--spring test-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.1.6.RELEASE</version>
</dependency>
SpringIOC容器依赖:
<!--spring ioc-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.1.6.RELEASE</version>
</dependency>
<!--spring 事务管理-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.1.6.RELEASE</version>
</dependency>
Spring AOP依赖:
<!--spring 第三方aop-->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.13</version>
</dependency>
<!--spring aop-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>5.1.6.RELEASE</version>
</dependency>
Spring-jdbc依赖:
<!--spring jdbc模板-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.1.6.RELEASE</version>
</dependency>
2.创建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"
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">
<!--开启spring 注解扫描-->
<context:component-scan base-package="com.ps.ssm.service"></context:component-scan>
<!--开启aop自动代理-->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
<!--开启事务注解支持-->
<tx:annotation-driven></tx:annotation-driven>
</beans>
至于那些连接数据库相关的,我们等到配置Mybatis的时候一起配置
3.创建最简单的业务逻辑代码
实体类:
package com.ps.ssm.pojo;
public class Account {
private int id;
private int uid;
private double money;
public Account() {
}
@Override
public String toString() {
return "Account{" +
"id=" + id +
", uid=" + uid +
", money=" + money +
'}';
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getUid() {
return uid;
}
public void setUid(int uid) {
this.uid = uid;
}
public double getMoney() {
return money;
}
public void setMoney(double money) {
this.money = money;
}
public Account(int id, int uid, double money) {
this.id = id;
this.uid = uid;
this.money = money;
}
}
数据访问层:
public interface AccountDao {
List<Account> findAll();
int save(Account account);
}
业务层:
public interface AccountService {
List<Account> findAll();
void save(Account account) ;
}
@Service
public class AccountServiceImpl implements AccountService {
private AccountDao accountDao;
public List<Account> findAll() {
System.out.println("find account finished!");
return null;
}
@Transactional
public void save(Account account) {
System.out.println("保存账户成功!");
}
}
4. 测试搭建是否成功
测试代码:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class TestAccountService {
@Autowired
private AccountService accountService;
@Test
public void testFind() {
List<Account> all = accountService.findAll();
}
}
测试结果:
由于我的是已经搭建好的,所以会有其他的输出,你只需要看到有这行输出即可
二、单独配置SpringMVC并运行测试
1.导入依赖
SpringMVC依赖:
<!--spring mvc-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.6.RELEASE</version>
</dependency>
servlet API:
<!--
这个的话版本随便导入,因为只是在编译的时候用一下,运行的时候会使用tomcat中的,如果害怕依赖冲突可以在下面加上<scope>provided</scope> 保证部署到tomcat运行时不会发生冲突
servlet api-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
</dependency>
json转换工具:
<!--jackson
这个版本的话可以根据自己的来,但是要保证高于2.9.0不然很大概率会报错
-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.8</version>
</dependency>
2.创建配置文件
配置web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<!--配置前端控制器-->
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--配置初始化参数,即加载SpringMVC配置文件-->
<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>
创建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">
<!--开启注解扫描-->
<context:component-scan base-package="com.ps.ssm.controller"></context:component-scan>
<!--放开静态资源-->
<mvc:default-servlet-handler/>
<!--开启注解驱动,创建控制器适配器和控制器映射器-->
<mvc:annotation-driven/>
<!--配置视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="viewResolver">
<property name="prefix" value="/"></property>
<property name="suffix" value=".html"></property>
</bean>
</beans>
3.创建相关类和静态资源
创建控制器:
@Controller
public class AccountController {
@Autowired
private AccountService accountService;
@RequestMapping("/find")
public String find() {
return "list";
}
}
创建要跳转的页面:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
list html
<h1>账号列表</h1>
</body>
</html>
初始访问页面:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
index html
</body>
</html>
4.部署并测试
部署到tomcat:
访问find:
三、单独配置Mybatis并运行测试
1.导入依赖
mybatis依赖:
<!--mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.0</version>
</dependency>
数据库驱动和连接池:
<!--数据库驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.49</version>
</dependency>
<!--数据库连接池-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.18</version>
</dependency>
2.创建配置文件
jdbc配置文件:
mysql.driver:com.mysql.jdbc.Driver
mysql.url:jdbc:mysql://localhost:3306/javaclass
mysql.username:root
mysql.password:123456
mybatis配置文件:
<?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>
<!--加载外部的properties文件-->
<properties resource="jdbc.properties"></properties>
<!--给类或包下面的类起别名,目标:在接口映射文件中只需要写类名就可以-->
<typeAliases>
<package name="com.ps.ssm.pojo"/>
</typeAliases>
<environments default="mysql">
<environment id="mysql">
<transactionManager type="JDBC"></transactionManager>
<dataSource type="pooled">
<property name="driver" value="${mysql.driver}"/>
<property name="url" value="${mysql.url}"/>
<property name="username" value="${mysql.username}"/>
<property name="password" value="${mysql.password}"/>
</dataSource>
</environment>
</environments>
<!--加载接口映射文件-->
<mappers>
<!--加载指定包下所有的接口映射文件-->
<package name="com.ps.ssm.dao"/>
</mappers>
</configuration>
3.修改数据访问层,获取数据
public interface AccountDao {
@Select("select * from account")
List<Account> findAll();
int save(Account account);
}
4.编写测试代码测试结果
测试代码:
package com.ps.ssm.dao;
import com.ps.ssm.pojo.Account;
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;
public class TestAccountDao {
@Test
public void testFindAll() throws IOException {
//1.创建SqlSessionFactoryBuilder对象
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
//2.读取配置配置文件
InputStream in = Resources.getResourceAsStream("sqlMapConfig.xml");
//3.创建 SqlSessionFactory对象
SqlSessionFactory sessionFactory = sqlSessionFactoryBuilder.build(in);
//4.打开链接
SqlSession sqlSession = sessionFactory.openSession();
//5.获得映射对象
AccountDao mapper = sqlSession.getMapper(AccountDao.class);
//6.调用接口方法
List<Account> all = mapper.findAll();
for (Account account : all) {
System.out.println(account);
}
//7.关闭连接
sqlSession.close();
}
}
测试结果:
四、Spring和SpringMVC整合并测试运行
概述:
由于Spring和SpringMVC都是同一个包下的框架,所以他们可以无缝集成,也就是稍微配置一下就可以了;
修改web.xml配置
修改这里的配置是为了让服务器运行的时候可以加载Spring的配置文件,这样就可以把Spring的IOC和AOP都激活了;
<!--配置加载Spring配置文件,也就是在tomcat启动的时候加载Spring配置文件-->
<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>
修改控制器代码:
@Controller
public class AccountController {
//前面我在业务层实体类上添加了@Service注解,所以这里可以直接获取
@Autowired
private AccountServiceImpl accountService;
@RequestMapping("/find")
public String find() {
List<Account> all = accountService.findAll();
return "list";
}
}
运行tomcat测试结果:
以上这就是Spring和SpringMVC的整合
五、Spring和Mybatis整合并测试运行
1.导入依赖
<!--spring 整个mybatis需要导入的依赖-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.1</version>
</dependency>
这个依赖必须导入,并且这个是由mybatis提供的,如果想进一步了解如何配置的可以取它的官网寻找答案
2.修改Spring中的配置文件
添加数据源,即配置数据库相关
<!--配置事务管理器-->
<bean class="org.springframework.jdbc.datasource.DataSourceTransactionManager" id="transactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!--配置DataSource-->
<bean class="com.alibaba.druid.pool.DruidDataSource" id="dataSource">
<property name="driverClassName" value="${mysql.driver}"></property>
<property name="url" value="${mysql.url}"></property>
<property name="username" value="${mysql.username}"></property>
<property name="password" value="${mysql.password}"></property>
</bean>
<!--加载外部属性文件,即加载外部的数据库驱动文件-->
<context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder>
把Mybatis交由Spring处理,即由Spring创建Mybatis的相关内容:
<!--配置会话工厂对象,负责创建SqlSessionFactory-->
<bean class="org.mybatis.spring.SqlSessionFactoryBean" id="sessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<!--给指定包下的类取别名-->
<property name="typeAliasesPackage" value="com.ps.ssm.pojo"></property>
<!--配置接口映射文件的位置-->
<!-- <property name="mapperLocations" value="classpath:com/ps/ssm/dao/*Mapper.xml"></property>-->
<!--配置mybatis主配置文件位置-->
<!--<property name="configLocation" value="classpath:sqlMapConfig.xml"></property>-->
</bean>
<!--配置代理对象,这个代理对象负责创建接口的代理对象,也就是帮我们创建持久层的代理对象
也可以称为:接口扫描器对象,扫描接口创建接口的实现类对象,而这个实现类对象是代理对象
-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer" id="mapperScannerConfigurer">
<!--配置要扫描那个包,那个包是需要帮助创建代理对象的包-->
<property name="basePackage" value="com.ps.ssm.dao "></property>
</bean>
配置完上面这两个,就不需要mybatis的配置文件了,因为那个配置文件中的内容这里都包含了
3.修改业务层代码
即给业务层添加自动注入
@Service
public class AccountServiceImpl implements AccountService {
@Autowired
private AccountDao accountDao;
public List<Account> findAll() {
System.out.println("find account finished!");
return accountDao.findAll();
}
@Transactional
public void save(Account account) {
System.out.println("保存账户成功!");
}
}
这样配置之后,业务层就可以从Spring的IOC容器中获得Mybatis的相关代理对象,也就是Spring和Mybatis集成完成
4.编写测试代码,测试结果
测试代码:
package com.ps.ssm.service;
import com.ps.ssm.pojo.Account;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.List;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class TestAccountService {
@Autowired
private AccountService accountService;
@Test
public void testFind() {
List<Account> all = accountService.findAll();
for (Account account : all) {
System.out.println(account);
}
}
}
测试结果:
经过上面的配置,其实已经算的SSM完全集成了,那么接下来就要整体测试一下了:
5.SSM整体测试
修改控制器,设置控制器返回json:
package com.ps.ssm.controller;
import com.ps.ssm.pojo.Account;
import com.ps.ssm.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.List;
@Controller
public class AccountController {
@Autowired
private AccountService accountService;
@RequestMapping("/find")
@ResponseBody
public List<Account> find() {
return accountService.findAll();
}
}
修改前端页面,发起Ajax异步请求获取json字符串:
注意,我在这里使用的是jquery3.3.1发送的ajax异步请求
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
list html
<h1>账号列表</h1>
<button onclick="getData()">加载数据</button>
<table id="account_table">
<tr>
<th>账号</th>
<th>编号</th>
<th>金额</th>
</tr>
</table>
<script src="js/jquery-3.3.1.min.js"></script>
<script>
//加载数据
function getData() {
$.get({
url: "find",//url地址
dataType: "json",//返回的数据格式
success: function (list) {//成功回调
var tds = " <tr>\n" +
" <th>账号</th>\n" +
" <th>编号</th>\n" +
" <th>金额</th>\n" +
" </tr>";
$(list).each(function (index, account) {//遍历返回的json对象
tds += "<tr>\n" +
" <td>" + account.id + "</td>\n" +
" <td>" + account.uid + "</td>\n" +
" <td>" + account.money + "</td>\n" +
"</tr>";
});
$("#account_table").html(tds);//把拼接好的结果添加到表格中
},
error: function () {
alert("没有获取到数据");
}
});
}
</script>
</body>
</html>
测试前页面效果:
点击按钮后:
好的,整合结束!