一、spring整合springmvc、mybatis
二、配置文件+注解
1、创建相应的类:dao,controller,domain,service,service.impl
2、首先配置spring,使用注解方式
编写applicationContext.xml文件
<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不需要spring框架处理,排除掉controller包不扫描-->
<context:component-scan base-package="cn.rzpt">
<!-- 配置哪些注解不扫描-->
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
</beans>
@Service("accountServiceImpl")
public class AccountServiceImpl implements AccountService
测试
3、配置springMVC环境
在web.xml配置全端控制器
<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>
<!-- 加载springMVC.xml文件-->
<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: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">
<!-- 开启注解扫描,只扫描controller注解-->
<context:component-scan base-package="cn.rzpt">
<!-- 开启扫描哪个类-->
<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 mapping="/css/**" location="/css/"/>
<mvc:resources mapping="/images/**" location="/images/"/>
<mvc:resources mapping="/js/**" location="/js/"/>
<!-- 开启springmvc注解的支持-->
<mvc:annotation-driven />
</beans>
测试:编辑jsp文件
<a href="account/findAll">测试</a>
编辑controller类
@Controller
@RequestMapping("/account")
public class AccountController {
@RequestMapping("/findAll")
public String findAll(){
System.out.println("表现层:查询所有账户信息.....");
return "list";
}
}
编辑list.jsp
<h3>查询所有账户信息</h3>
4、spring整合springmvc
思路:在controller中能够调用service方法,则表示整合成功
在controller中依赖注入service对象就可以
那么什么时候构建service对象?
因为tomcat服务器启动,加载web.xml文件,并没有加载applicationConfig.xml
需要在web.xml中配置一个监听器类,用来监听ServletContext的创建和销毁,并提供WEB版本工厂,存储在ServletContext对象中
这个监听器有spring-web提供org.springframework.web.context.ContextLoaderListener
<web-app>
<display-name>Archetype Created Web Application</display-name>
<!-- 配置spring的监听器.默认只加载WEB-INF目录下的applicationContext.xml文件
可以设置配置文件的路径
-->
<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>
controller类中:
@Controller
@RequestMapping("/account")
public class AccountController {
@Autowired
private AccountService accountService;
@RequestMapping("/findAll")
public String findAll(){
System.out.println("表现层:查询所有账户信息.....");
//调用service方法,成功调用整合
accountService.findAll();
return "list";
}
}
5、mybatis配置(采用注解方式)
核心配置文件SqlMapConfig.xml需要配置
与dao匹配的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="zxn682899"/>
</dataSource>
</environment>
</environments>
<!-- 引入映射配置文件-->
<mappers>
<!-- resource是使用配置文件的方式,使用注解的话不能使用resource-->
<!-- <mapper resource="cn/rzpt/dao/AccountDao.xml"></mapper>-->
<!-- <mapper class="cn.rzpt.dao.AccountDao"/>-->
<!-- 使用package,包内的所有类都可以访问到-->
<package name="cn.rzpt.dao"/>
</mappers>
</configuration>
dao注解:
@Repository
public interface AccountDao {
//查询所有账户
@Select("select * from account")
public List<Account> findAll();
//保存账户信息
@Insert("insert into account (name,money) values(#{name},#{money})")
public void saveAccount(Account account);
}
测试类:
@Test
public void run1() throws IOException {
//加载配置文件
InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
//创建SQLSessionFactory对象
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
//创建SqlSession对象
SqlSession session = factory.openSession();
//获取到代理对象
AccountDao dao = session.getMapper(AccountDao.class);
//查询所有数据
List<Account> list = dao.findAll();
for(Account account : list){
System.out.println(account);
}
//关闭资源
session.close();
in.close();
}
6、spring整合mybatis
思路:如何把代理对象存到spring容器中
//获取到代理对象 AccountDao dao = session.getMapper(AccountDao.class);
在applicationConfig.xml中配置mybatis整合
<!--spring整合mybatis框架-->
<!-- 1:配置连接池-->
<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="zxn68289"/>
</bean>
<!-- 2:配置SqlSessionFactory-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- 3:配置AccountDao接口所在包-->
<bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="cn.rzpt.dao"/>
</bean>
service中:
@Service("accountService")
public class AccountServiceImpl implements AccountService {
@Autowired
private AccountDao accountDao;
@Override
public List<Account> findAll() {
System.out.println("业务层查询所有账户信息。。。。。。。。");
return accountDao.findAll();
}
@Override
public void saveAccount(Account account) {
System.out.println("业务层保存账户信息。。。。。。。。。。。");
accountDao.saveAccount(account);
}
}
controller中
@Controller
@RequestMapping("/account")
public class AccountController {
@Autowired
private AccountService accountService;
@RequestMapping("/findAll")
public String findAll(Model model){
System.out.println("表现层:查询所有账户信息.....");
//调用service方法,成功调用整合
List<Account> list = accountService.findAll();
model.addAttribute("list",list);
return "list";
}
}
list.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="${list}" var="account">
${account.name}<br>
${account.money}<br>
</c:forEach>
注意&符合改成:&;
?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8
7、spring整合mybatis事务框架
保存数据需要事务开启
配置事务在apllication中,加入:
<!-- 配置spring框架声明式事务管理--> <!-- 1:配置事务管理器--> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean> <!-- 2:配置事务通知--> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="find*" read-only="true"/> <tx:method name="*"/> </tx:attributes> </tx:advice> <!-- 3:配置AOP增强--> <aop:config> <aop:advisor advice-ref="txAdvice" pointcut="execution(* cn.rzpt.service.impl.*ServiceImpl.*(..))"/> </aop:config>
index.jsp:
<h3>测试保存</h3> <form action="account/save" method="post"> 姓名:<input type="text" name="name"/><br/> 金额:<input type="text" name="money"/><br/> <input type="submit" value="保存"> </form>
AccountController中:
@RequestMapping("/save") public String save(Account account){
//注意account的自动封装,从jsp来的数据
System.out.println("表现层:保存账户信息....."); //调用service方法,成功调用整合 accountService.saveAccount(account); return "list"; }
也可以: