【Web开发】springmvc3.2+mybatis2.3.7整合

====springmvc和mybatis整合、
===========》准备《====================
---导入jar包:
jar包明细如下:
commons-logging-1.1.1.jar
jstl-1.2.jar  
//如果tomcat服务器不支jstl-1.2.jar标签----》请将此jar包放在tomcat的lib(apache-tomcat-7.0.57\lib)目录下
spring-aop-3.2.0.RELEASE.jar
spring-aspects-3.2.0.RELEASE.jar
spring-beans-3.2.0.RELEASE.jar
spring-context-3.2.0.RELEASE.jar
spring-context-support-3.2.0.RELEASE.jar
spring-core-3.2.0.RELEASE.jar
spring-expression-3.2.0.RELEASE.jar
spring-jdbc-3.2.0.RELEASE.jar
spring-orm-3.2.0.RELEASE.jar
spring-test-3.2.0.RELEASE.jar
spring-tx-3.2.0.RELEASE.jar
spring-web-3.2.0.RELEASE.jar
spring-webmvc-3.2.0.RELEASE.jar


aopalliance-1.0.jar  通常Spring等其它具备动态织入功能的框架依赖此包
asm-3.3.1.jar
aspectjweaver-1.6.11.jar
cglib-2.2.2.jar


commons-dbcp-1.2.2.jar   dbcp连接池
commons-pool-1.3.jar


javassist-3.17.1-GA.jar
junit-4.9.jar
log4j-1.2.17.jar
log4j-api-2.0-rc1.jar
log4j-core-2.0-rc1.jar
mybatis-3.2.7.jar
mybatis-spring-1.2.2.jar
mysql-connector-java-5.1.7-bin.jar  连接mysql数据库的jar包
slf4j-api-1.7.5.jar
slf4j-log4j12-1.7.5.jar




创建数据库mybatis 数据建表items;和插入测试数据:


CREATE DATABASE mybatis  DEFAULT CHARACTER SET utf8 ;


USE mybatis;




DROP TABLE IF EXISTS items;


CREATE TABLE items (
  id INT(11) NOT NULL AUTO_INCREMENT,
  NAME VARCHAR(32) NOT NULL COMMENT '商品名称', --COMMENT '商品名称'设置字段描述
  price FLOAT(10,1) NOT NULL COMMENT '商品定价',
  detail TEXT COMMENT '商品描述',
  pic VARCHAR(64) DEFAULT NULL COMMENT '商品图片',
  createtime DATETIME NOT NULL COMMENT '生产日期',
  PRIMARY KEY (`id`)
) ENGINE=INNODB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;


/*Data for the table `items` */


INSERT  INTO items(`id`,`name`,`price`,`detail`,`pic`,`createtime`) VALUES
 (1,'台式机',3000.0,'该电脑质量非常好!!!!',NULL,'2015-02-03 13:22:53'),
(2,'笔记本',6000.0,'笔记本性能好,质量好!!!!!',NULL,'2015-02-09 13:22:57'),
(3,'背包',200.0,'名牌背包,容量大质量好!!!!',NULL,'2015-02-06 13:23:02');


=>工程==》build path==>configure builde path ===>default out folder 项填写:工程名/WebRoot/WEB-INF/classes
 src 
   -cn.ssm.controller
        -ItemsTest.java     
   -cn.ssm.mapper
        -ItemsMapper.java
        -ItemsMapper.xml  
   -cn.ssm.po
        -Items.java
   -cn.ssm.service
        -ItemsService.java   
   -cn.ssm.service.impl    
        -ItemsServiceImpl.java
  config
     -mybatis
-sqlMapConfig.xml
     -spring
  -applicationContext-dao.xml
-applicationContext-service.xml
-applicationContext-transaction.xml
      db.properties
      log4j.properties 


   WebRoot
     WEB-INF
         jsp
           items
             itemsList.jsp




准备Properties文档
===》db.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis
jdbc.username=root
jdbc.password=root


===》log4j.properties


# Global logging configuration 
# debug:  log4j.rootLogger=DEBUG, stdout   publish; log4j.rootLogger=info, stdout
log4j.rootLogger=DEBUG, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d%5p [%t] - %m%n








===============源码=======================


--------(1:)写PO类  Items.java
package cn.ssm.po;


import java.util.Date;


public class Items {
    private Integer id;


    private String name;


    private Float price;


    private String pic;


    private Date createtime;


    private String detail;


    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 == null ? null : name.trim();
    }


    public Float getPrice() {
        return price;
    }


    public void setPrice(Float price) {
        this.price = price;
    }


    public String getPic() {
        return pic;
    }


    public void setPic(String pic) {
        this.pic = pic == null ? null : pic.trim();
    }


    public Date getCreatetime() {
        return createtime;
    }


    public void setCreatetime(Date createtime) {
        this.createtime = createtime;
    }


    public String getDetail() {
        return detail;
    }


    public void setDetail(String detail) {
        this.detail = detail == null ? null : detail.trim();
      /*  if(detail == null)
        {
        this.detail = null;
        }else{
        this.detail = detail.trim();
        }*/
    }
}




(2)======mybatis======>使用的是Mapper代理<=======================
说明:a:ItemsMapper.java 和 ItemsMapper.xml名字相同:后缀不一样
      b:ItemsMapper.xml的命名空间为所在包名cn.ssm.mapper.ItemsMapper
      c:ItemsMapper.java 和 ItemsMapper.xml在同一包下
      d:ItemsMapper.java的方法名和ItemsMapper.xml对应sql语句名称一致
以上条件缺一出现如下异常
  org.apache.ibatis.binding.BindingException: Invalid bound statement (not found):
