SpringMVC和Mybatis (一)整合思路、整合dao、service、springmvc、加载spring

开发分层开发:前端层,业务层,持久层


sping将各层进行整合:
通过spring管理持久层的mapper
通过spring管理service,可以调用mapper接口,进行事务控制。
通过spring管理Handler,可以调用service接口
mapper、service、Handler都是javaBean


第一步整合dao层
使用mapper的扫描器自动扫描mapper接口在spring中进行注册


第二步整合service层
使用配置方式将service接口配置在spring配置文件中。
实现事务控制,根据业务层在哪里,事务层在哪里。


第三步整合springmvc
不需要整合


1.加载jar包:数据库驱动包、mybatis包、mybatis和spring整合包、log4j包、dbcp数据库连接池包、


spring所有包、jstl包
2.创建config创建log4j.properties

config创建db.properties

3.创建包:controller、mapper、po、service、创建ItemsService.java、service.impl。

4.整合dao(mybatis和spring进行整合)
config创建mybatis包创建sqlMapConfig.xml


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>


<!-- 全局setting -->


<!-- 配置别名 -->
<typeAliases>
<!-- 批量扫描别名 -->
<package name="cn.itcast.ssm.po" />
</typeAliases>


<!-- 配置mapper
由于使用spring和mybatis的整合包进行mapper扫描,这里不需要配置
必须要:mapper、xml和mapper.java同名且在一个目录
-->
 
<!-- <mapperts></mappers> -->


</configuration>


在config创建spring创建applicationContext-dao.xml、applicationContext-service.xml、applicationContext-transaction.xml、springmvc.xml

applicationContext-dao.xml

配置:数据源、SqlSessionFactory


<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"
    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-3.2.xsd 
        http://www.springframework.org/schema/mvc 
        http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd 
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-3.2.xsd 
        http://www.springframework.org/schema/aop 
        http://www.springframework.org/schema/aop/spring-aop-3.2.xsd 
        http://www.springframework.org/schema/tx 
        http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">


  <!-- 加载配置文件 -->
  <context:property-placeholder location="classpath:db.properties" />


<!-- 数据源,使用dbcp -->
        <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
        destroy-method="close">
        <property name="driverClassName" value="${jdbc.driver}" />
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
        <property name="maxActive" value="10" />
        <property name="maxIdle" value="5" />
        </bean>
        
<!-- sqlSessionFactory -->
<!-- 从mybatis-spring内查看class -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 加载mybatis配置文件 -->
<property name="configLocation" value="classpath:mybatis/sqlMapConfig.xml" />
<!-- 数据源 -->
<property name="dataSource" ref="dataSource" />
</bean>

<!-- mapper批量扫描,从mapper包中扫描出mapper接口,自动创建代理对象并且在spring容器中注册 
将mapper接口类名和mapper.xml映射文件名称保存一致,且在一个目录下
自动扫描出来的mapper的bean的id为mapper类名(首字母小写)
-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 指定扫描包的名字
如果扫描多个包,每个包中间使用半角逗号分隔 -->
<property name="basePackage" value="cn.itcast.ssm.mapper" />
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
</bean>

</beans>


编写mapper使用逆向工程
生成:
ssm.mapper和ssm.po的包


针对综合查询mapper,手动定义商品查询mapper
ItemsMapperCustom.xml
sql语句:SELECT * FROM items WHERE NAME LIKE '%批量%'

<?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="cn.itcast.ssm.mapper.ItemsMapperCustom" >


<!-- 定义商品查询的sql片段,就是商品查询条件 -->
<sql id="query_items_where">
<!-- 使用动态sql,通过if判断,满足条件进行sql拼接 -->
<!-- 商品的查询条件通过ItemsQueryVo的包装属性传递 -->
<if test="itemsCustom!=null">
<if test="itemsCustom.name!=null and itemsCustom.name!=''">
items.name LIKE '%${itemsCustom.name}%'
</if>
</if>
</sql>


<!-- 商品的列表查询
parameterType包装了查询条件
resultType使用扩展对象
-->
<select id="findItemsList" parameterType="cn.itcast.ssm.po.ItemsQueryVo" 
resultType="cn.itcast.ssm.po.ItemsCustom">
SELECT * FROM items 
<where>
<include refid="query_items_where"></include>
</where>
</select>


</mapper>



