mybatis3.2.6整合spring4.0和springMVC4.0开发

  1. 云栖社区>
  2. 博客列表>
  3. 正文

mybatis3.2.6整合spring4.0和springMVC4.0开发

jeanheo 2016-03-20 11:08:00 浏览3307 评论0

摘要: 1. 新建项目,导入jar包 在eclipse/myeclipse上新建一个web项目,导入如下图所示的jar包,关于jar包的整合资源可到http://download.csdn.net/detail/qwe6112071/9467007

1. 新建项目,导入jar包

在eclipse/myeclipse上新建一个web项目,导入如下图所示的jar包,关于jar包的整合资源可到http://download.csdn.net/detail/qwe6112071/9467007进行下载
这里写图片描述

如果使用了maven,则配置更为方便:

<properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <!-- spring版本号 -->
        <spring.version>4.0.2.RELEASE</spring.version>
        <!-- mybatis版本号 -->
        <mybatis.version>3.2.6</mybatis.version>
        <!-- log4j日志文件管理包版本 -->
        <slf4j.version>1.7.7</slf4j.version>
        <log4j.version>1.2.17</log4j.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <!-- 表示开发的时候引入,发布的时候不会加载此包 -->
            <scope>test</scope>
        </dependency>
        <!-- spring核心包 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-oxm</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!-- mybatis核心包 -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>${mybatis.version}</version>
        </dependency>
        <!-- mybatis/spring包 -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.2.2</version>
        </dependency>
        <!-- 导入java ee jar 包 -->
        <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-api</artifactId>
            <version>7.0</version>
        </dependency>
        <!-- 导入Mysql数据库链接jar包 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.30</version>
        </dependency>
        <!-- 导入dbcp的jar包,用来在applicationContext.xml中配置数据库 -->
        <dependency>
            <groupId>commons-dbcp</groupId>
            <artifactId>commons-dbcp</artifactId>
            <version>1.2.2</version>
        </dependency>
        <!-- 日志文件管理包 -->
        <!-- log start -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>${log4j.version}</version>
        </dependency>

        <!-- 格式化对象,方便输出日志 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.1.41</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>${slf4j.version}</version>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>${slf4j.version}</version>
        </dependency>
        <!-- log end -->
        <!-- 映入JSON -->
        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-mapper-asl</artifactId>
            <version>1.9.13</version>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.4</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.6.11</version>
        </dependency>
    </dependencies>

