SpringMVC3.2+Spring3.2+Mybatis3.1(SSM~Demo)

SpringMVC+Spring+Mybatis 框架搭建

整个Demo的视图结构:

JAR:

下载地址:http://download.csdn.net/detail/li1669852599/8546059

首先,我是使用MyEclipse工具做的这个例子,整合了Sping 3 、Spring MVC 3 、MyBatis框架,演示数据库采用MySQL数据库。例子中主要操作包括对数据的添加(C)、查找(R)、更新(U)、删除(D)。我在这里采用的数据库连接池是来自阿里巴巴的Druid,至于Druid的强大之处,我在这里就不做过多的解释了,有兴趣的朋友们可以去网上谷歌或者百度一下哦!好了下面我就贴上这次这个演示例子的关键代码:

example目录下是一个基本案例:

BaseController.java

  1 package com.talent.example.controller;
  2 import java.util.List;
  3 import java.util.UUID;
  4 import javax.servlet.http.HttpServletRequest;
  5 import org.springframework.beans.factory.annotation.Autowired;
  6 import org.springframework.stereotype.Controller;
  7 import org.springframework.web.bind.annotation.RequestMapping;
  8 
  9 import com.talent.example.model.Base;
 10 import com.talent.example.service.BaseService;
 11 /**
 12  * <p>Title:控制器Controller</p>
 13  * <p>Description: </p>
 14  * <p>Copyright: Copyright (c) VISEC 2015</p>
 15  * <P>CreatTime: Mar 25 2015 </p>
 16  * @author  Dana丶Li
 17  * @version 1.0
 18  */
 19 @Controller
 20 public class BaseController {
 21 private BaseService baseService;
 22 private static String pathHead="ViewCenter/TalentBaseExample/";
 23     
 24     public BaseService getBaseService(){
 25         return baseService;
 26     }
 27     @Autowired
 28     public void setBaseService(BaseService baseService){
 29         this.baseService = baseService;
 30     }
 31     
 32     @SuppressWarnings("finally")
 33     @RequestMapping("addInfo")
 34     public String add(Base add,HttpServletRequest request){
 35         try{            
 36             add.setId(UUID.randomUUID().toString());
 37             //System.out.println(add.getId() + ":::::" + add.getTname() + ":::::" + add.getTpwd());
 38             String str = baseService.addInfo(add);
 39             //System.out.println(str);
 40             request.setAttribute("InfoMessage", str);
 41         } catch (Exception e){
 42             e.printStackTrace();
 43             //request.setAttribute("InfoMessage", "添加信息失败!具体异常信息:" + e.getMessage());
 44         }finally{            
 45             return BaseController.pathHead+"result";
 46         }
 47     }
 48     
 49     @RequestMapping("getAll")
 50     public String getBaseInfoAll(HttpServletRequest request){
 51         try{            
 52             List<Base> list = baseService.getAll();
 53             //System.out.println(list);
 54             request.setAttribute("addLists", list);
 55             return BaseController.pathHead+"listAll";
 56         } catch (Exception e){
 57             e.printStackTrace();
 58             //request.setAttribute("InfoMessage", "信息载入失败!具体异常信息:" + e.getMessage());
 59             return BaseController.pathHead+"result";
 60         }
 61     }
 62     
 63     @SuppressWarnings("finally")
 64     @RequestMapping("del")
 65     public String del(String tid,HttpServletRequest request){
 66         try {            
 67             String str = baseService.delete(tid);
 68             request.setAttribute("InfoMessage", str);
 69         } catch (Exception e) {
 70             e.printStackTrace();
 71             //request.setAttribute("InfoMessage", "删除信息失败!具体异常信息:" + e.getMessage());
 72         } finally{            
 73             return BaseController.pathHead+"result";
 74         }
 75     }
 76     @RequestMapping("modify")
 77     public String modify(String tid,HttpServletRequest request){
 78         try {            
 79             Base add = baseService.findById(tid);
 80             request.setAttribute("add", add);
 81             return BaseController.pathHead+"modify";
 82         } catch (Exception e){
 83             e.printStackTrace();
 84             //request.setAttribute("InfoMessage", "信息载入失败!具体异常信息:" + e.getMessage());
 85             return BaseController.pathHead+"result";
 86         }
 87     }
 88     
 89     @SuppressWarnings("finally")
 90     @RequestMapping("update")
 91     public String update(Base add,HttpServletRequest request){
 92         try {            
 93             String str = baseService.update(add);
 94             request.setAttribute("InfoMessage", str);
 95         } catch (Exception e) {
 96             e.printStackTrace();
 97             //request.setAttribute("InfoMessage", "更新信息失败!具体异常信息:" + e.getMessage());
 98         } finally {            
 99             return BaseController.pathHead+"result";
100         }
101     }
102     
103 }
View Code