ItemsMapperCustom.java接口
public interface ItemsMapperCustom {


//商品查询列表
public List<ItemsCustom> findItemsList(ItemsQueryVo itemsQueryVo)throws Exception;
}




定义包装对象po类
ItemsQueryVo.java 增加set和get方法
public class ItemsQueryVo {


//商品信息包装进入
private Items items;

//为了系统可以扩展性,对商品信息定义扩展类
private ItemsCustom itemsCustom;


不使用原始的po类,使用扩展类
ItemsCustom.java
//商品信息的扩展类
public class ItemsCustom extends Items{


//添加商品扩展的属性
}
==================================================================================
整合service层
让spring管理service接口。
定义service接口ItemsService.java
//商品管理service
public interface ItemsService {


//商品查询列表
public List<ItemsCustom> findItemsList(ItemsQueryVo itemsQueryVo)throws Exception;
}


service实现类
ItemsServiceImpl.java
public class ItemsServiceImpl implements ItemsService {


@Autowired
private ItemsMapperCustom itemsMapperCustom;

//itemsMapperCustom直接从service传到dao
@Override
public List<ItemsCustom> findItemsList(ItemsQueryVo itemsQueryVo) throws Exception {
// TODO Auto-generated method stub
return itemsMapperCustom.findItemsList(itemsQueryVo);
}


}


在spring容器配置service接口
applicationContext-service.xml
<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"
    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-3.2.xsd 
        http://www.springframework.org/schema/mvc 
        http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd 
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-3.2.xsd 
        http://www.springframework.org/schema/aop 
        http://www.springframework.org/schema/aop/spring-aop-3.2.xsd 
        http://www.springframework.org/schema/tx 
        http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">


<!-- 商品管理的service -->
<bean id="itemsService" class="cn.itcast.ssm.service.impl.ItemsServiceImpl" />
</beans>
事务控制
applicationContext-transation
<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"
    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-3.2.xsd 
        http://www.springframework.org/schema/mvc 
        http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd 
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-3.2.xsd 
        http://www.springframework.org/schema/aop 
        http://www.springframework.org/schema/aop/spring-aop-3.2.xsd 
        http://www.springframework.org/schema/tx 
        http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">


<!-- 事物管理器
对mybatis操作数据库事物控制,spring使用jdbc的事物控制类
 -->
 <bean id="transactionManager" 


class="org.springframework.jdbc.datasource.DataSourceTransactionManager" >
  <!-- 配置数据源
  dataSource已经在applicationContext-dao.xml中配置了 -->
  <property name="dataSource" ref="dataSource" />
 </bean>
 
 <!-- 通知 -->
 <tx:advice id="txAdvice" transaction-manager="transactionManager">
  <tx:attributes>
  <!-- 传播行为 -->
  <tx:method name="save*" propagation="REQUIRED"/>
  <tx:method name="delete*" propagation="REQUIRED"/>
  <tx:method name="insert*" propagation="REQUIRED"/>
  <tx:method name="update*" propagation="REQUIRED"/>
  <tx:method name="find*" propagation="SUPPORTS" read-only="true"/>
  <tx:method name="get*" propagation="SUPPORTS" read-only="true"/>
  <tx:method name="select*" propagation="SUPPORTS" read-only="true"/>
  </tx:attributes>
 </tx:advice>
 
 <!-- aop -->
 <aop:config>
  <aop:advisor advice-ref="txAdvice" pointcut="execution(* 


cn.itcast.ssm.service.impl.*.*(..))"/>
 </aop:config>
</beans>
=====================================================================================
整合springmvc
创建springmvc.xml
<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"
    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-3.2.xsd 
        http://www.springframework.org/schema/mvc 
        http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd 
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-3.2.xsd 
        http://www.springframework.org/schema/aop 
        http://www.springframework.org/schema/aop/spring-aop-3.2.xsd 
        http://www.springframework.org/schema/tx 
        http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">


<!-- 但是在实际开发中建议使用组件扫描 ,可以扫描controller、service-->
<context:component-scan base-package="cn.itcast.ssm.controller" ></context:component-scan>




<!-- 注解映射器 
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping" />-->
<!-- 注解适配器
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter" /> -->


<!-- 使用mvc:annotation-driven 代替上边的注解映射器和注解适配器
mvc:annotation-driven默认加载很多的参数绑定方法,比如json转换解析器就默认加载了,如果使用mvc:annotation-driven不用配置上边的RequestMappingHandlerMapping和RequestMappingHandlerAdapter
实际开发使用的也是这个mvc:annotation-driven -->
<mvc:annotation-driven></mvc:annotation-driven>




