Maven搭建SpringMVC+Mybatis项目详解

Java 发表评论

 前言

         最近比较闲,复习搭建一下项目,这次主要使用Spring+SpringMVC+Mybatis。项目持久层使用Mybatis3,控制层使用SpringMVC4.1,使用Spring4.1管理控制器,数据库连接池使用druid数据源,该项数据库暂使用MySQL。(如果是oracle需修改pom.xml)

    <!– oracle连接 –>
    <dependency>
      <groupId>com.hynnet</groupId>
      <artifactId>oracle-driver-ojdbc6</artifactId>
      <version>12.1.0.1</version>
    </dependency>

1、 数据库表结构以及maven项目结构

         数据表非常的简单(不是重点),如下:

         

       创建maven项目,详细见上一篇maven创建(http://blog.csdn.net/fengshizty/article/details/43019561),创建Maven
Project时,将Filter选择为org.apache.maven.archetypes。填写完相关项目坐标信息后项目结构如下:

        

     注:若无src/main/java,src/test/java,src/test/resources时,创建这个几个Source Folder。


 2、修改pom.xml添加对应的包依赖

     这儿将全部使用的Maven依赖贴出了,对应什么作用上面都有解释,如下:

     pom.xml

[html] view
plain
 copy

 在CODE上查看代码片派生到我的代码片

  1. <project xmlns=“http://maven.apache.org/POM/4.0.0” xmlns:xsi=“http://www.w3.org/2001/XMLSchema-instance”  
  2.     xsi:schemaLocation=“http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd”>  
  3.     <modelVersion>4.0.0</modelVersion>  
  4.     <groupId>org.andy.sm</groupId>  
  5.     <artifactId>springmvc_mybatis_demo</artifactId>  
  6.     <packaging>war</packaging>  
  7.     <version>0.0.1-SNAPSHOT</version>  
  8.   
  9.     <name>springmvc_mybatis_demo Maven Webapp</name>  
  10.     <url>http://maven.apache.org</url>  
  11.   
  12.     <properties>  
  13.         <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>  
  14.         <spring.version>4.1.4.RELEASE</spring.version>  
  15.         <jackson.version>2.5.0</jackson.version>  
  16.     </properties>  
  17.   
  18.     <dependencies>  
  19.   
  20.         <dependency>  
  21.             <groupId>junit</groupId>  
  22.             <artifactId>junit</artifactId>  
  23.             <version>4.12</version>  
  24.             <scope>test</scope>  
  25.         </dependency>  
  26.   
  27.         <!– spring –>  
  28.         <dependency>  
  29.             <groupId>org.springframework</groupId>  
  30.             <artifactId>spring-core</artifactId>  
  31.             <version>${spring.version}</version>  
  32.         </dependency>  
  33.   
  34.         <dependency>  
  35.             <groupId>org.springframework</groupId>  
  36.             <artifactId>spring-beans</artifactId>  
  37.             <version>${spring.version}</version>  
  38.         </dependency>  
  39.   
  40.         <dependency>  
  41.             <groupId>org.springframework</groupId>  
  42.             <artifactId>spring-context</artifactId>  
  43.             <version>${spring.version}</version>  
  44.         </dependency>  
  45.   
  46.         <dependency>  
  47.             <groupId>org.springframework</groupId>  
  48.             <artifactId>spring-tx</artifactId>  
  49.             <version>${spring.version}</version>  
  50.         </dependency>  
  51.   
  52.         <dependency>  
  53.             <groupId>org.springframework</groupId>  
  54.             <artifactId>spring-web</artifactId>  
  55.             <version>${spring.version}</version>  
  56.         </dependency>  
  57.   
  58.         <dependency>  
  59.             <groupId>org.springframework</groupId>  
  60.             <artifactId>spring-webmvc</artifactId>  
  61.             <version>${spring.version}</version>  
  62.         </dependency>  
  63.   
  64.         <dependency>  
  65.             <groupId>org.springframework</groupId>  
  66.             <artifactId>spring-jdbc</artifactId>  
  67.             <version>${spring.version}</version>  
  68.         </dependency>  
  69.   
  70.         <dependency>  
  71.             <groupId>org.springframework</groupId>  
  72.             <artifactId>spring-test</artifactId>  
  73.             <version>${spring.version}</version>  
  74.             <scope>test</scope>  
  75.         </dependency>  
  76.   
  77.         <!– mybatis 包 –>  
  78.         <dependency>  
  79.             <groupId>org.mybatis</groupId>  
  80.             <artifactId>mybatis</artifactId>  
  81.             <version>3.2.8</version>  
  82.         </dependency>  
  83.   
  84.         <!–mybatis spring 插件 –>  
  85.         <dependency>  
  86.             <groupId>org.mybatis</groupId>  
  87.             <artifactId>mybatis-spring</artifactId>  
  88.             <version>1.2.2</version>  
  89.         </dependency>  
  90.   
  91.         <!– mysql连接 –>  
  92.         <dependency>  
  93.             <groupId>mysql</groupId>  
  94.             <artifactId>mysql-connector-java</artifactId>  
  95.             <version>5.1.34</version>  
  96.         </dependency>  
  97.   
  98.         <!– 数据源 –>  
  99.         <dependency>  
  100.             <groupId>com.alibaba</groupId>  
  101.             <artifactId>druid</artifactId>  
  102.             <version>1.0.12</version>  
  103.         </dependency>  
  104.   
  105.         <dependency>  
  106.             <groupId>org.aspectj</groupId>  
  107.             <artifactId>aspectjweaver</artifactId>  
  108.             <version>1.8.4</version>  
  109.         </dependency>  
  110.   
  111.         <!– log4j –>  
  112.         <dependency>  
  113.             <groupId>log4j</groupId>  
  114.             <artifactId>log4j</artifactId>  
  115.             <version>1.2.17</version>  
  116.         </dependency>  
  117.   
  118.         <!– servlet –>  
  119.         <dependency>  
  120.             <groupId>javax.servlet</groupId>  
  121.             <artifactId>servlet-api</artifactId>  
  122.             <version>3.0-alpha-1</version>  
  123.         </dependency>  
  124.   
  125.         <dependency>  
  126.             <groupId>javax.servlet</groupId>  
  127.             <artifactId>jstl</artifactId>  
  128.             <version>1.2</version>  
  129.         </dependency>  
  130.   
  131.         <!– json –>  
  132.         <dependency>  
  133.             <groupId>org.codehaus.jackson</groupId>  
  134.             <artifactId>jackson-mapper-asl</artifactId>  
  135.             <version>1.9.13</version>  
  136.         </dependency>  
  137.   
  138.         <dependency>  
  139.             <groupId>com.alibaba</groupId>  
  140.             <artifactId>fastjson</artifactId>  
  141.             <version>1.2.3</version>  
  142.         </dependency>  
  143.   
  144.         <dependency>  
  145.             <groupId>com.fasterxml.jackson.core</groupId>  
  146.             <artifactId>jackson-annotations</artifactId>  
  147.             <version>${jackson.version}</version>  
  148.         </dependency>  
  149.   
  150.         <dependency>  
  151.             <groupId>com.fasterxml.jackson.core</groupId>  
  152.             <artifactId>jackson-core</artifactId>  
  153.             <version>${jackson.version}</version>  
  154.         </dependency>  
  155.   
  156.         <dependency>  
  157.             <groupId>com.fasterxml.jackson.core</groupId>  
  158.             <artifactId>jackson-databind</artifactId>  
  159.             <version>${jackson.version}</version>  
  160.         </dependency>  
  161.         <!– 文件上传 –>  
  162.         <dependency>  
  163.             <groupId>commons-io</groupId>  
  164.             <artifactId>commons-io</artifactId>  
  165.             <version>2.4</version>  
  166.         </dependency>  
  167.   
  168.         <dependency>  
  169.             <groupId>commons-fileupload</groupId>  
  170.             <artifactId>commons-fileupload</artifactId>  
  171.             <version>1.2.2</version>  
  172.         </dependency>  
  173.   
  174.   
  175.     </dependencies>  
  176.   
  177.   
  178.     <build>  
  179.         <finalName>springmvc_mybatis_demo</finalName>  
  180.         <plugins>  
  181.             <!– Run the JUnit unit tests in an isolated classloader –>  
  182.             <plugin>  
  183.                 <groupId>org.apache.maven.plugins</groupId>  
  184.                 <artifactId>maven-surefire-plugin</artifactId>  
  185.                 <version>2.4.2</version>  
  186.                 <configuration>  
  187.                     <skipTests>true</skipTests>  
  188.                 </configuration>  
  189.             </plugin>  
  190.   
  191.             <plugin>  
  192.                 <groupId>org.apache.maven.plugins</groupId>  
  193.                 <artifactId>maven-war-plugin</artifactId>  
  194.                 <version>2.3</version>  
  195.                 <configuration>  
  196.                     <webXml>src/main/webapp/WEB-INF/web.xml</webXml>  
  197.                 </configuration>  
  198.             </plugin>  
  199.   
  200.             <!– generate java doc –>  
  201.             <plugin>  
  202.                 <groupId>org.apache.maven.plugins</groupId>  
  203.                 <artifactId>maven-javadoc-plugin</artifactId>  
  204.                 <version>2.9.1</version>  
  205.                 <configuration>  
  206.                     <javadocDirectory>target/javadoc</javadocDirectory>  
  207.                     <reportOutputDirectory>target/javadoc</reportOutputDirectory>  
  208.                     <charset>UTF-8</charset>  
  209.                     <encoding>UTF-8</encoding>  
  210.                     <docencoding>UTF-8</docencoding>  
  211.                     <show>private</show>  
  212.                 </configuration>  
  213.             </plugin>  
  214.   
  215.             <!– 部署至本机 –>  
  216.             <plugin>  
  217.                 <groupId>org.codehaus.cargo</groupId>  
  218.                 <artifactId>cargo-maven2-plugin</artifactId>  
  219.                 <version>1.0</version>  
  220.                 <configuration>  
  221.                     <container>  
  222.                         <containerId>tomcat6x</containerId>  
  223.                         <home>D:\WebServer\apache-tomcat-6.0.39</home>  
  224.                     </container>  
  225.                     <configuration>  
  226.                         <type>existing</type>  
  227.                         <home>D:\WebServer\apache-tomcat-6.0.39</home>  
  228.                     </configuration>  
  229.                 </configuration>  
  230.             </plugin>  
  231.   
  232.         </plugins>  
  233.   
  234.     </build>  
  235. </project>  

3、使用Generator自动生成Mybatis相关表信息

      自动生成表的Model,Mapping,Dao文件,先关使用见文章 http://blog.csdn.net/fengshizty/article/details/43086833 

并将其导入到项目的src/main/java包中。

      其中生成的Model中UserInfo如下:

UserInfo.java(其中List<CourseInfo> courseInfos手动添加的)

[java] view
plain
 copy

 在CODE上查看代码片派生到我的代码片

  1. package org.andy.shop.model;  
  2.   
  3. import java.util.List;  
  4.   
  5. public class UserInfo {  
  6.     private Integer id;  
  7.   
  8.     private String uname;  
  9.   
  10.     private Integer unumber;  
  11.   
  12.     private List<CourseInfo> courseInfos;  
  13.   
  14.     public Integer getId() {  
  15.         return id;  
  16.     }  
  17.   
  18.     public void setId(Integer id) {  
  19.         this.id = id;  
  20.     }  
  21.   
  22.     public String getUname() {  
  23.         return uname;  
  24.     }  
  25.   
  26.     public void setUname(String uname) {  
  27.         this.uname = uname == null ? null : uname.trim();  
  28.     }  
  29.   
  30.     public Integer getUnumber() {  
  31.         return unumber;  
  32.     }  
  33.   
  34.     public void setUnumber(Integer unumber) {  
  35.         this.unumber = unumber;  
  36.     }  
  37.   
  38.     public List<CourseInfo> getCourseInfos() {  
  39.         return courseInfos;  
  40.     }  
  41.   
  42. }  



   Dao包中的UserInfoMapper.java

  

[java] view
plain
 copy

 在CODE上查看代码片派生到我的代码片

  1. package org.andy.shop.dao;  
  2.   
  3. import java.util.List;  
  4.   
  5. import org.andy.shop.model.UserInfo;  
  6.   
  7. public interface UserInfoMapper {  
  8.     int deleteByPrimaryKey(Integer id);  
  9.   
  10.     int insert(UserInfo record);  
  11.   
  12.     int insertSelective(UserInfo record);  
  13.   
  14.     UserInfo selectByPrimaryKey(Integer id);  
  15.   
  16.     int updateByPrimaryKeySelective(UserInfo record);  
  17.   
  18.     int updateByPrimaryKey(UserInfo record);  
  19.       
  20.     List<UserInfo> selectAll();  
  21. }  



mapping 中的配置文件UserInfoMapper.xml

[html] view
plain
 copy

 在CODE上查看代码片派生到我的代码片

  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=“org.andy.shop.dao.UserInfoMapper”>  
  4.     <resultMap id=“BaseResultMap” type=“org.andy.shop.model.UserInfo”>  
  5.         <id column=“id” property=“id” jdbcType=“INTEGER” />  
  6.         <result column=“uname” property=“uname” jdbcType=“VARCHAR” />  
  7.         <result column=“unumber” property=“unumber” jdbcType=“INTEGER” />  
  8.     </resultMap>  
  9.     <sql id=“Base_Column_List”>  
  10.         id, uname, unumber  
  11.     </sql>  
  12.     <select id=“selectByPrimaryKey” resultMap=“BaseResultMap”  
  13.         parameterType=“java.lang.Integer”>  
  14.         select  
  15.         <include refid=“Base_Column_List” />  
  16.         from user_info  
  17.         where id = #{id,jdbcType=INTEGER}  
  18.     </select>  
  19.     <delete id=“deleteByPrimaryKey” parameterType=“java.lang.Integer”>  
  20.         delete from  
  21.         user_info  
  22.         where id = #{id,jdbcType=INTEGER}  
  23.     </delete>  
  24.     <insert id=“insert” parameterType=“org.andy.shop.model.UserInfo”>  
  25.         insert into user_info (id,  
  26.         uname, unumber  
  27.         )  
  28.         values (#{id,jdbcType=INTEGER},  
  29.         #{uname,jdbcType=VARCHAR},  
  30.         #{unumber,jdbcType=INTEGER}  
  31.         )  
  32.     </insert>  
  33.     <insert id=“insertSelective” parameterType=“org.andy.shop.model.UserInfo”>  
  34.         insert into user_info  
  35.         <trim prefix=“(“ suffix=“)” suffixOverrides=“,”>  
  36.             <if test=“id != null”>  
  37.                 id,  
  38.             </if>  
  39.             <if test=“uname != null”>  
  40.                 uname,  
  41.             </if>  
  42.             <if test=“unumber != null”>  
  43.                 unumber,  
  44.             </if>  
  45.         </trim>  
  46.         <trim prefix=“values (“ suffix=“)” suffixOverrides=“,”>  
  47.             <if test=“id != null”>  
  48.                 #{id,jdbcType=INTEGER},  
  49.             </if>  
  50.             <if test=“uname != null”>  
  51.                 #{uname,jdbcType=VARCHAR},  
  52.             </if>  
  53.             <if test=“unumber != null”>  
  54.                 #{unumber,jdbcType=INTEGER},  
  55.             </if>  
  56.         </trim>  
  57.     </insert>  
  58.     <update id=“updateByPrimaryKeySelective” parameterType=“org.andy.shop.model.UserInfo”>  
  59.         update user_info  
  60.         <set>  
  61.             <if test=“uname != null”>  
  62.                 uname = #{uname,jdbcType=VARCHAR},  
  63.             </if>  
  64.             <if test=“unumber != null”>  
  65.                 unumber = #{unumber,jdbcType=INTEGER},  
  66.             </if>  
  67.         </set>  
  68.         where id = #{id,jdbcType=INTEGER}  
  69.     </update>  
  70.     <update id=“updateByPrimaryKey” parameterType=“org.andy.shop.model.UserInfo”>  
  71.         update user_info  
  72.         set uname = #{uname,jdbcType=VARCHAR},  
  73.         unumber =  
  74.         #{unumber,jdbcType=INTEGER}  
  75.         where id = #{id,jdbcType=INTEGER}  
  76.     </update>  
  77.   
  78.     <resultMap type=“org.andy.shop.model.UserInfo” id=“UserCourseMap”  
  79.         extends=“BaseResultMap”>  
  80.         <collection property=“courseInfos” javaType=“list”  
  81.             ofType=“org.andy.shop.model.CourseInfo”>  
  82.             <id property=“id” column=“course_id” jdbcType=“INTEGER” />  
  83.             <result property=“cname” column=“cname” jdbcType=“VARCHAR” />  
  84.             <result property=“caddress” column=“caddress” jdbcType=“VARCHAR” />  
  85.         </collection>  
  86.   
  87.   
  88.     </resultMap>  
  89.     <select id=“selectAll” resultMap=“UserCourseMap”>  
  90.         select u.id, u.uname,  
  91.         u.unumber, c.id course_id, c.cname, c.caddress from user_info u left  
  92.         join course_user_info cu on u.id = cu.uid  
  93.         left join course_info c on  
  94.         cu.cid = c.id  
  95.     </select>  
  96. </mapper>  




4、引入Spring并配置相关属性

     在src/main/resources创建spring的配置文件,这里创建了spring.xml,信息如下:

   

[html] view
plain
 copy

 在CODE上查看代码片派生到我的代码片

  1. <?xml version=“1.0” encoding=“UTF-8”?>  
  2. <beans xmlns=“http://www.springframework.org/schema/beans”  
  3.     xmlns:xsi=“http://www.w3.org/2001/XMLSchema-instance” xmlns:context=“http://www.springframework.org/schema/context”  
  4.     xsi:schemaLocation=”http://www.springframework.org/schema/beans  
  5.             http://www.springframework.org/schema/beans/spring-beans-4.1.xsd  
  6.             http://www.springframework.org/schema/context  
  7.             http://www.springframework.org/schema/context/spring-context-4.1.xsd”>  
  8.   
  9.     <!–引入配置属性文件 –>  
  10.     <context:property-placeholder location=“classpath:config.properties” />  
  11.   
  12.     <!–自动扫描含有@Service将其注入为bean –>  
  13.     <context:component-scan base-package=“org.andy.shop.service” />  
  14.   
  15. </beans>  


5、引入Mybatis并配置数据连接池等信息

   5.1、数据连接池druid配置信息 

   配置连接池配置信息在config.properties中,如下:

 

[plain] view
plain
 copy

 在CODE上查看代码片派生到我的代码片

  1. #mysql version database druid setting  
  2. validationQuery=SELECT 1  
  3. jdbc.url=jdbc:mysql://localhost:3306/shop?useUnicode=true&characterEncoding=utf-8  
  4. jdbc.username=root  
  5. jdbc.password=12345  


  5.2、配置Mybatis相关信息

    以下是mybatis的配置信息:spring-mybatis.xml(ps:名字可随便起)

[html] view
plain
 copy

 在CODE上查看代码片派生到我的代码片

  1. <?xml version=“1.0” encoding=“UTF-8”?>  
  2. <beans xmlns=“http://www.springframework.org/schema/beans”  
  3.     xmlns:xsi=“http://www.w3.org/2001/XMLSchema-instance” xmlns:tx=“http://www.springframework.org/schema/tx”  
  4.     xmlns:aop=“http://www.springframework.org/schema/aop”  
  5.     xsi:schemaLocation=”  
  6.         http://www.springframework.org/schema/beans   
  7.         http://www.springframework.org/schema/beans/spring-beans-4.1.xsd   
  8.         http://www.springframework.org/schema/tx   
  9.         http://www.springframework.org/schema/tx/spring-tx-4.1.xsd  
  10.         http://www.springframework.org/schema/aop   
  11.         http://www.springframework.org/schema/aop/spring-aop-4.1.xsd  
  12.         “>  
  13.   
  14.     <!– 配置数据源 使用的是Druid数据源 –>  
  15.     <bean name=“dataSource” class=“com.alibaba.druid.pool.DruidDataSource”  
  16.         init-method=“init” destroy-method=“close”>  
  17.         <property name=“url” value=“${jdbc.url}” />  
  18.         <property name=“username” value=“${jdbc.username}” />  
  19.         <property name=“password” value=“${jdbc.password}” />  
  20.   
  21.         <!– 初始化连接大小 –>  
  22.         <property name=“initialSize” value=“0” />  
  23.         <!– 连接池最大使用连接数量 –>  
  24.         <property name=“maxActive” value=“20” />  
  25.           
  26.         <!– 连接池最小空闲 –>  
  27.         <property name=“minIdle” value=“0” />  
  28.         <!– 获取连接最大等待时间 –>  
  29.         <property name=“maxWait” value=“60000” />  
  30.         <property name=“poolPreparedStatements” value=“true” />  
  31.         <property name=“maxPoolPreparedStatementPerConnectionSize”  
  32.             value=“33” />  
  33.         <!– 用来检测有效sql –>  
  34.         <property name=“validationQuery” value=“${validationQuery}” />  
  35.         <property name=“testOnBorrow” value=“false” />  
  36.         <property name=“testOnReturn” value=“false” />  
  37.         <property name=“testWhileIdle” value=“true” />  
  38.         <!– 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 –>  
  39.         <property name=“timeBetweenEvictionRunsMillis” value=“60000” />  
  40.         <!– 配置一个连接在池中最小生存的时间,单位是毫秒 –>  
  41.         <property name=“minEvictableIdleTimeMillis” value=“25200000” />  
  42.         <!– 打开removeAbandoned功能 –>  
  43.         <property name=“removeAbandoned” value=“true” />  
  44.         <!– 1800秒,也就是30分钟 –>  
  45.         <property name=“removeAbandonedTimeout” value=“1800” />  
  46.         <!– 关闭abanded连接时输出错误日志 –>  
  47.         <property name=“logAbandoned” value=“true” />  
  48.         <!– 监控数据库 –>  
  49.         <property name=“filters” value=“mergeStat” />  
  50.     </bean>  
  51.   
  52.     <!– myBatis文件 –>  
  53.     <bean id=“sqlSessionFactory” class=“org.mybatis.spring.SqlSessionFactoryBean”>  
  54.         <property name=“dataSource” ref=“dataSource” />  
  55.         <!– 自动扫描entity目录, 省掉Configuration.xml里的手工配置 –>  
  56.         <property name=“mapperLocations” value=“classpath:org/andy/shop/mapping/*.xml” />  
  57.     </bean>  
  58.   
  59.     <bean class=“org.mybatis.spring.mapper.MapperScannerConfigurer”>  
  60.         <property name=“basePackage” value=“org.andy.shop.dao” />  
  61.         <property name=“sqlSessionFactoryBeanName” value=“sqlSessionFactory” />  
  62.     </bean>  
  63.   
  64.     <!– 配置事务管理器 –>  
  65.     <bean id=“transactionManager”  
  66.         class=“org.springframework.jdbc.datasource.DataSourceTransactionManager”>  
  67.         <property name=“dataSource” ref=“dataSource” />  
  68.     </bean>  
  69.   
  70.     <!– 注解方式配置事物 –>  
  71.     <!– <tx:annotation-driven transaction-manager=”transactionManager” /> –>  
  72.   
  73.     <!– 拦截器方式配置事物 –>  
  74.     <tx:advice id=“transactionAdvice” transaction-manager=“transactionManager”>  
  75.         <tx:attributes>  
  76.             <tx:method name=“insert*” propagation=“REQUIRED” />  
  77.             <tx:method name=“update*” propagation=“REQUIRED” />  
  78.             <tx:method name=“delete*” propagation=“REQUIRED” />  
  79.   
  80.             <tx:method name=“get*” propagation=“SUPPORTS” read-only=“true” />  
  81.             <tx:method name=“find*” propagation=“SUPPORTS” read-only=“true” />  
  82.             <tx:method name=“select*” propagation=“SUPPORTS” read-only=“true” />  
  83.   
  84.         </tx:attributes>  
  85.     </tx:advice>  
  86.     <!– Spring aop事务管理 –>  
  87.     <aop:config>  
  88.         <aop:pointcut id=“transactionPointcut”  
  89.             expression=“execution(* org.andy.shop.service..*Impl.*(..))” />  
  90.         <aop:advisor pointcut-ref=“transactionPointcut”  
  91.             advice-ref=“transactionAdvice” />  
  92.     </aop:config>  
  93.   
  94. </beans>  



主要配置数据连接池,事务管理, mybatis关联映射等,事务采用aop的声明式事务。


6、引入日志

     在src/main/resources中添加log4j日志配置信息:

   log4j.properties

[plain] view
plain
 copy

 在CODE上查看代码片派生到我的代码片

  1. ### set log levels ###  
  2. log4j.rootLogger = INFO , C , D , E   
  3.   
  4. ### console ###  
  5. log4j.appender.C = org.apache.log4j.ConsoleAppender  
  6. log4j.appender.C.Target = System.out  
  7. log4j.appender.C.layout = org.apache.log4j.PatternLayout  
  8. log4j.appender.C.layout.ConversionPattern = [springmvc_mybatis_demo][%p] [%-d{yyyy-MM-dd HH:mm:ss}] %C.%M(%L) | %m%n  
  9.   
  10. ### log file ###  
  11. log4j.appender.D = org.apache.log4j.DailyRollingFileAppender  
  12. log4j.appender.D.File = ../logs/springmvc-mybatis-demo.log  
  13. log4j.appender.D.Append = true  
  14. log4j.appender.D.Threshold = INFO   
  15. log4j.appender.D.layout = org.apache.log4j.PatternLayout  
  16. log4j.appender.D.layout.ConversionPattern = [springmvc_mybatis_demo][%p] [%-d{yyyy-MM-dd HH:mm:ss}] %C.%M(%L) | %m%n  
  17.   
  18. ### exception ###  
  19. log4j.appender.E = org.apache.log4j.DailyRollingFileAppender  
  20. log4j.appender.E.File = ../logs/springmvc-mybatis-demo_error.log   
  21. log4j.appender.E.Append = true  
  22. log4j.appender.E.Threshold = ERROR   
  23. log4j.appender.E.layout = org.apache.log4j.PatternLayout  
  24. log4j.appender.E.layout.ConversionPattern = [sspringmvc_mybatis_demo][%p] [%-d{yyyy-MM-dd HH:mm:ss}] %C.%M(%L) | %m%n  

7、创建Service

    在src/main/java中创建相关的org.andy.shop.service包和org.andy.shop.service.Impl包。

    UserService接口:

 

[java] view
plain
 copy

 在CODE上查看代码片派生到我的代码片

  1. package org.andy.shop.service;  
  2.   
  3. import java.util.List;  
  4.   
  5. import org.andy.shop.model.UserInfo;  
  6.   
  7. /**   
  8.  * 创建时间:2015-1-27 下午5:15:03   
  9.  * @author andy   
  10.  * @version 2.2   
  11.  */  
  12.   
  13. public interface UserService {  
  14.   
  15.     UserInfo getUserById(int id);  
  16.       
  17.     List<UserInfo> getUsers();  
  18.       
  19.     int insert(UserInfo userInfo);  
  20. }  

   UserServiceImpl实现Service:

[java] view
plain
 copy

 在CODE上查看代码片派生到我的代码片

  1. package org.andy.shop.service.impl;  
  2.   
  3. import java.util.List;  
  4.   
  5. import org.andy.shop.dao.UserInfoMapper;  
  6. import org.andy.shop.model.UserInfo;  
  7. import org.andy.shop.service.UserService;  
  8. import org.springframework.beans.factory.annotation.Autowired;  
  9. import org.springframework.stereotype.Service;  
  10.   
  11. /** 
  12.  * 创建时间:2015-1-27 下午5:22:59 
  13.  *  
  14.  * @author andy 
  15.  * @version 2.2 
  16.  */  
  17. @Service(“userService”)  
  18. public class UserServiceImpl implements UserService {  
  19.   
  20.     @Autowired  
  21.     private UserInfoMapper userInfoMapper;  
  22.   
  23.     @Override  
  24.     public UserInfo getUserById(int id) {  
  25.         return userInfoMapper.selectByPrimaryKey(id);  
  26.     }  
  27.   
  28.     @Override  
  29.     public List<UserInfo> getUsers() {  
  30.         return userInfoMapper.selectAll();  
  31.     }  
  32.   
  33.     @Override  
  34.     public int insert(UserInfo userInfo) {  
  35.           
  36.         int result = userInfoMapper.insert(userInfo);  
  37.           
  38.         System.out.println(result);  
  39.         return result;  
  40.     }  
  41.   
  42. }  


8、测试Spring和Mybatis配置

   在src/test/java中写测试类,检测是否能够读出数据,若能读出则证明Spring+Mybatis整合成功。

TestUserService测试类:

[java] view
plain
 copy

 在CODE上查看代码片派生到我的代码片

  1. package org.andy.shop.service;  
  2.   
  3. import java.util.List;  
  4.   
  5. import org.andy.shop.model.UserInfo;  
  6. import org.apache.log4j.Logger;  
  7. import org.junit.Test;  
  8. import org.junit.runner.RunWith;  
  9. import org.springframework.beans.factory.annotation.Autowired;  
  10. import org.springframework.test.context.ContextConfiguration;  
  11. import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;  
  12.   
  13. import com.alibaba.fastjson.JSON;  
  14.   
  15. /** 
  16.  * 创建时间:2015-1-27 下午10:45:38 
  17.  *  
  18.  * @author andy 
  19.  * @version 2.2 
  20.  */  
  21. @RunWith(SpringJUnit4ClassRunner.class)  
  22. @ContextConfiguration(locations = { “classpath:spring.xml”,  
  23.         “classpath:spring-mybatis.xml” })  
  24. public class TestUserService {  
  25.   
  26.     private static final Logger LOGGER = Logger  
  27.             .getLogger(TestUserService.class);  
  28.   
  29.     @Autowired  
  30.     private UserService userService;  
  31.   
  32.       
  33.     @Test  
  34.     public void testQueryById1() {  
  35.         UserInfo userInfo = userService.getUserById(1);  
  36.         LOGGER.info(JSON.toJSON(userInfo));  
  37.     }  
  38.   
  39.     @Test  
  40.     public void testQueryAll() {  
  41.         List<UserInfo> userInfos = userService.getUsers();  
  42.         LOGGER.info(JSON.toJSON(userInfos));  
  43.     }  
  44.   
  45.     @Test  
  46.     public void testInsert() {  
  47.         UserInfo userInfo = new UserInfo();  
  48.         userInfo.setUname(“xiaoming”);  
  49.         userInfo.setUnumber(4);  
  50.         int result = userService.insert(userInfo);  
  51.         System.out.println(result);  
  52.     }  
  53. }  



若是测试成功,那证明已经成功了一半了。

9、引入SpringMVC

   9.1 配置SpringMVC配置信息

    SpringMVC的配置信息主要包括控制层Controller的bean管理,视图层和控制层配置等等,下面是spring-mvc.xml信息:

 

[html] view
plain
 copy

 在CODE上查看代码片派生到我的代码片

  1. <?xml version=“1.0” encoding=“UTF-8”?>  
  2. <beans xmlns=“http://www.springframework.org/schema/beans”  
  3.     xmlns:mvc=“http://www.springframework.org/schema/mvc” xmlns:xsi=“http://www.w3.org/2001/XMLSchema-instance”  
  4.     xmlns:p=“http://www.springframework.org/schema/p” xmlns:context=“http://www.springframework.org/schema/context”  
  5.     xsi:schemaLocation=”http://www.springframework.org/schema/beans   
  6.         http://www.springframework.org/schema/beans/spring-beans-4.1.xsd   
  7.         http://www.springframework.org/schema/context   
  8.         http://www.springframework.org/schema/context/spring-context-4.1.xsd   
  9.         http://www.springframework.org/schema/mvc   
  10.         http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd”>  
  11.   
  12.     <!– 自动扫描controller包下的所有类,如果@Controller注入为bean –>  
  13.     <context:component-scan base-package=“org.andy.shop.controller” />  
  14.   
  15.     <!– 避免IE执行AJAX时,返回JSON出现下载文件 –>  
  16.     <bean id=“mappingJacksonHttpMessageConverter”  
  17.         class=“org.springframework.http.converter.json.MappingJackson2HttpMessageConverter”>  
  18.         <property name=“supportedMediaTypes”>  
  19.             <list>  
  20.                 <value>text/html;charset=UTF-8</value>  
  21.             </list>  
  22.         </property>  
  23.     </bean>  
  24.   
  25.     <!– 启动Spring MVC的注解功能,完成请求和注解POJO的映射 –>  
  26.     <bean  
  27.         class=“org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter”>  
  28.         <property name=“messageConverters”>  
  29.             <list>  
  30.                 <!– json转换器 –>  
  31.                 <ref bean=“mappingJacksonHttpMessageConverter” />  
  32.             </list>  
  33.         </property>  
  34.     </bean>  
  35.   
  36.     <!– 对模型视图名称的解析,即在模型视图名称添加前后缀 –>  
  37.     <bean  
  38.         class=“org.springframework.web.servlet.view.InternalResourceViewResolver”>  
  39.         <property name=“viewClass”  
  40.             value=“org.springframework.web.servlet.view.JstlView” />  
  41.         <property name=“prefix” value=“/WEB-INF/views” />  
  42.         <property name=“suffix” value=“.jsp” />  
  43.     </bean>  
  44.   
  45.     <!– 配置多文件上传 –>  
  46.     <bean id=“multipartResolver”  
  47.         class=“org.springframework.web.multipart.commons.CommonsMultipartResolver”>  
  48.         <property name=“defaultEncoding”>  
  49.             <value>UTF-8</value>  
  50.         </property>  
  51.         <property name=“maxUploadSize”>  
  52.             <!– 上传文件大小限制为31M,31*1024*1024 –>  
  53.             <value>32505856</value>  
  54.         </property>  
  55.         <property name=“maxInMemorySize”>  
  56.             <value>4096</value>  
  57.         </property>  
  58.     </bean>  
  59.   
  60. </beans>  



  自动扫描org.andy.shop.controller报下还有@Controller的控制层,注入为bean。

 9.2、Web容器web.xml配置

    web容器配置启动加载的配置文件,设置SpringMVC拦截的请求(此处拦截.htmls结尾的url请求)

[html] view
plain
 copy

 在CODE上查看代码片派生到我的代码片

  1. <?xml version=“1.0” encoding=“UTF-8”?>  
  2. <web-app xmlns:xsi=“http://www.w3.org/2001/XMLSchema-instance”  
  3.     xmlns=“http://java.sun.com/xml/ns/javaee” xmlns:web=“http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd”  
  4.     xsi:schemaLocation=“http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd”  
  5.     id=“WebApp_ID” version=“2.5”>  
  6.   
  7.     <display-name>springmvc_mybatis_demo</display-name>  
  8.   
  9.     <context-param>  
  10.         <param-name>contextConfigLocation</param-name>  
  11.         <param-value>classpath:spring.xml,classpath:spring-mybatis.xml</param-value>  
  12.     </context-param>  
  13.   
  14.     <filter>  
  15.         <filter-name>encodingFilter</filter-name>  
  16.         <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>  
  17.         <init-param>  
  18.             <param-name>encoding</param-name>  
  19.             <param-value>utf-8</param-value>  
  20.         </init-param>  
  21.         <init-param>  
  22.             <param-name>forceEncoding</param-name>  
  23.             <param-value>true</param-value>  
  24.         </init-param>  
  25.     </filter>  
  26.     <filter-mapping>  
  27.         <filter-name>encodingFilter</filter-name>  
  28.         <url-pattern>/*</url-pattern>  
  29.     </filter-mapping>  
  30.   
  31.     <listener>  
  32.         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
  33.     </listener>  
  34.   
  35.     <!– 防止spring内存溢出监听器 –>  
  36.     <listener>  
  37.         <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>  
  38.     </listener>  
  39.   
  40.     <servlet>  
  41.         <description>spring mvc servlet</description>  
  42.         <servlet-name>rest</servlet-name>  
  43.         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
  44.         <init-param>  
  45.             <param-name>contextConfigLocation</param-name>  
  46.             <param-value>  
  47.                 classpath:spring-mvc.xml  
  48.             </param-value>  
  49.         </init-param>  
  50.         <load-on-startup>1</load-on-startup>  
  51.     </servlet>  
  52.     <servlet-mapping>  
  53.         <servlet-name>rest</servlet-name>  
  54.         <url-pattern>*.htmls</url-pattern>  
  55.     </servlet-mapping>  
  56.   
  57.     <!– 配置session超时时间,单位分钟 –>  
  58.     <session-config>  
  59.         <session-timeout>30</session-timeout>  
  60.     </session-config>  
  61.   
  62.     <welcome-file-list>  
  63.         <welcome-file>index.jsp</welcome-file>  
  64.     </welcome-file-list>  
  65. </web-app>  




  9.3、Controller控制层

    在org.andy.shop.controller创建控制层,如UserController.java

 

[java] view
plain
 copy

 在CODE上查看代码片派生到我的代码片

  1. package org.andy.shop.controller;  
  2.   
  3. import java.util.List;  
  4.   
  5. import org.andy.shop.model.UserInfo;  
  6. import org.andy.shop.service.UserService;  
  7. import org.springframework.beans.factory.annotation.Autowired;  
  8. import org.springframework.stereotype.Controller;  
  9. import org.springframework.ui.ModelMap;  
  10. import org.springframework.web.bind.annotation.PathVariable;  
  11. import org.springframework.web.bind.annotation.RequestMapping;  
  12. import org.springframework.web.bind.annotation.ResponseBody;  
  13.   
  14. /**   
  15.  * 创建时间:2015-1-28 下午1:17:27   
  16.  * @author andy   
  17.  * @version 2.2   
  18.  */  
  19. @Controller  
  20. @RequestMapping(“/user”)  
  21. public class UserController {  
  22.   
  23.     @Autowired  
  24.     private UserService userService;  
  25.       
  26.     @RequestMapping(“/showInfo/{userId}”)  
  27.     public String showUserInfo(ModelMap modelMap, @PathVariable int userId){  
  28.         UserInfo userInfo = userService.getUserById(userId);  
  29.         modelMap.addAttribute(“userInfo”, userInfo);  
  30.         return “/user/showInfo”;  
  31.     }  
  32.       
  33.     @RequestMapping(“/showInfos”)  
  34.     public @ResponseBody Object showUserInfos(){  
  35.         List<UserInfo> userInfos = userService.getUsers();  
  36.         return userInfos;  
  37.     }  
  38. }  

9.4、视图层

  在WEB-INF创建视图总目录views(为了安全起见一般都在WEB-INF下创建),创建/user/showInfo.jsp视图文件。

 

[html] view
plain
 copy

 在CODE上查看代码片派生到我的代码片

  1. <%@ page language=“java” contentType=“text/html; charset=UTF-8” pageEncoding=“UTF-8”%>  
  2.   
  3. <!DOCTYPE html PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN” “http://www.w3.org/TR/html4/loose.dtd”>  
  4. <html>  
  5. <head>  
  6. <meta http-equiv=“Content-Type” content=“text/html; charset=UTF-8”>  
  7. <title>userInfo</title>  
  8. </head>  
  9. <body>  
  10.   
  11.      姓名: ${userInfo.uname}  
  12.   
  13. </body>  
  14. </html>  


 9.5、项目总目录结构

   到此为demo以及基本创建完成总目录如下:

     

10、项目测试

    将项目编译,Maven build…输入clean compile package,部署到Tomcat服务器,启动项目。

   测试1:测试第一个url,  http://localhost:8080/springmvc_mybatis_demo/user/showInfo/1.htmls

     


   测试2:测试第二个json数据返回的url,  http://localhost:8080/springmvc_mybatis_demo/user/showInfos.htmls

    

发表评论

电子邮件地址不会被公开。 必填项已用*标注

昵称 *