3、SpringMVC与MaBatis整合

来源:互联网 发布:2016年美国网络星期一 编辑:程序博客网 时间:2024/06/04 00:26

在入门程序中jsp中的数据都是在java代码中写好的,我们需要实现从数据库中获取数据并显示。所有需要将SpringMVC和MyBatis整合。

数据库表的创建

SET FOREIGN_KEY_CHECKS=0;-- ------------------------------ Table structure for items-- ----------------------------DROP TABLE IF EXISTS `items`;CREATE TABLE `items` (  `id` INT(11) NOT NULL AUTO_INCREMENT,  `name` VARCHAR(32) NOT NULL 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;-- ------------------------------ Records of items-- ----------------------------INSERT INTO `items` VALUES ('1', '台式机', '3000.0', '该电脑质量非常好!!!!', NULL, '2016-02-03 13:22:53');INSERT INTO `items` VALUES ('2', '笔记本', '6000.0', '笔记本性能好,质量好!!!!!', NULL, '2015-02-09 13:22:57');INSERT INTO `items` VALUES ('3', '背包', '200.0', '名牌背包,容量大质量好!!!!', NULL, '2015-02-06 13:23:02');-- ------------------------------ Table structure for user-- ----------------------------DROP TABLE IF EXISTS `user`;CREATE TABLE `user` (  `id` INT(11) NOT NULL AUTO_INCREMENT,  `username` VARCHAR(32) NOT NULL COMMENT '用户名称',  `birthday` DATE DEFAULT NULL COMMENT '生日',  `sex` CHAR(1) DEFAULT NULL COMMENT '性别',  `address` VARCHAR(256) DEFAULT NULL COMMENT '地址',  PRIMARY KEY (`id`)) ENGINE=INNODB AUTO_INCREMENT=27 DEFAULT CHARSET=utf8;-- ------------------------------ Records of user-- ----------------------------INSERT INTO `user` VALUES ('1', '王五', NULL, '2', NULL);INSERT INTO `user` VALUES ('10', '张三', '2014-07-10', '1', '北京市');INSERT INTO `user` VALUES ('16', '张小明', NULL, '1', '河南郑州');INSERT INTO `user` VALUES ('22', '陈小明', NULL, '1', '河南郑州');INSERT INTO `user` VALUES ('24', '张三丰', NULL, '1', '河南郑州');INSERT INTO `user` VALUES ('25', '陈小明', NULL, '1', '河南郑州');INSERT INTO `user` VALUES ('26', '王五', NULL, NULL, NULL);

导入需要的jar包

http://download.csdn.net/download/qq_25343557/10165141

这里写图片描述

加入配置文件

最终效果:
这里写图片描述
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></configuration>

applicationContext-dao.xml:

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"    xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"    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-4.0.xsd    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">    <!-- 加载配置文件 -->    <context:property-placeholder location="classpath:mybatis/jdbc.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="10"/>        <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">        <!-- 配置Mapper扫描包 -->        <property name="basePackage" value="cn.xpu.hcp.ssm.mapper"/>    </bean></beans>

applicationContext-service.xml:

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"    xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"    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-4.0.xsd    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">    <!-- 配置事务-->    <!-- 事务管理器 -->    <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="save*" propagation="REQUIRED"/>            <tx:method name="insert*" propagation="REQUIRED"/>            <tx:method name="delete*" 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="query*" propagation="SUPPORTS" read-only="true"/>        </tx:attributes>    </tx:advice>    <!-- 切面 -->    <aop:config>        <aop:advisor advice-ref="txAdvice"            pointcut="execution(* cn.xpu.hcp.ssm.service.*.*(..))" />    </aop:config></beans>

applicationContext-trans.xml:

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"    xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"    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-4.0.xsd    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">    <!-- 配置service扫描 -->    <context:component-scan base-package="cn.xpu.hcp.ssm.service"/></beans>

jdbc.propertiesa:

jdbc.driver=com.mysql.jdbc.Driverjdbc.url=jdbc\:mysql\:///springmvcandmybatisjdbc.username=rootjdbc.password=

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:p="http://www.springframework.org/schema/p"    xmlns:context="http://www.springframework.org/schema/context"    xmlns:mvc="http://www.springframework.org/schema/mvc"    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">    <!-- 配置controller扫描包 -->    <context:component-scan base-package="cn.xpu.hcp.ssm.controller"/>    <!-- 注解驱动 -->    <mvc:annotation-driven />    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">        <property name="prefix" value="/WEB-INF/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">  <!-- 配置spring -->  <context-param>    <param-name>contextConfigLocation</param-name>    <param-value>classpath:spring/application*.xml</param-value>  </context-param>  <!-- 使用监听器加载Spring配置文件 -->  <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>    <!-- 指定SpringMVC的配置文件,SpringMVC配置文件的默认路径是/WEB-INF/${servlet-name}-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结尾的请求进入SpringMVC -->    <url-pattern>*.action</url-pattern>  </servlet-mapping></web-app>

加入jsp页面

editItem.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>     <!-- 上传图片是需要指定属性 enctype="multipart/form-data" -->    <!-- <form id="itemForm" action="" method="post" enctype="multipart/form-data"> -->    <form id="itemForm" action="${pageContext.request.contextPath }/updateitem.action" method="post">        <input type="hidden" name="id" value="${item.id }" /> 修改商品信息:        <table width="100%" border=1>            <tr>                <td>商品名称</td>                <td><input type="text" name="name" value="${item.name }" /></td>            </tr>            <tr>                <td>商品价格</td>                <td><input type="text" name="price" value="${item.price }" /></td>            </tr>            <%--             <tr>                <td>商品生产日期</td>                <td><input type="text" name="createtime"                    value="<fmt:formatDate value="${item.createtime}" pattern="yyyy-MM-dd HH:mm:ss"/>" /></td>            </tr>            <tr>                <td>商品图片</td>                <td>                    <c:if test="${item.pic !=null}">                        <img src="/pic/${item.pic}" width=100 height=100/>                        <br/>                    </c:if>                    <input type="file"  name="pictureFile"/>                 </td>            </tr>             --%>            <tr>                <td>商品简介</td>                <td><textarea rows="3" cols="30" name="detail">${item.detail }</textarea>                </td>            </tr>            <tr>                <td colspan="2" align="center"><input type="submit" value="提交" />                </td>            </tr>        </table>    </form></body></html>

itemList.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> <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="${itemList }" 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 }/itemEdit.action?id=${item.id}">修改</a></td></tr></c:forEach></table></form></body></html>

DAO开发

使用MyBatis逆向工程实现POJO和mapper的开发。
这里写图片描述

itemService接口及其实现类:

public interface itemService {    List<Items> getAll();}@Servicepublic class ItemServiceImpl implements ItemService {    @Autowired    private ItemsMapper itemMapper;    public List<Items> getAll() {        List<Items> list = itemMapper.selectByExampleWithBLOBs(null);        return list;    }}

ItemController的开发:

@Controllerpublic class ItemController {    @Autowired    private ItemService itemService;    @RequestMapping("/itemList")    public ModelAndView getAll(){        List<Items> list = itemService.getAll();        ModelAndView modelAndView = new ModelAndView();        // 把商品数据放到模型中        modelAndView.addObject("itemList", list);        // 设置逻辑视图        modelAndView.setViewName("itemList");        return modelAndView;    }}

测试:
这里写图片描述

原创粉丝点击