2. 配置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"  
    version="3.0">  
    <display-name>demo</display-name>  

     <!-- 该servlet为tomcat,jetty等容器提供,将静态资源映射从/改为/static/目录,如原来访问 http://localhost/foo.css ,现在http://localhost/static/foo.css -->  
    <!-- 不拦截静态文件 -->  
    <servlet-mapping>  
        <servlet-name>default</servlet-name>  
        <url-pattern>/js/*</url-pattern>  
        <url-pattern>/css/*</url-pattern>  
        <url-pattern>/images/*</url-pattern>  
        <url-pattern>/fonts/*</url-pattern>  
    </servlet-mapping> 

    <!-- Spring和mybatis的配置文件 -->  
    <context-param>  
        <param-name>contextConfigLocation</param-name>  
        <param-value>classpath*:spring/spring-*.xml</param-value>  
    </context-param>  
    <!-- 编码过滤器 -->  
    <filter>  
        <filter-name>encodingFilter</filter-name>  
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>  
        <async-supported>true</async-supported>  
        <init-param>  
            <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>  
    <!-- Spring监听器 -->  
    <listener>  
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
    </listener>  
    <!-- 防止Spring内存溢出监听器 -->  
    <listener>  
        <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>  
    </listener>  

    <!-- Spring MVC servlet -->  
    <servlet>  
        <servlet-name>SpringMVC</servlet-name>  
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
        <init-param>  
            <param-name>contextConfigLocation</param-name>  
            <param-value>classpath:spring/spring-mvc.xml</param-value>  
        </init-param>  
        <load-on-startup>1</load-on-startup>  
        <async-supported>true</async-supported>  
    </servlet>  
    <servlet-mapping>  
        <servlet-name>SpringMVC</servlet-name>  
        <!-- 此处可以可以配置成*.do,对应struts的后缀习惯 -->  
        <url-pattern>/</url-pattern>  
    </servlet-mapping>  
    <welcome-file-list>  
        <welcome-file>/index.jsp</welcome-file>  
    </welcome-file-list>  

</web-app>  

3. 配置日志记录文件

在classpath路径下创建文件log4j.properties,并在里面填写

 log4j.rootLogger=DEBUG,Console,File  
#定义日志输出目的地为控制台  
log4j.appender.Console=org.apache.log4j.ConsoleAppender  
log4j.appender.Console.Target=System.out  
#可以灵活地指定日志输出格式,下面一行是指定具体的格式  
log4j.appender.Console.layout = org.apache.log4j.PatternLayout  
log4j.appender.Console.layout.ConversionPattern=[%c] - %m%n  

#文件大小到达指定尺寸的时候产生一个新的文件  
log4j.appender.File = org.apache.log4j.RollingFileAppender  
#指定输出目录  
log4j.appender.File.File = logs/ssm.log  
#定义文件最大大小  
log4j.appender.File.MaxFileSize = 10MB  
# 输出所以日志,如果换成DEBUG表示输出DEBUG以上级别日志  
log4j.appender.File.Threshold = ALL  
log4j.appender.File.layout = org.apache.log4j.PatternLayout  
log4j.appender.File.layout.ConversionPattern =[%p] [%d{yyyy-MM-dd HH\:mm\:ss}][%c]%m%n 

4. 配置spring-mybatis整合文件

<?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"
    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.1.xsd    
                        http://www.springframework.org/schema/context    
                        http://www.springframework.org/schema/context/spring-context-3.1.xsd    
                        http://www.springframework.org/schema/mvc    
                        http://www.springframework.org/schema/mvc/spring-mvc-4.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">

    <!-- 自动扫描 -->
    <context:component-scan base-package="com.yc" />
    <!-- 引入配置文件 -->
    <bean id="propertyConfigurer"
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location" value="classpath:jdbc.properties" />
    </bean>

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
        destroy-method="close">
        <property name="driverClassName" value="${driver}" />
        <property name="url" value="${url}" />
        <property name="username" value="${username}" />
        <property name="password" value="${password}" />
        <!-- 初始化连接大小 -->
        <property name="initialSize" value="${initialSize}"></property>
        <!-- 连接池最大数量 -->
        <property name="maxActive" value="${maxActive}"></property>
        <!-- 连接池最大空闲 -->
        <property name="maxIdle" value="${maxIdle}"></property>
        <!-- 连接池最小空闲 -->
        <property name="minIdle" value="${minIdle}"></property>
        <!-- 获取连接最大等待时间 -->
        <property name="maxWait" value="${maxWait}"></property>
    </bean>

    <!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 实例化sqlSessionFactory时需要使用上述配置好的数据源以及SQL映射文件 -->
        <property name="dataSource" ref="dataSource" />
        <!-- 自动扫描mapping.xml文件 , 省掉Configuration.xml里的手工配置 -->
        <property name="mapperLocations" value="classpath*:com/yc/mapping/*Mapper.xml"></property>
    </bean>

    <!-- DAO接口所在包名,Spring会自动查找对应包及其子包下的所有映射接口类 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.yc.dao" />
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
    </bean>

    <!-- (事务管理)transaction manager, use JtaTransactionManager for global tx -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> 
        <property name="dataSource" ref="dataSource" /> </bean>
    <!-- 拦截器方式配置事物 -->
    <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="*" propagation="SUPPORTS" />
        </tx:attributes>
    </tx:advice>
    <aop:config>
        <aop:pointcut id="transactionPointcut"
            expression="execution(* com.yc.service..*Impl.*(..))" />
        <aop:advisor pointcut-ref="transactionPointcut"
            advice-ref="transactionAdvice" />
    </aop:config>
</beans>

5. 配置model、mapping文件

先配置数据库测试表,这里以一个移动端后台的用户表为例,因为已经在数据库建好表了,这时可以到$MYSQL_HOME/bin目录下使用命令:
mysqldump -u用户名 -p密码 数据库 用户表
来导出相应的表结构如
mysqldump -uyc -pyc yc User > /home/user.sql
到对应目录打开user.sql文件则得到如下的建表sql语句:

DROP TABLE IF EXISTS `User`;
CREATE TABLE `User` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `headImg` varchar(255) DEFAULT NULL,
  `isDeleted` int(11) NOT NULL DEFAULT '0',
  `name` varchar(255) DEFAULT NULL,
  `password` varchar(255) DEFAULT NULL,
  `phoneNum` varchar(255) DEFAULT NULL,
  `userType` varchar(255) DEFAULT NULL,
  `openId` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=14 DEFAULT CHARSET=utf8;
#以下插入两条测试数据
LOCK TABLES `User` WRITE;
/*!40000 ALTER TABLE `User` DISABLE KEYS */;
INSERT INTO `User` VALUES (12,'http://localhost:8090/dheadImg/1.jpg',0,'glcnk','$2a$10$EpmkvDhQU5AHkn3Mvq1oDuJbT83aZRooqF0ZxdawiQsTz/sWfpxJa','1234','normal',NULL),(13,'http://localhost:8090/dheadImg/1.jpg',0,'psnys','$2a$10$dv4EQjbMwmUpbNB.kFySNe9RRJ1jwAXliK4FotoRLDrdfSAyWkk7C','3412','normal',NULL);
UNLOCK TABLES;

