SSM整合
项目准备
-
创建MAVEN工程,在
pom.xml
引入坐标如下<properties> <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.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> <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> <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>
-
数据库准备
创建数据库表
accounts
及其实体类Account
DROP TABLE IF EXISTS accounts; create table accounts( id int primary key auto_increment, name varchar(20), money double ); insert into accounts(`name`, `money`) values ('路人1', '100'), ('路人2', '99.8');
package cn.maoritian.domain; import java.io.Serializable; // 账户实体类 public class Account implements Serializable { private Integer id; private String name; private Double money; public Integer getId() {return id; } public void setId(Integer id) {this.id = id; } public String getName() {return name; } public void setName(String name) {this.name = name; } public Double getMoney() {return money; } public void setMoney(Double money) {this.money = money; } @Override public String toString() {return "Account{" + "id=" + id + ", name='" + name + '\'' + ", money=" + money + '}'; } }
-
编写DAO层,SERVICE层接口及实现类
DAO层接口,其实现类由Mybatis通过反射创建
package cn.maoritian.dao; // 账户DAO层接口 @Repository public interface IAccountDao { // 查询所有账户 public List<Account> findAll(); // 保存帐户 public void saveAccount(Account account); }
SERVICE层接口及其MOCK实现类.
package cn.maoritian.service; // 账户SERVICE层接口 public interface AccountService { // 查询所有账户 public List<Account> findAll(); // 保存帐户 public void saveAccount(Account account); }
package cn.maoritian.service.impl; // 账户SERVICE层实现类 @Service("accountService") public class AccountServiceImpl implements AccountService { // @Autowired // private AccountDao accountDao; // 查询所有账户 public List<Account> findAll() { System.out.println("MOCK Service层方法:查询所有账户"); return null; } // 保存帐户 public void saveAccount(Account account) { System.out.println("MOCK Service层方法:保存帐户"); return; } }
编写Spring框架代码
-
在
resources
目录下编写Spring配置文件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"> <!-- 开启注解扫描,我们希望Controller层由SpringMVC管理,因此不能扫描@Controller注解 --> <context:component-scan base-package="cn.maoritian" > <!-- 配置不扫描@Controller注解 --> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" /> </context:component-scan> </beans>
-
编写测试类如下,通过测试:
package cn.maoritian.test; public class TestSpring { @Test public void testFindAll() { ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:applicationContext.xml"); AccountService accountService = (AccountService) applicationContext.getBean("accountService"); accountService.findAll(); } @Test public void testSaveAccount() { ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:applicationContext.xml"); AccountService accountService = (AccountService) applicationContext.getBean("accountService"); accountService.saveAccount(new Account()); } }
编写SpringMVC代码
配置SpringMVC
-
在项目的
webapp/WEB-INF/web.xml
中配置前端控制器和解决中文乱码的编码过滤器<!-- 前端控制器,启动时加载springmvc.xml文件 --> <servlet> <servlet-name>dispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- 初始化参数:加载springmvc.xml文件 --> <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> <!-- 设置编码为UTF-8 --> <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>
在这里要注意两个组件的
url-pattern
不同- 前端控制器的
url-pattern
为/
,表示 - 编码过滤器的
url-pattern
为/*
,表示过滤所有请求
这两个
url-pattern
的区别见Difference between / and /* in servlet mapping url pattern - 前端控制器的
-
在
resources
路径下创建SpringMVC配置文件springmvc.xml
如下:<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" 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 http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 开启注解扫描,SpringMVC只扫描Controller注解 --> <context:component-scan base-package="cn.maoritian"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> <!-- 配置的视图解析器 --> <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/pages/"/> <property name="suffix" value=".jsp"/> </bean> <!--过滤静态资源--> <mvc:resources location="/css/" mapping="/css/**"/> <mvc:resources location="/images/" mapping="/images/**"/> <mvc:resources location="/js/" mapping="/js/**"/> <!--开启SpringMVC注解的支持--> <mvc:annotation-driven/> </beans>
-
创建CONTRLLER层对象以及对应的jsp如下
package cn.maoritian.controller; @Controller @RequestMapping("/account") public class AccountController { @Autowired private AccountService accountService; // 调用Service层方法并展示 @RequestMapping("/findAll") public String findAll(Model model) { List<Account> AccountList = accountService.findAll(); model.addAttribute("AccountList", AccountList); return "displayAccounts"; } // 调用Service层方法并转到展示所有视图 @RequestMapping("/save") public void save(Account account, HttpServletRequest request, HttpServletResponse response) throws IOException { accountService.saveAccount(account); response.sendRedirect(request.getContextPath() + "/account/findAll"); return; } }
在
/webapp/WEB_INF/pages
目录下创建jsp视图displayAccounts.jsp
<%@ 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="${accountList}" var="accountList"> ${accountList.toString()}<br/> </c:forEach> </body> </html>
Spring整合SpringMVC
在web.xml
中配置监听器ContextLoaderListener
,该监听器可以监听ServletContext
的创建和销毁(ServletContext
的创建和销毁与TOMCAT是同步的),将applicationContext.xml
配置成为其初始化参数.
<!-- 配置Spring的监听器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listenerclass>
</listener>
<!-- 配置加载类路径的配置文件 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
编写Mybatis代码
配置SpringMVC
-
在项目的
/resources
目录下创建Mybatis配置文件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"/> <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="root"/> </dataSource> </environment> </environments> <!-- 配置mappers --> <mappers> <package name="cn.maoritian.dao"/> </mappers> </configuration>
-
为DAO层方法配置注解
package cn.maoritian.dao; // 账户DAO层接口 @Repository public interface IAccountDao { // 查询所有账户 @Select("select * from accounts") public List<Account> findAll(); // 保存帐户 @Insert("insert into accounts (name,money) values (#{name},#{money})") public void saveAccount(Account account); }
-
编写测试类如下,通过测试:
package cn.maoritian.test; public class TestMybatis { IAccountDao accountDao = null; SqlSession sqlSession = null; InputStream sqlConfig = null; @Before public void init() throws IOException { sqlConfig = Resources.getResourceAsStream("SqlMapConfig.xml"); SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(sqlConfig); sqlSession = factory.openSession(); accountDao = sqlSession.getMapper(IAccountDao.class); } @After public void destroy() throws IOException { sqlSession.commit(); sqlSession.close(); sqlConfig.close(); } @Test // 测试查询方法 public void testFindAll() { List<Account> list = accountDao.findAll(); for (Account account : list) { System.out.println(account); } } @Test // 测试增加方法 public void testSaveAccount() throws IOException { Account account = new Account(); account.setName("熊大"); account.setMoney(400d); accountDao.saveAccount(account); } }
Spring整合Mybatis
我们将SqlSession
的创建过程托管给Spring容器,因此我们就不再需要SqlMapConfig.xml
了,而是要转而在applicationContext.xml
中配置Mybatis.
<!-- 配置Spring整合Mybatis框架 -->
<!-- 配置数据库连接池 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"/>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/mydatabase"/>
<property name="user" value="root"/>
<property name="password" value="123456"/>
</bean>
<!--配置SqlSessionFactory工厂-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
</bean>
<!-- 配置AccountDao -->
<bean id="accountDao" class="org.mybatis.spring.mapper.MapperFactoryBean">
<property name="mapperInterface" value="cn.maoritian.dao.IAccountDao" />
<property name="sqlSessionFactory" ref="sqlSessionFactory" />
</bean>
<!-- 配置Spring框架声明式事务管理 -->
<!--配置事务管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<!--配置事务通知-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="find*" read-only="true"/>
<tx:method name="*" isolation="DEFAULT"/>
</tx:attributes>
</tx:advice>
<!--配置AOP增强-->
<aop:config>
<aop:advisor advice-ref="txAdvice" pointcut="execution(* cn.maoritian.service.impl.*ServiceImpl.*(..))"/>
</aop:config>
然而没有整合成功,Spring容器中没有DAO实现类,明天来解决这个问题.