JavaWeb项目整合Spring,SpringMVC,Mybatis框架

衔接上篇:
使用IDEA创建基于Gradle构建JavaWeb项目

版本信息
  • spring 4.4.13
  • mybatis 3.4.1

One Step!

根据所需,导入相应jar包,添加依赖。
    //spring 系列包 4.4.13
    // spring mvc
    compile group: 'org.springframework', name: 'spring-webmvc', version: '4.3.13.RELEASE'
    // spring 核心包
    compile group: 'org.springframework', name: 'spring-core', version: '4.3.13.RELEASE'
    // spring beans
    compile group: 'org.springframework', name: 'spring-beans', version: '4.3.13.RELEASE'
    // spring 上下文
    compile group: 'org.springframework', name: 'spring-context', version: '4.3.13.RELEASE'
    // spring web
    compile group: 'org.springframework', name: 'spring-web', version: '4.3.13.RELEASE'
    // spring orm
    compile group: 'org.springframework', name: 'spring-orm', version: '4.3.13.RELEASE'
    // spring测试包
    compile group: 'org.springframework', name: 'spring-test', version: '4.3.13.RELEASE'
    // 日志记录 1.7.25
    compile group: 'org.slf4j', name: 'slf4j-simple', version: '1.7.25'
    // 数据库连接 5.1.38
    compile group: 'mysql', name: 'mysql-connector-java', version: '5.1.38'
    // 数据库连接池 2.7.7
    compile group: 'com.zaxxer', name: 'HikariCP', version: '2.7.7'
    // spring与Mybatis整合 1.3.0
    compile group: 'org.mybatis', name: 'mybatis-spring', version: '1.3.0'
    // mybatis 3.4.1
    compile group: 'org.mybatis', name: 'mybatis', version: '3.4.1'

这里使用的连接池为HikariCP,没了解过的建议百度一下。

Two Step!

进行相关的基础配置

修改web.xml,如下图所示。

<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
    <!-- 防止中文参数乱码 放在前面 -->
    <filter>
        <filter-name>SetCharacterEncoding</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>
        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
            <!-- 强制进行转码 -->
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>SetCharacterEncoding</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <!-- spring 配置Listener-->
    <!-- needed for ContextLoaderListener -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:/spring/SpringApplicationContext.xml</param-value>
    </context-param>
    <!-- Bootstraps the root web application context before servlet initialization -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <!--配置springmvc前端控制器 DispatcherServlet-->
    <servlet>
        <servlet-name>springMVC</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <!--Sources标注的文件夹下需要新建一个spring文件夹-->
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring/SpringMVC.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
        <async-supported>true</async-supported>
    </servlet>
    <!-- Map all requests to the DispatcherServlet for handling -->
    <servlet-mapping>
        <servlet-name>springMVC</servlet-name>
        <url-pattern>/</url-pattern><!--映射根路径-->
    </servlet-mapping>
</web-app>

在Resources目录下创建SpirngApplicationContext.xml,SpringMVC.xmljdbc.propertieslogback.xml配置文件。

SpirngApplicationContext.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" xmlns:tx="http://www.springframework.org/schema/tx"      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 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">
    <!-- 扫描service包下所有使用注解的类型 -->
    <context:component-scan base-package="com.example.service" />
    <!-- 配置数据库相关参数properties的属性:${url} -->
    <context:property-placeholder location="classpath:/jdbc.properties"/>
    <!--配置连接池-->
    <!--2.数据池-->
    <bean id="dataSource" class="com.zaxxer.hikari.HikariDataSource"
          destroy-method="shutdown">
        <!--配置连接池属性-->
        <property name="driverClassName" value="${jdbc.driverClassName}"/>
        <property name="jdbcUrl" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
        <!-- 连接只读数据库时配置为true, 保证安全 -->
        <property name="readOnly" value="${jdbc.readOnly}" />
        <!-- 等待连接池分配连接的最大时长(毫秒),超过这个时长还没可用的连接则发生SQLException, 缺省:30秒 -->
        <property name="connectionTimeout" value="${jdbc.connectionTimeout}" />
        <!-- 一个连接idle状态的最大时长(毫秒),超时则被释放(retired),缺省:10分钟 -->
        <property name="idleTimeout" value="${jdbc.idleTimeout}" />
        <!-- 一个连接的生命时长(毫秒),超时而且没被使用则被释放(retired),缺省:30分钟,建议设置比数据库超时时长少30秒,参考MySQL
            wait_timeout参数(show variables like '%timeout%';) -->
        <property name="maxLifetime" value="${jdbc.maxLifetime}" />
        <!-- 连接池中允许的最大连接数。缺省值:10;推荐的公式:((core_count * 2) + effective_spindle_count) -->
        <property name="maximumPoolSize" value="${jdbc.maximumPoolSize}" />
        <property name="minimumIdle" value="${jdbc.minimumIdle}" />