完成数据库建表后,创建pojo文件、xml等文件,这里有两种方式,一种是手动配置,另一种是通过数据库反向生成:

1. 手动配置

  1. 先创建对应的pojo类

        package com.yc.model;
    
        public class User {
            private Integer id;
    
            private String headimg;
    
            private Integer isdeleted;
    
            private String name;
    
            private String password;
    
            private String phonenum;
    
            private String usertype;
    
            private String openid;
    
            //方便测试时用到
            @Override
            public String toString() {
                return "User [id=" + id + ", headimg=" + headimg + ", isdeleted="
                        + isdeleted + ", name=" + name + ", password=" + password
                        + ", phonenum=" + phonenum + ", usertype=" + usertype
                        + ", openid=" + openid + "]";
            }
    
            getter and setter here.....
    }
  2. 创建映射接口java文件

        package com.yc.dao;
    
        import com.yc.model.User;
    
        public interface UserMapper {
            User selectByPrimaryKey(Integer id);
    
        }
  3. 创建对应的UserMapper.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.yc.dao.UserMapper" ><!-- 必须是UserMapper接口的全类名 -->
 <resultMap id="BaseResultMap" type="com.yc.model.User" >
   <id column="id" property="id" jdbcType="INTEGER" />
   <result column="headImg" property="headimg" jdbcType="VARCHAR" />
   <result column="isDeleted" property="isdeleted" jdbcType="INTEGER" />
   <result column="name" property="name" jdbcType="VARCHAR" />
   <result column="password" property="password" jdbcType="VARCHAR" />
   <result column="phoneNum" property="phonenum" jdbcType="VARCHAR" />
   <result column="userType" property="usertype" jdbcType="VARCHAR" />
   <result column="openId" property="openid" jdbcType="VARCHAR" />
 </resultMap>
 <sql id="Base_Column_List" >
   id, headImg, isDeleted, name, password, phoneNum, userType, openId
 </sql>
 <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
   select 
   <include refid="Base_Column_List" />
   from User
   where id = #{id,jdbcType=INTEGER}
 </select>
</mapper>

这里需要注意的是一些开发规范的问题,对应spring-mybatis.xml扫描配置,UserMapper.java文件存放在classpath:com/yc/dao下,UserMapper.xml存放在classpath:com/yc/mapping下,同时要特别注意的是UserMapper.xml文件中的namespace套与UserMapper.java文件相对应,如本例中的com.yc.model.User如果这里配置错误的话,我们在测试时会报如下错误信息:
nested exception is org.springframework.core.NestedIOException: Failed to parse mapping resource: ‘file [/home/myBatisYc/target/classes/com/yc/mapping/UserMapper.xml]’; nested exception is org.apache.ibatis.builder.BuilderException: Error parsing Mapper XML. Cause: org.apache.ibatis.builder.BuilderException: Error resolving class. Cause: org.apache.ibatis.type.TypeException: Could not resolve type alias ‘com.yc.User’. Cause: java.lang.ClassNotFoundException: Cannot find class: com.yc.User