BaseMapper.java

 1 package com.talent.example.dao;
 2 import java.util.List;
 3 import com.talent.example.model.Base;
 4 /**
 5  * <p>Title: DAO BaseMapper</p>
 6  * <p>Description: Base接口</p>
 7  * <p>Copyright: Copyright (c) VISEC 2015</p>
 8  * <P>CreatTime: Mar 25 2015 </p>
 9  * @author  Dana丶Li
10  * @version 1.0
11  */
12 public interface BaseMapper {
13     int deleteByPrimaryKey(String id);
14 
15     int insert(Base record);
16 
17     int insertSelective(Base record);
18 
19     Base selectByPrimaryKey(String id);
20 
21     int updateByPrimaryKeySelective(Base record);
22 
23     int updateByPrimaryKey(Base record);
24     
25     List<Base> getAll();
26 }
View Code

BaseMapper.xml

 1 <?xml version="1.0" encoding="UTF-8" ?>
 2 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
 3 <mapper namespace="com.talent.example.dao.BaseMapper">
 4     <resultMap id="BaseResultMap" type="com.talent.example.model.Base">
 5         <id column="id" property="id" jdbcType="VARCHAR" />
 6         <result column="tname" property="tname" jdbcType="VARCHAR" />
 7         <result column="tpwd" property="tpwd" jdbcType="VARCHAR" />
 8     </resultMap>
 9     <sql id="Base_Column_List">
10         id, tname, tpwd
11     </sql>
12     <select id="selectByPrimaryKey" resultMap="BaseResultMap"
13         parameterType="java.lang.String">
14         select
15         <include refid="Base_Column_List" />
16         from tadd
17         where id = #{id,jdbcType=VARCHAR}
18     </select>
19     <delete id="deleteByPrimaryKey" parameterType="java.lang.String">
20         delete from tadd
21         where id = #{id,jdbcType=VARCHAR}
22     </delete>
23     <insert id="insert" parameterType="com.talent.example.model.Base">
24         insert into tadd (id, tname,
25         tpwd
26         )
27         values (#{id,jdbcType=VARCHAR}, #{tname,jdbcType=VARCHAR},
28         #{tpwd,jdbcType=VARCHAR}
29         )
30     </insert>
31     <insert id="insertSelective" parameterType="com.talent.example.model.Base">
32         insert into tadd
33         <trim prefix="(" suffix=")" suffixOverrides=",">
34             <if test="id != null">
35                 id,
36             </if>
37             <if test="tname != null">
38                 tname,
39             </if>
40             <if test="tpwd != null">
41                 tpwd,
42             </if>
43         </trim>
44         <trim prefix="values (" suffix=")" suffixOverrides=",">
45             <if test="id != null">
46                 #{id,jdbcType=VARCHAR},
47             </if>
48             <if test="tname != null">
49                 #{tname,jdbcType=VARCHAR},
50             </if>
51             <if test="tpwd != null">
52                 #{tpwd,jdbcType=VARCHAR},
53             </if>
54         </trim>
55     </insert>
56     <update id="updateByPrimaryKeySelective" parameterType="com.talent.example.model.Base">
57         update tadd
58         <set>
59             <if test="tname != null">
60                 tname = #{tname,jdbcType=VARCHAR},
61             </if>
62             <if test="tpwd != null">
63                 tpwd = #{tpwd,jdbcType=VARCHAR},
64             </if>
65         </set>
66         where id = #{id,jdbcType=VARCHAR}
67     </update>
68     <update id="updateByPrimaryKey" parameterType="com.talent.example.model.Base">
69         update tadd
70         set
71         tname = #{tname,jdbcType=VARCHAR},
72         tpwd = #{tpwd,jdbcType=VARCHAR}
73         where id = #{id,jdbcType=VARCHAR}
74     </update>
75 
76     <select id="getAll" resultMap="BaseResultMap">
77         SELECT * FROM tadd
78     </select>
79 </mapper>
View Code

Base.java

 1 package com.talent.example.model;
 2 /**
 3  * <p>Title: MODEL Base</p>
 4  * <p>Description: Base实体类</p>
 5  * <p>Copyright: Copyright (c) VISEC 2015</p>
 6  * <P>CreatTime: Mar 25 2015 </p>
 7  * @author Dana丶Li
 8  * @version 1.0
 9  */
10 public class Base{
11     
12     private String id;
13     
14     private String tname;
15     
16     private String tpwd;
17 
18     public String getId(){
19         return id;
20     }
21     public void setId(String id) {
22         this.id = id == null ? null : id.trim();
23     }
24     public String getTname() {
25         return tname;
26     }
27     public void setTname(String tname) {
28         this.tname = tname == null ? null : tname.trim();
29     }
30 
31     public String getTpwd() {
32         return tpwd;
33     }
34 
35     public void setTpwd(String tpwd) {
36         this.tpwd = tpwd == null ? null : tpwd.trim();
37     }
38 }
View Code

