码迷,mamicode.com
首页 > 编程语言 > 详细

SpringMVC+Spring+Mybatis整合

时间:2015-07-02 10:17:53      阅读:227      评论:0      收藏:0      [点我收藏+]

标签:

创建web工程

用eclipse或idea创建一个web工程,在这里演示使用idea,项目命名为ssm

建立工程目录框架

根据习惯,简历包目录,分别为

  1. config
    在其中创建两个子包mybatis和spring,分别用来放置spring、mybatis配置文件
  2. mapper
    用来放置mybatis的mapper接口和mapper.xml
  3. service
    service层的javabean
  4. controller
    controller的javabean
  5. pojo
    简单的POJO类

技术分享

在WEB-INF下建立两个目录

  1. lib
    jar包目录
  2. views
    jsp视图目录

技术分享

导入jar包

一共需要如下jar包

  1. spring所有包
  2. mybatis
  3. spring-mybatis整合包
  4. aspectj
  5. jstl
  6. log4j
  7. c3p0
  8. mysql

技术分享

百度云下载 链接:http://pan.baidu.com/s/1dDB8cxV 密码:3cqp

添加mybatis配置文件

在config.mybatis下创建mybatis.xml配置文件,SSM整合和mybatis在不需要二级缓存等配置时,mybatis配置文件只需要一个框架,不需要书写具体内容,框架如下

<?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>

添加spring和springmvc配置文件

  • springmvc

在config.spring下创建springmvc.xml文件,用来配置springmvc

<?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:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       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 加入IOC容器-->
       <context:component-scan base-package="com.elin4it.ssm.controller"/>

       <!--配置映射器和适配器-->
       <mvc:annotation-driven></mvc:annotation-driven>

       <!--配置视图渲染类-->
       <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
              <!--配置物理解析路径-->
              <property name="prefix" value="/WEB-INF/views/"/>
              <property name="suffix" value=".jsp"/>
       </bean>


</beans>
  • applicationContext-dao.xml

在config.spring下创建applicationContext-dao.xml文件,用来配置DAO层的内容,在这里连接数据库的数据源使用C3P0,所以在这之前先在config中添加db.properties来指定数据库连接信息

jdbc.driver = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://127.0.0.1:3306/mybatis?characterEncoding=UTF-8
jdbc.username = root
jdbc.password = root

applicationContext-dao.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"
       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">

       <!--添加数据库配置文件-->
       <context:property-placeholder location="classpath:com/elin4it/ssm/config/db.properties"/>

       <!--设置数据源c3p0-->
       <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
              <property name="driverClass" value="${jdbc.driver}"/>
              <property name="jdbcUrl" value="${jdbc.url}"/>
              <property name="user" value="${jdbc.username}"/>
              <property name="password" value="${jdbc.password}"/>
              <property name="maxPoolSize" value="50"/>
              <property name="minPoolSize" value="5"/>
              <property name="maxIdleTime" value="60"/>
       </bean>

       <!--配置sqlsessionFactory-->
       <bean id="sqlSession" class="org.mybatis.spring.SqlSessionFactoryBean">
              <!--配置mybatis配置文件-->
              <property name="configLocation" value="classpath:com/elin4it/ssm/config/mybaits/SqlMapConfig.xml"/>
              <!--配置数据源-->
              <property name="dataSource" ref="dataSource"/>
       </bean>

       <!--配置自动扫描mapper,将mapper接口加入到IOC容器-->
       <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
              <property name="basePackage" value="com/elin4it/ssm/mapper"/>
              <property name="sqlSessionFactoryBeanName" value="sqlSession"/>
       </bean>
</beans>
  • applicationContext-service.xml

在config.spring中添加applicationContext-service.xml,用来把service层的javabean注入到IOC容器中

<?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"
       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">


       <!--将service加入到IOC容器-->
       <context:component-scan base-package="com.elin4it.ssm.service"/>
</beans>
  • applicationContext-transtion.xml

在config.spring中添加applicationContext-transtion.xml,用来配置AOP事务

<?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:tx="http://www.springframework.org/schema/tx"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.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="find*" propagation="REQUIRED"/>
                     <tx:method name="add*" propagation="REQUIRED"/>
                     <tx:method name="delete*" propagation="REQUIRED"/>
                     <tx:method name="update*" propagation="REQUIRED"/>
              </tx:attributes>
       </tx:advice>

       <aop:config>
              <aop:advisor advice-ref="txAdvice" pointcut="execution(* com.elin4it.ssm.service.*.*(..))"/>
       </aop:config>
</beans>

添加log4j配置文件