2. 通过数据库建表反向生成

可先到 http://download.csdn.net/detail/qwe6112071/9467019下载生成工具,解压,然后配置里面的generator.xml文件,配置实例如下:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
<!-- 数据库驱动包位置 -->
<classPathEntry location="/home/zenghao/下载/generator/mysql-connector-java-5.1.34.jar" /> 
<!-- <classPathEntry location="C:\oracle\product\10.2.0\db_1\jdbc\lib\ojdbc14.jar" />-->
<context id="DB2Tables" targetRuntime="MyBatis3">
    <commentGenerator>
        <property name="suppressAllComments" value="true" />
    </commentGenerator>
    <!-- 数据库链接URL、用户名、密码 -->
     <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/yc" userId="root" password="root"> 
    <!--<jdbcConnection driverClass="oracle.jdbc.driver.OracleDriver" connectionURL="jdbc:oracle:thin:@localhost:1521:orcl" userId="msa" password="msa">-->
    </jdbcConnection>
    <javaTypeResolver>
        <property name="forceBigDecimals" value="false" />
    </javaTypeResolver>
    <!-- 生成模型的包名和位置 -->
    <javaModelGenerator targetPackage="com.yc.model" targetProject="/home/zenghao/mybatis">
        <property name="enableSubPackages" value="true" />
        <property name="trimStrings" value="true" />
    </javaModelGenerator>
    <!-- 生成的映射文件包名和位置 -->
    <sqlMapGenerator targetPackage="com.yc.mapping" targetProject="/home/zenghao/mybatis">
        <property name="enableSubPackages" value="true" />
    </sqlMapGenerator>
    <!-- 生成DAO的包名和位置 -->
    <javaClientGenerator type="XMLMAPPER" targetPackage="com.yc.dao" targetProject="/home/zenghao/mybatis">
        <property name="enableSubPackages" value="true" />
    </javaClientGenerator>
    <!-- 要生成那些表(更改tableName和domainObjectName就可以) -->
    <table tableName="Article" domainObjectName="BackArticle" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false" />
<table tableName="User" domainObjectName="User" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false" />
</context>
</generatorConfiguration>

注意根据你的下载路径来配置正确的数据库驱动包位置,对应targetProject等属性的配置,不一定真正要在你的项目中,可以先生成到任意位置,然后复制导入,配置好后,在当前目录下通过命令行执行java -jar mybatis-generator-core-1.3.2.jar -configfile generator.xml -overwrite即可

6. 使用junit4测试配置

创建测试文件:

package com.yc.test;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.yc.dao.UserMapper;
import com.yc.model.User;

public class Test1 {
    private UserMapper userMapper;
    /**
     * 这个before方法在所有的测试方法之前执行,并且只执行一次
     * 所有做Junit单元测试时一些初始化工作可以在这个方法里面进行
     * 比如在before方法里面初始化ApplicationContext和usermapper
     */
    @Before
    public void before(){
        ApplicationContext ac = new ClassPathXmlApplicationContext("classpath:spring/spring-mybatis.xml");
        userMapper = (UserMapper) ac.getBean("userMapper");
    }

    @Test
    public void test(){
        User user = userMapper.selectByPrimaryKey(12);
        System.out.println(user);
        /*
        * 结合前面数据库插入的数据,这里会打印出信息:
        *   User [id=12, headimg=http://localhost:8090/dheadImg/1.jpg, isdeleted=0, name=glcnk, password=$2a$10$EpmkvDhQU5AHkn3Mvq1oDuJbT83aZRooqF0ZxdawiQsTz/sWfpxJa, phonenum=1234, usertype=normal, openid=null]
        */
    }
    /*
    * 在测试方法后调用,主要进行资源的销毁工作。
    */
    @After
    public void after(){
        userMapper = null;
        ac = null;
    }
}