BaseServiceImpl.java

 1 package com.talent.example.service.impl;
 2 import java.util.List;
 3 import org.springframework.beans.factory.annotation.Autowired;
 4 import org.springframework.stereotype.Service;
 5 import com.talent.example.dao.BaseMapper;
 6 import com.talent.example.model.Base;
 7 import com.talent.example.service.BaseService;
 8 /**
 9  * <p>Title: DAO BaseMapper</p>
10  * <p>Description: Base接口</p>
11  * <p>Copyright: Copyright (c) VISEC 2015</p>
12  * <P>CreatTime: Mar 25 2015 </p>
13  * @author  Dana丶Li
14  * @version 1.0
15  */
16 @Service("baseService")
17 public class BaseServiceImpl implements BaseService{
18 
19     private BaseMapper baseMapper;
20 
21     public BaseMapper getBaseMapper(){
22         return baseMapper;
23     }
24     @Autowired
25     public void setBaseMapper(BaseMapper BaseMapper) {
26         this.baseMapper = BaseMapper;
27     }
28 
29     @Override
30     public String addInfo(Base BaseInfo) {
31         if (baseMapper.insertSelective(BaseInfo) == 1) {
32             return "添加成功";
33         }
34         return "添加失败";
35     }
36     @Override
37     public List<Base> getAll() {
38         return baseMapper.getAll();
39     }
40     @Override
41     public String delete(String id) {
42         if (baseMapper.deleteByPrimaryKey(id) == 1) {
43             return "删除成功";
44         }
45         return "删除失败";
46     }
47     @Override
48     public Base findById(String id) {
49         return baseMapper.selectByPrimaryKey(id);
50     }
51     @Override
52     public String update(Base BaseInfo) {
53         if (baseMapper.updateByPrimaryKeySelective(BaseInfo) == 1) {
54             return "更新成功";
55         }
56         return "更新失败";
57     }
58 
59 
60 }
View Code

BaseService.java

 1 package com.talent.example.service;
 2 import java.util.List;
 3 import com.talent.example.model.Base;
 4 /**
 5  * <p>Title: DAO BaseService</p>
 6  * <p>Description: BaseService接口</p>
 7  * <p>Copyright: Copyright (c) VISEC 2015</p>
 8  * <P>CreatTime: Mar 25 2015 </p>
 9  * @author  Dana丶Li
10  * @version 1.0
11  */
12 public interface BaseService {
13     
14     String addInfo(Base addInfo);
15 
16     List<Base> getAll();
17 
18     String delete(String id);
19 
20     Base findById(String id);
21 
22     String update(Base addInfo);
23 }
View Code

接下来主要详述SpringMVC+Spring+Mybatis的配置文件

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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    version="3.0">
    <display-name></display-name>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring.xml;classpath:spring-mybatis.xml</param-value>
    </context-param>
    <filter>
        <description>字符集过滤器</description>
        <filter-name>encodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <description>字符集编码</description>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <listener>
        <description>spring监听器</description>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <listener>
        <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
    </listener>
    <servlet>
        <description>spring mvc servlet</description>
        <servlet-name>springMvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <description>spring mvc 配置文件</description>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring-mvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springMvc</servlet-name>
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>15</session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>ViewCenter/TalentBaseExample/index.jsp</welcome-file>
    </welcome-file-list>
</web-app>

通过Web.xml加载SpringMVC+Spring+Mybatis的配置文件

首先是Spring.xml ,spring-mybatis.xml俩文件

Spring.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-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
">
    <!-- 引入属性文件 -->
    <context:property-placeholder location="classpath:com/talent/base/config.properties" />
    <!-- 自动扫描(自动注入) -->
    <context:component-scan base-package="com.talent.example.service..*" />
</beans>