<!-- 视图解析器 
解析jsp解析,默认使用jstl标签,classpath下面得有jstl的包-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 配置jsp路径的前缀 -->
<property name="prefix" value="/WEB-INF/jsp/" />
<!-- 配置jsp路径的后缀 -->
<property name="suffix" value=".jsp" />
</bean>


</beans>


配置前端控制器
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" id="WebApp_ID" version="2.5">
  <display-name>springmv_mybatis1208</display-name>
  
  
  <!-- springmvc前段控制器 -->
  <servlet>
  <servlet-name>springmvc</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  <!-- contextConfigLocation配置springmvc加载的配置文件(配置处理器映射器、适配器等等) 
  如果不配置contextConfigLocation默认加载/WEB-INF/servlet名称-servlet.xml(springmvc-


servlet.xml)-->
  <init-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>classpath:spring/springmvc.xml</param-value>
  </init-param>
  </servlet>
  
  <servlet-mapping>
  <servlet-name>springmvc</servlet-name>
  <!-- 第一种:*.action,访问.action结尾由DispatcherServlet进行解析
  第二种:/,所有访问的地址都由DispatcherServlet进行解析,对于静态的文件解析,要配置不让


DispatcherServlet进行解析
  使用此种方法可以实现RESTful风格的url -->
  <url-pattern>*.action</url-pattern>
  </servlet-mapping>
  
  
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
</web-app>


编写Handler(Controller)

ItemsController.java


//使用Controller标识他是一个控制器
@Controller
public class ItemsController {

//注入service
@Autowired
private ItemsService itemsService;


//商品查询列表
//一般建议将url和方法名写成一样,方便queryItems和url进行映射,一个方法对应一个url
@RequestMapping("/queryItems")
public ModelAndView queryItems()throws Exception{
//调用service查找数据库,查询商品,这里先使用静态模拟
List<ItemsCustom> itemsList = itemsService.findItemsList(null);

//返回ModelAndView
ModelAndView modelAndView = new ModelAndView();
//相当于request的setAttribut,在jsp页面中通过itemsList取数据
modelAndView.addObject("itemsList",itemsList);

//指定视图
//下边的路径,如果在视图解析器中配置jsp路径的前缀和jsp路径的后缀,就改为
//modelAndView.setViewName("/WEB-INF/jsp/items/itemsList.jsp");
//上边的路径配置可以不再程序中指定jsp路径的前缀和jsp路径的后缀
modelAndView.setViewName("items/itemsList");
return modelAndView;
}


编写jsp

itemsList.jsp


<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"
contentType="text/html; charset=UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>



<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    
    <title>check list</title>
    
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">    
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->


  </head>
  
  <body>
  <form action="${pageContext.request.contextPath }/item/queryItem.action" method="post">
  查询条件:
  <table width="100%" border=1>
  <tr>
  <td><input type="submit" value="查询" /></td>
  </tr>
  </table>
  商品列表:
  <table width="100%" border=1>
  <tr>
  <td>商品名称</td>
  <td>商品价格</td>
  <td>生产日期</td>
  <td>商品描述</td>
  <td>操作</td>
  </tr>
  <c:forEach items="${itemsList }" var="item">
  <tr>
  <td>${item.name }</td>
  <td>${item.price }</td>
  <td><fmt:formatDate value="${item.createtime }" pattern="yyyy-MM-dd HH:mm:ss" /></td>
  <td>${item.detail }</td>
 
  <td><a href="${pageContext.request.contextPath }/editItem.action?id=${item.id}">修改</a></td>
  </tr>
  </c:forEach>
  </table>
  </form>
  </body>
</html>


=====================================================================================
加载spring容器
把dao、service、transaction
建议使用通配符加载上边的配置文件
在web.xml添加spring容器监听器,加载spring容器。
<?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" id="WebApp_ID" version="2.5">
  <display-name>springmv_mybatis1208</display-name>
  
  <!-- 加载spring容器 
  <param-value>/WEB-INF/classes/spring/applicationContext.xml,/WEB-


INF/classes/spring/applicationContext-*.xml</param-value>-->
  <context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>/WEB-INF/classes/spring/applicationContext-*.xml</param-value>
  </context-param>
  <listener>
  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值