</bean>
    <!-- 配置SqlSessionFactory对象 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 注入数据库连接池 -->
        <property name="dataSource" ref="dataSource" />
        <!-- 扫描bean包 使用别名 -->
        <property name="typeAliasesPackage" value="com.example.bean"/>
        <!-- 扫描sql配置文件:mapper需要的xml文件 -->
        <property name="mapperLocations" value="classpath:mapper/*.xml"/>
    </bean>
    <!-- 配置扫描Dao接口包,动态实现Dao接口,注入到spring容器中 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.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"/>
</beans>
SpringMVC.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns: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.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
    <!--  静态资源交给默认的Servlet-->
    <mvc:default-servlet-handler/>
    <!-- 开启SpringMVC注解模式 -->
    <mvc:annotation-driven/>
    <!-- 配置自动扫描的包 -->
    <context:component-scan base-package="com.example.controller"></context:component-scan>
    <!-- 配置视图解析器 如何把 handler 方法返回值解析为实际的物理视图 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/"></property>
        <property name="suffix" value=".html"></property>
    </bean>
    <!--
        静态资源的解析
        包括js,css,img等

    <mvc:resources mapping="swagger-ui.html" location="classpath:/META-INF/resources/" />
    <mvc:resources mapping="/webjars/**" location="classpath:/META-INF/resources/webjars/" />
    <mvc:resources mapping="/mdui/**" location="/WEB-INF/statics/mdui/"></mvc:resources>
-->
</beans>
jdbc.properties
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/demo?useUnicode=true&characterEncoding=utf-8&useSSL=false
jdbc.username=root
jdbc.password=123456
jdbc.readOnly=false
jdbc.connectionTimeout=30000
jdbc.idleTimeout=600000
jdbc.maxLifetime=1800000
jdbc.maximumPoolSize=60
jdbc.minimumIdle=10
logback.xml
<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="true">
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
        </encoder>
    </appender>
    <root level="debug">
        <appender-ref ref="STDOUT"/>
    </root>
</configuration>

添加完配置文件不要忘了Create new application context。
对于SpringMVC.xml也是如此。



到这里我们基本已经配置完成,所以剩下一步,我们只需要测试一下是否成功运行就可以了。

Three Step!

测试是否整合成功

运行Tomcat,没有出现404,说明我们成功了第一步
接下来,我测试一下是否能够根据id查找出数据库中的信息



页面并没有输出信息,结果出现了500错误。原因是缺少jar包。所以Gradle要添加以下依赖。

// 页面输出json数据所需jar包
    compile group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.9.0'
    compile group: 'com.fasterxml.jackson.core', name: 'jackson-core', version: '2.9.0'
    compile group: 'com.fasterxml.jackson.core', name: 'jackson-annotations', version: '2.9.0'

再次测试,成功运行输出内容。


此时我们的SSM框架基本整合成功!!

下一节!SSM项目添加swagger2支持

项目地址:https://github.com/isliqian/ssm
个人博客:www.imqian.top

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,830评论 5 468
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,992评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,875评论 0 331
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,837评论 1 271
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,734评论 5 360
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,091评论 1 277
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,550评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,217评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,368评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,298评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,350评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,027评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,623评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,706评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,940评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,349评论 2 346
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,936评论 2 341

推荐阅读更多精彩内容