spring-mybatis.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: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-3.0.xsd 
http://www.springframework.org/schema/tx 
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/aop 
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
    <!-- 配置数据源 -->
    <bean name="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
        <property name="url" value="${jdbc_url}" />
        <property name="username" value="${jdbc_username}" />
        <property name="password" value="${jdbc_password}" />

        <!-- 初始化连接大小 -->
        <property name="initialSize" value="0" />
        <!-- 连接池最大使用连接数量 -->
        <property name="maxActive" value="20" />
        <!-- 连接池最大空闲 -->
        <property name="maxIdle" value="20" />
        <!-- 连接池最小空闲 -->
        <property name="minIdle" value="0" />
        <!-- 获取连接最大等待时间 -->
        <property name="maxWait" value="60000" />

        <!-- <property name="poolPreparedStatements" value="true" /> <property name="maxPoolPreparedStatementPerConnectionSize" value="33" /> -->

        <property name="validationQuery" value="${validationQuery}" />
        <property name="testOnBorrow" value="false" />
        <property name="testOnReturn" value="false" />
        <property name="testWhileIdle" value="true" />

        <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
        <property name="timeBetweenEvictionRunsMillis" value="60000" />
        <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
        <property name="minEvictableIdleTimeMillis" value="25200000" />

        <!-- 打开removeAbandoned功能 -->
        <property name="removeAbandoned" value="true" />
        <!-- 1800秒,也就是30分钟 -->
        <property name="removeAbandonedTimeout" value="1800" />
        <!-- 关闭abanded连接时输出错误日志 -->
        <property name="logAbandoned" value="true" />

        <!-- 监控数据库 -->
        <!-- <property name="filters" value="stat" /> -->
        <property name="filters" value="mergeStat" />
    </bean>



    <!-- MyBatis文件 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <!-- 自动扫描entity目录, 省掉Configuration.xml里的手工配置 -->
        <property name="mapperLocations" value="classpath:com/talent/example/mapping/*.xml" />
    </bean>

    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.talent.example.dao" />
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
    </bean>

    <!-- 配置事务管理器 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>

    <!-- 注解方式配置事物 -->
    <!-- <tx:annotation-driven transaction-manager="transactionManager" /> -->
 
    <!-- 拦截器方式配置事物 -->
    <tx:advice id="transactionAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="add*" propagation="REQUIRED" />
            <tx:method name="append*" propagation="REQUIRED" />
            <tx:method name="insert*" propagation="REQUIRED" />
            <tx:method name="save*" propagation="REQUIRED" />
            <tx:method name="update*" propagation="REQUIRED" />
            <tx:method name="modify*" propagation="REQUIRED" />
            <tx:method name="edit*" propagation="REQUIRED" />
            <tx:method name="delete*" propagation="REQUIRED" />
            <tx:method name="remove*" propagation="REQUIRED" />
            <tx:method name="repair" propagation="REQUIRED" />
            <tx:method name="delAndRepair" propagation="REQUIRED" />

            <tx:method name="get*" propagation="SUPPORTS" />
            <tx:method name="find*" propagation="SUPPORTS" />
            <tx:method name="load*" propagation="SUPPORTS" />
            <tx:method name="search*" propagation="SUPPORTS" />
            <tx:method name="datagrid*" propagation="SUPPORTS" />

            <tx:method name="*" propagation="SUPPORTS" />
        </tx:attributes>
    </tx:advice>
    
    <aop:config>
        <aop:pointcut id="transactionPointcut" expression="execution(* com.talent.example.service..*Impl.*(..))" />
        <aop:advisor pointcut-ref="transactionPointcut" advice-ref="transactionAdvice" />
    </aop:config>


    <!-- 配置Druid监控Spring JDBC -->
    <bean id="druid-stat-interceptor" class="com.alibaba.druid.support.spring.stat.DruidStatInterceptor">
    </bean>
    <bean id="druid-stat-pointcut" class="org.springframework.aop.support.JdkRegexpMethodPointcut" scope="prototype">
        <property name="patterns">
            <list>
                <value>com.talent.example.service.*</value>
            </list>
        </property>
    </bean>
    
    <aop:config>
        <aop:advisor advice-ref="druid-stat-interceptor" pointcut-ref="druid-stat-pointcut" />
    </aop:config>
</beans>

其次呢是Spring-mvc.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:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans 
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
http://www.springframework.org/schema/context 
http://www.springframework.org/schema/context/spring-context-3.0.xsd 
http://www.springframework.org/schema/mvc 
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

    <!-- 自动扫描controller包下的所有类,使其认为spring mvc的控制器 -->
    <context:component-scan base-package="com.talent.example.controller" />

    <!-- 对模型视图名称的解析,即在模型视图名称添加前后缀 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/" p:suffix=".jsp" />
    
</beans>

以上就是几个关键位置的代码,我全部贴出来了。至于配置文件什么的,由于时间原因没有贴出。如果大家要是感兴趣的话,可以下载我的这个演示项目包,里面的东西都齐全着,导入到MyEclipse上面直接部署到服务器上面就可以运行。数据库就是里面的那个.sql文件。建个库然后将数据导入就是。哦,对了。导完数据后,记得别忘了到config.properties里面去把数据库的连接信息换成你自己哦!

项目Demo下载地址~

 

posted @ 2015-03-30 10:18  小码哥、iByte  阅读(2182)  评论(0编辑  收藏  举报