为了方便mybatis的调试,使用log4j作为日志输出,在src根目录中添加log4j.properties

log4j.rootLogger=DEBUG,Console
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n
log4j.logger.org.apache=INFO

修改web.xml文件

web.xml需要实现三个功能

  • 配置spring文件
<!--设置spring 配置文件的位置-->
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:cn/elinzhou/OrderSpringMVC/config/spring/applicationContext-*.xml</param-value>
</context-param>
<!--配置spring listener-->
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
  • 配置springmvc中的前端控制器
<!--配置springmvc-->
<servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <!--springmvc配置文件位置-->
        <param-value>classpath:cn/elinzhou/OrderSpringMVC/config/spring/springmvc.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>
  • 解决post乱码问题
<!--解决POST乱码问题-->
<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>

创建pojo类

这里使用一张用户表做示例,表结构如下

DROP TABLE IF EXISTS `user`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `user` (
  `id` int(11) NOT NULL auto_increment,
  `username` varchar(32) NOT NULL COMMENT ‘用户名称‘,
  `sex` char(1) default NULL COMMENT ‘性别‘,
  PRIMARY KEY  (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=31 DEFAULT CHARSET=utf8;

根据表结构建立POJO类

package cn.elinzhou.OrderSpringMVC.pojo;

import java.util.Date;

public class User {
    private Integer id;

    private String username;

    private String sex;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username == null ? null : username.trim();
    }
    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex == null ? null : sex.trim();
    }
}

创建mapper接口和mapper.xml

mapper.java

package com.elin4it.ssm.mapper;

import com.elin4it.ssm.pojo.User;
import java.util.List;

public interface UserMapper {
    //查询用户列表
    List<User> findUser() throws Exception;
}

mapper.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.elin4it.ssm.mapper.UserMapper" >
  <select id="findUser" resultMap="com.elin4it.ssm.pojo.User">
    select
    id, username, birthday, sex, address
    from user
  </select>

</mapper>

创建service接口和实现

创建一个service接口,添加一个方法,用来查询所用用户
UserService.java

package com.elin4it.ssm.service;

import com.elin4it.ssm.pojo.User;

import java.util.List;

/**
 * Created by elin on 15-7-1.
 */
public interface UserService {
    List<User> findUser()throws Exception;
}

添加UserService的实现类UserServiceImpl.java

package com.elin4it.ssm.service;

import com.elin4it.ssm.mapper.UserMapper;
import com.elin4it.ssm.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Description: UserServiceImpl
 * Author: Elin Zhou
 * Create: 2015-07-01 20:59
 */
@Service
public class UserServiceImpl implements UserService {

    //自动注入mapper接口
    @Autowired
    private UserMapper userMapper;


    @Override
    public List<User> findUser() throws Exception {
        //调用mapper接口中的方法,获取用户列表
        List<User> users = userMapper.findUser();
        return users;
    }
}

创建controller

创建后端控制器,前端控制器根据用户请求映射到后端控制器中的方法,并且返回视图和数据来渲染视图

package com.elin4it.ssm.controller;

import com.elin4it.ssm.pojo.User;
import com.elin4it.ssm.service.UserService;
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 java.util.List;
import java.util.Map;

/**
 * Description: UserController
 * Author: Elin Zhou
 * Create: 2015-07-01 19:30
 */
@Controller
@RequestMapping("/user")
public class UserController {
    //自动注入service   
    @Autowired
    private UserService userService;

    @RequestMapping("/findUser")
    public String findUser(Map<String,Object> map) throws Exception{
    //调用service中的查询用户列表方法来获取用户列表
        List<User> users = userService.findUser();
        //把用户列表放到形参传入的map中,相当于执行request.addAttribute()方法
        map.put("users",users);

        return "user/userList";
    }
}

创建对应的jsp页面

在WEB-INF的views文件夹中添加user文件加,用来存放用户相关的视图,在添加一个userList.jsp文件

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--
  Created by IntelliJ IDEA.
  User: elin
  Date: 15-7-1
  Time: 下午8:53
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title></title>
</head>
<body>
  <h1>userList</h1>
  <table>
    <tr><td>id</td><td>username</td><td>sex</td></tr>
    <c:forEach items="${users}" var="i">
      <tr>
        <td>${i.id}</td>
        <td>${i.username}</td>
        <td>${i.sex}</td>
      </tr>
    </c:forEach>
  </table>
</body>
</html>

版权声明:本文为博主原创文章,未经博主允许不得转载。

SpringMVC+Spring+Mybatis整合

标签:

原文地址:http://blog.csdn.net/u011403655/article/details/46715589

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!