cn.ssm.mapper.ItemsMapper.findItemsList






-----》ItemsMapper.java


package cn.ssm.mapper;


import java.util.List;


import cn.ssm.po.Items;


public interface ItemsMapper {


public List<Items> findItemsList(Items items)throws Exception;
}


----->ItemsMapper.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="cn.ssm.mapper.ItemsMapper" >
 
  <!-- 商品列表查询 -->
  <!-- parameterType传入包装对象(包装了查询条件)
  resultType建议使用扩展对象
  -->
  <select id="findItemsList" parameterType="cn.ssm.po.Items"
  resultType="cn.ssm.po.Items">
  SELECT * FROM items where 1=1 
  </select>
</mapper>


-----》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.ssm.po"/>
</typeAliases>


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


<!-- <mappers>

</mappers> -->
</configuration>





   

</beans>




(3):============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 ">
<!--注解映射器 -->
<!-- <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>
    <!--cotrallor(多个)配置-->
    <context:component-scan base-package="cn.ssm.controller"></context:component-scan>
   
    <!-- 视图解析器
解析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>




------applicationContext-dao.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 ">
<!-- 加载db.properties文件中的内容,db.properties文件中key命名要有一定的特殊规则 -->
   <context:property-placeholder location="classpath:db.properties" />
   
   <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="30" />
<property name="maxIdle" value="5" />
</bean>
   
   <!-- sqlSessionFactory 得到一个连接 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">


<!-- 数据库连接池 -->
<property name="dataSource" ref="dataSource" />
<!-- 加载mybatis的全局配置文件 -->
<property name="configLocation" value="classpath:mybatis/sqlMapConfig.xml" />
</bean>

<!-- mapper扫描器 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 扫描包路径,如果需要扫描多个包,中间使用半角逗号隔开 -->
<property name="basePackage" value="cn.ssm.mapper"></property>
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
</bean>
</beans>




------》applicationContext-transaction.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 ">


<!-- 事务管理器 
对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>
<!-- 传播行为 对以save、delete、insert、 update方法开头的进行事物-->
<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  对包‘cn.itcast.ssm.service.impl’包下的所有方法进行切面插入 -->
<aop:config>
<aop:advisor advice-ref="txAdvice" pointcut="execution(* cn.ssm.service.impl.*.*(..))"/>
</aop:config>


</beans>






  
(3)========》service层配置<===================
------ItemsService.java


package cn.ssm.service;


import java.util.List;


import cn.ssm.po.Items;


public interface ItemsService {
public List<Items> findItemsList(Items items)  throws  Exception;
}


------ItemsServiceImpl.java
package cn.ssm.service.impl;


import java.util.List;


import org.springframework.beans.factory.annotation.Autowired;


import cn.ssm.mapper.ItemsMapper;
import cn.ssm.po.Items;
import cn.ssm.service.ItemsService;


public class ItemsServiceImpl implements  ItemsService{
@Autowired
         //@Autowired表示使用set注入
private ItemsMapper itemsMapper;


public ItemsMapper getItemsMapper() {
return itemsMapper;
}




public void setItemsMapper(ItemsMapper itemsMapper) {
this.itemsMapper = itemsMapper;
}




@Override
public List<Items> findItemsList(Items items) throws Exception {


// TODO Auto-generated method stub
return itemsMapper.findItemsList(items);
}




}




-----》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 ">
<bean id="ItemsServiceImpl" class="cn.ssm.service.impl.ItemsServiceImpl"></bean>

</beans>






(4)======》和页面交互=======================
---》ItemsTest.java
package cn.ssm.controller;


import java.util.List;


import javax.servlet.http.HttpServletRequest;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;


import cn.ssm.po.Items;
import cn.ssm.service.ItemsService;


@Controller
//为了对url进行分类管理 ,可以在这里定义根路径,最终访问url是根路径+子路径
//比如:商品列表:/items/queryItems.action
@RequestMapping("/items") 


/**
 * @RequestMapping("/items")放在类之前表示根目录,指定需要访问的方法时:
 * “根+方法目录”(http://localhost:8080/Test/items/queryItems.action)
 * @author bridge
 * @date   2015年11月14日
 * @版本 1.1
 */


public class ItemsTest  {
@Autowired
private ItemsService itemsService;


public ItemsService getItemsService() {
return itemsService;
}


public void setItemsService(ItemsService itemsService) {
this.itemsService = itemsService;
}


//商品查询
@RequestMapping("/queryItems")
public ModelAndView queryItems(HttpServletRequest request) throws Exception {
//测试forward后request是否可以共享

System.out.println(request.getParameter("id"));


// 调用service查找 数据库,查询商品列表
List<Items> 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;


}
}






--->itemsList.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="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" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>查询商品列表</title>
</head>
<body> 
<%-- ${pageContext.request.contextPath 得到根目录--%>
<form action="${pageContext.request.contextPath }/queryItems.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 }/item/editItem.action?id=${item.id}">修改</a></td>


</tr>
</c:forEach>


</table>
</form>
</body>


</html>










================全部交由web容器管理========>
------->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_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>Test</display-name>
  
  <!-- 加载spring容器 -->
<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>
  
  
   <!-- 加载springmvc控制器 -->
   <servlet>
  <servlet-name>springmvc</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  <!-- contextConfigLocation配置springmvc加载的配置文件(配置处理器映射器、适配器等等)
  如果不配置contextConfigLocation,默认加载的是/WEB-INF/servlet名称-serlvet.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
  第三种:/*,这样配置不对,使用这种配置,最终要转发到一个jsp页面时,
  仍然会由DispatcherServlet解析jsp地址,不能根据jsp页面找到handler,会报错。
 
  -->
  <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>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值