7. 配置spring-mvc.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-3.1.xsd    
                        http://www.springframework.org/schema/context    
                        http://www.springframework.org/schema/context/spring-context-3.1.xsd    
                        http://www.springframework.org/schema/mvc    
                        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">


    <!-- 启用spring mvc 注解 -->
    <mvc:annotation-driven />
    <!-- 自动扫描该包,使SpringMVC认为包下用了@controller注解的类是控制器 -->
    <context:component-scan base-package="com.yc.controller" />
    <context:component-scan base-package="com.yc.service" />
    <!--避免IE执行AJAX时,返回JSON出现下载文件 -->
    <bean id="mappingJacksonHttpMessageConverter"
        class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
        <property name="supportedMediaTypes">
            <list>
                <value>text/html;charset=UTF-8</value>
            </list>
        </property>
    </bean>
    <!-- 启动SpringMVC的注解功能,完成请求和注解POJO的映射 -->
    <bean
        class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <property name="messageConverters">
            <list>
                <ref bean="mappingJacksonHttpMessageConverter" /> <!-- JSON转换器 -->
            </list>
        </property>
    </bean>
    <!-- 定义跳转的文件的前后缀 ,视图模式配置 -->
    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!-- 这里的配置我的理解是自动给后面action的方法return的字符串加上前缀和后缀,变成一个 可用的url地址 -->
        <property name="prefix" value="/WEB-INF/views/" />
        <property name="suffix" value=".jsp" />
    </bean>

    <!-- 配置文件上传,如果没有使用文件上传可以不用配置,当然如果不配,那么配置文件中也不必引入上传组件包 -->
    <!-- <bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        默认编码
        <property name="defaultEncoding" value="utf-8" />
        文件大小最大值
        <property name="maxUploadSize" value="10485760000" />
        内存中的最大值
        <property name="maxInMemorySize" value="40960" />
    </bean> -->

</beans>  

8. 配置service层和controller层文件

package com.yc.service;

import com.yc.model.User;

public interface IUserService {
    User selectByPrimaryKey(Integer id);
}
/*--------------------------分割线-------------------------*/
package com.yc.service;

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

import com.yc.dao.UserMapper;
import com.yc.model.User;

@Service
public class UserService implements IUserService {

    @Autowired
    private UserMapper userMapper;
    @Override
    public User selectByPrimaryKey(Integer id) {
        return userMapper.selectByPrimaryKey(id);
    }

}
/*--------------------------分割线-------------------------*/
package com.yc.controller;

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

import com.yc.model.User;
import com.yc.service.IUserService;

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private IUserService userService;

    @RequestMapping("getUser")
    @ResponseBody//将返回内容序列化成json格式输出
    public User getUser(Integer id){
        return userService.selectByPrimaryKey(id);
    }
}

9. 测试springMVC

将项目部署到tomcat服务器中,打开游览器,访问http://localhost:8080/myBatisYc/user/getUser?id=13,我们会看到游览器中打印了User序列化后的json格式字符串:
{"id":13,"headimg":"http://localhost:8090/dheadImg/1.jpg","isdeleted":0,"name":"psnys","password":"$2a$10$dv4EQjbMwmUpbNB.kFySNe9RRJ1jwAXliK4FotoRLDrdfSAyWkk7C","phonenum":"3412","usertype":"normal","openid":null}

至此,我们的mybatis3.2.6整合spring4和springMVC4配置已完成

用云栖社区APP,舒服~

【云栖快讯】云栖社区技术交流群汇总,阿里巴巴技术专家及云栖社区专家等你加入互动,老铁,了解一下?  详情请点击

网友评论

jeanheo
文章87篇 | 关注52
关注
大数据开发套件(Data IDE),提供可视化开发界面、离线任务调度运维、快速数据集成、多人... 查看详情
阿里云移动APP解决方案,助力开发者轻松应对移动app中随时可能出现的用户数量的爆发式增长、... 查看详情
阿里云专门为物联网领域的开发人员推出的,其目的是帮助开发者搭建安全性能强大的数据通道,方便终... 查看详情
为您提供简单高效、处理能力可弹性伸缩的计算服务,帮助您快速构建更稳定、安全的应用,提升运维效... 查看详情
阿里中间件云大使

阿里中间件云大使