文章目录
整体结构

结构图

Spring 整合SpringMVC
整合SpringMVC我们需要将Spring的配置文件加载到服务器中(配置Spring ioc容器)。
我们可以使用Spring的ContextLoaderListener 监听器去监听ServletContext的生命周期。
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
在启动服务器时监听ServletContext的创建,在这时载入Spring的配置文件,这样就整合成功了。但是有个细节。ContextLoaderListener 默认加载只加载WEB-INF目录下的的applicationContext.xml文件,所以我们Spring的配置文件的名称要设置为applicationContext.xml,但是在一般情况下我们的配置文件都会在resouces下面也就是服务器中WEB-INF/classes下面。所以我们需要配置文件路径:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
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">
<!-- 配置spring的ContextLoaderListener监听器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 设置配置文件路径-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!-- 配置前端控制器-->
<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>
<!-- 启动服务器就创建该servlet-->
<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
<?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"
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/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
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- 注解扫描的包 -->
<context:component-scan base-package="com">
<!-- 只扫描的注解-->
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!-- 过滤的静态资源-->
<mvc:resources mapping="/js/" location="/js/**"></mvc:resources>
<mvc:resources mapping="/css/" location="/css/**"></mvc:resources>
<mvc:resources mapping="/imgs/" location="/imgs/**"></mvc:resources>
<!--配置视图解析器对象-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">
<property name="prefix" value="/jsp/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<!-- 开启注解驱动 -->
<mvc:annotation-driven></mvc:annotation-driven>
</beans>
Spring整合Mybatis
我们将Mybatis的配置集成的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">
<!--开启注解的扫描,只希望扫描service和dao,controller不需要-->
<context:component-scan base-package="com">
<!-- 配置哪些注解不扫描-->
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!-- spring 整合Mybatis框架-->
<!-- 引入外部jdbc配置文件-->
<context:property-placeholder location="classpath:db.properties"></context:property-placeholder>
<!-- 配置数据库连接池-->
<bean class="org.apache.ibatis.datasource.pooled.PooledDataSource" id="dataSource">
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<!-- 配置 SqlSessionFactory 工厂-->
<bean class="org.mybatis.spring.SqlSessionFactoryBean" id="sqlSessionFactory">
<!-- 指定数据源 -->
<property name="dataSource" ref="dataSource"></property>
<!-- 自动扫描mapping.xml文件,**表示迭代查找 ,,也可在mybatis-config.xml中单独指定xml文件 -->
<property name="mapperLocations" value="classpath:mybatis/**/*.xml"></property>
</bean>
<!--配置mybatis扫描所在的包-->
<!-- 自动扫描com/dao下的所有dao接口,并实现这些接口,可直接在程序中使用dao接口,不用再获取sqlsession对象 -->
<bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- basePackage 属性是映射器接口文件的包路径。
你可以使用分号或逗号 作为分隔符设置多于一个的包路径-->
<property name="basePackage" value="com.dao"></property>
</bean>
<!--
Spring 中基于xml的声明式事务控制配置步骤
1、配置事务管理器 DataSourceTransactionManager
2、配置事务的通知
此时我们需要导入事务的约束 tx名称空间和约束,同时也需要aop的
使用tx:advice 标签配置事务通知
属性:
id:给事务通知起一个唯一标志
transaction-manager:给事务通知提供一个事务管理器引用
3、配置AOP中的通用切入点表达式
4、建立切入点表达式与事务通知的对应关系
5、配置事务的属性
是在事务的通知tx:advice 标签内部配 <tx:attributes>
配置事务的属性
isolation:用于指定事务的隔离级别,默认值是DEFAULT,表示使用数据库的默认隔离级别。
propagation:用于指定事务的传播行为,默认值是REQUIRED,表示一定有事务,增删改的选择。查询方法可以使用SUPPORTS
read-only:用于指定事务是否只读。只有查询方法才设置为true,默认值为false,表示读写。
timeout:用于指定事务的超时时间,默认值为-1,表示永不超时。如果设置了指定值,以秒为单位。
rollback-for:用于指定一个异常,当产生该异常时,事务回滚,如果产生其他异常,事务不回滚。没有默认值。表示任何异常都回滚。
no-rollback-for:用于指定一个异常,当产生该异常时,事务不回滚,产生其他异常时事务回滚。没有默认值。表示任何异常都回滚。
-->
<!-- 配置事务管理器-->
<bean class="org.springframework.jdbc.datasource.DataSourceTransactionManager" id="transactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 配置事务的通知-->
<tx:advice transaction-manager="transactionManager" id="txAdvice">
<tx:attributes>
<tx:method name="find*" read-only="true" propagation="SUPPORTS"/>
<tx:method name="save*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
<!-- 配置AOP-->
<aop:config>
<!-- 配置切入点表达式-->
<aop:pointcut id="pt1" expression="execution(* com.servcie.impl.*.*(..))"></aop:pointcut>
<!-- 建立切入点表达式与事务通知的对应关系-->
<aop:advisor advice-ref="txAdvice" pointcut-ref="pt1"></aop:advisor>
</aop:config>
</beans>
代理接口的配置accountDaoimpl.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">
<mapper namespace="com.dao.AccountDao">
<select id="findAll" resultType="com.domain.Account">
select *from account;
</select>
<insert id="saveAccount" parameterType="com.domain.Account">
insert into account (name,money) values(#{name},#{money});
</insert>
</mapper>
其余代码
表现层
package com.controller;
import com.domain.Account;
import com.servcie.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.annotation.Resource;
import java.util.List;
/**
* 账户表现层
*/
@Controller
@RequestMapping("/account")
public class AccountController {
@Resource(name = "accountService") // @Autowired
private AccountService accountService;
@RequestMapping("/findAll")
public String findAll(Model model) {
System.out.println("表现层:查询所有账户");
final List<Account> accounts = accountService.findAll();
// System.out.println(accounts);
model.addAttribute("accounts", accounts);
return "list";
}
@RequestMapping("saveAccount")
public String saveAccount(Account account, Model model) {
accountService.saveAccount(account);
final List<Account> accounts = accountService.findAll();
model.addAttribute("accounts", accounts);
return "list";
}
}
业务层
package com.servcie.impl;
import com.dao.AccountDao;
import com.domain.Account;
import com.servcie.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service("accountService")
public class AccountServiceimpl implements AccountService {
@Autowired
private AccountDao accountDao;
@Override
public List<Account> findAll() {
System.out.println("业务层:查询所有账户信息");
final List<Account> all = accountDao.findAll();
return all;
}
@Override
public void saveAccount(Account account) {
System.out.println("业务层:保存账户");
accountDao.saveAccount(account);
}
}
持久层
package com.dao;
import com.domain.Account;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
* 账户的dao接口
*/
@Repository
public interface AccountDao {
//查询所有账户
// @Select("select *from Account")
List<Account> findAll();
//保存账户
// @Insert("insert into account (name,money) values(#{name},#{money})")
void saveAccount(Account account);
}
domain
package com.domain;
import java.io.Serializable;
public class Account implements Serializable {
private Integer id;
private String name;
private Double money;
@Override
public String toString() {
return "Account{" +
"id=" + id +
", name='" + name + '\'' +
", money=" + 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;
}
}
查询效果展示

附上spring约束
spring约束
<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">
<!--开启注解的扫描,只希望扫描service和dao,controller不需要-->
<context:component-scan base-package="com">
<!-- 配置哪些注解不扫描-->
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
</beans>
SpringMVC约束
<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"
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/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
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- 注解扫描的包 -->
<context:component-scan base-package="com">
<!-- 只扫描的注解-->
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!-- 开启注解驱动-->
<mvc:annotation-driven></mvc:annotation-driven>
</beans>
Maven 依赖
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-oxm</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.5</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.3</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.4</version>
</dependency>
<!-- 整合Spring -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.4</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.12</version>
</dependency>
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>
</dependencies>
本文详细介绍了如何在Spring MVC框架下整合MyBatis,包括配置Spring、Spring MVC和MyBatis,以及实现数据库操作的具体步骤。通过示例代码展示了如何配置监听器、前端控制器、事务管理、注解驱动等,最终实现账户信息的查询和保存。
8727

被折叠的 条评论
为什么被折叠?



