最優雅地整合 Spring & Spring MVC & MyBatis 搭建 Java 企業級應用(附源碼)
這裡使用 Maven
項目管理工具構建項目
初始化項目
- 打開 Intellij IDEA,點擊
Create New Project
- 選擇 Maven 構建項目
- 選擇 JDK 版本
選擇 maven-archetype-webapp
模板(Java Web
項目)
填寫項目在 Maven 倉庫中的坐標(在 Maven 倉庫中根據這個坐標才能找到該項目)
- 選擇 Maven 路徑
- 選擇 Maven 配置文件路徑
- 選擇 Maven 本地倉庫路徑
- 填寫項目名
- 選擇工作目錄
創建目錄
在 src
> main
目錄下分別新建 java
源碼目錄 和 resource
配置文件目錄
java
目錄下創建基本的源碼目錄結構
webapp
目錄下創建 static
目錄,用於存放靜態資源文件(css, js, img 等)
webapp
> WEB-INF
目錄下創建 views
目錄,用於存放視圖頁面(jsp, html 等)
pom.xml
完整的 pom.xml
配置如下
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.antoniopeng</groupId> <artifactId>ssm-example</artifactId> <version>1.0-SNAPSHOT</version> <packaging>war</packaging> <name>hello-ssm Maven Webapp</name> <!-- FIXME change it to the project's website --> <url>https://antoniopeng.com</url> <properties> <!-- 環境配置 --> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> <!-- 統一的依賴管理 --> <alibaba-druid.version>1.1.6</alibaba-druid.version> <apache-httpclient.version>4.5.5</apache-httpclient.version> <commons-email.version>1.5</commons-email.version> <commons-fileupload.version>1.3.2</commons-fileupload.version> <commons-lang3.version>3.5</commons-lang3.version> <hibernate-validator.version>5.3.4.Final</hibernate-validator.version> <jackson.version>2.9.5</jackson.version> <jstl.version>1.2</jstl.version> <junit.version>4.12</junit.version> <kaptcha.version>2.3</kaptcha.version> <log4j.version>1.2.17</log4j.version> <lombok.version>1.16.18</lombok.version> <mybaits-spring.version>1.3.1</mybaits-spring.version> <mybatis.version>3.2.8</mybatis.version> <mysql.version>5.1.46</mysql.version> <servlet-api.version>3.1.0</servlet-api.version> <slf4j.version>1.7.25</slf4j.version> <spring.version>4.3.17.RELEASE</spring.version> </properties> <dependencies> <!-- Test Begin --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>${junit.version}</version> </dependency> <!-- Test Begin --> <!-- Spring Begin --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</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-aspects</artifactId> <version>${spring.version}</version> </dependency> <!-- Spring End --> <!-- Servlet Begin --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>${servlet-api.version}</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>${jstl.version}</version> </dependency> <!-- Servlet End --> <!-- Log Begin --> <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> <dependency> <groupId>org.slf4j</groupId> <artifactId>jcl-over-slf4j</artifactId> <version>${slf4j.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>jul-to-slf4j</artifactId> <version>${slf4j.version}</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>${log4j.version}</version> </dependency> <!-- Log End --> <!-- Commons Begin --> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>${commons-lang3.version}</version> </dependency> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>${commons-fileupload.version}</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-email</artifactId> <version>${commons-email.version}</version> </dependency> <!-- Commons End --> <!-- Database Begin --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>${alibaba-druid.version}</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.version}</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${mybatis.version}</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>${mybaits-spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>${hibernate-validator.version}</version> </dependency> <!-- Database End --> <!-- Json Begin --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>${jackson.version}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>${jackson.version}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>${jackson.version}</version> </dependency> <!-- Json End --> <!-- Apache Http Begin --> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>${apache-httpclient.version}</version> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>fluent-hc</artifactId> <version>${apache-httpclient.version}</version> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpmime</artifactId> <version>${apache-httpclient.version}</version> </dependency> <!-- Apache Http End --> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>${lombok.version}</version> </dependency> </dependencies> <build> <pluginManagement> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-install-plugin</artifactId> <version>2.5.2</version> </plugin> </plugins> </pluginManagement> <plugins> <!-- Compiler 插件, 設定 JDK 版本 --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.7.0</version> <configuration> <source>${java.version}</source> <target>${java.version}</target> <encoding>${project.build.sourceEncoding}</encoding> <showWarnings>true</showWarnings> </configuration> </plugin> </plugins> <!-- 資源文件配置 --> <resources> <resource> <directory>src/main/java</directory> <excludes> <exclude>**/*.java</exclude> </excludes> </resource> <resource> <directory>src/main/resources</directory> </resource> </resources> </build> </project>
全局配置文件
resources
目錄下創建全局配置文件,供後續調用
# JDBC jdbc.driverClass=com.mysql.jdbc.Driver jdbc.connectionURL=jdbc:mysql://localhost:3306/ssm?useUnicode=true&characterEncoding=utf-8&useSSL=false jdbc.username=root jdbc.password=123456 # JDBC Pool jdbc.pool.init=1 jdbc.pool.minIdle=3 jdbc.pool.maxActive=20 # Web View Location web.view.prefix=/WEB-INF/views/ web.view.suffix=.jsp # Upload Size web.maxUploadSize=10485760
Spring 核心配置
resources
目錄下創建 spring-context.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"> <!-- 開啟 Spring 相關註解 --> <context:annotation-config /> <!-- 使用 Annotation 自動註冊 Bean, 並且隻掃描 @Controller --> <context:component-scan base-package="com.antoniopeng.hello.ssm"> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" /> </context:component-scan> <!-- 配置事務管理器 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean> <!-- 開啟事務註解驅動 --> <tx:annotation-driven transaction-manager="transactionManager"/> </beans>
整合 Spring MVC
創建 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: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"> <!-- 加載配置屬性文件 --> <context:property-placeholder ignore-unresolvable="true" location="classpath:ssm.properties"/> <!-- 使用 Annotation 自動註冊 Bean,隻掃描 @Controller --> <context:component-scan base-package="com.antoniopeng.hello.ssm.controller" use-default-filters="false"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> <!-- 默認的註解映射的支持 --> <mvc:annotation-driven /> <!-- 定義視圖文件解析 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="${web.view.prefix}"/> <property name="suffix" value="${web.view.suffix}"/> </bean> <!-- 靜態資源映射 --> <mvc:resources mapping="/static/**" location="/static/" cache-period="31536000"/> <!-- 攔截器配置 --> <mvc:interceptors> <!-- 攔截登錄 --> <mvc:interceptor> <mvc:mapping path="/**"/> <mvc:exclude-mapping path="/login" /> <mvc:exclude-mapping path="/static/**" /> <bean class="com.antoniopeng.hello.ssm.interceptor.LoginInterceptor" /> </mvc:interceptor> </mvc:interceptors> <!-- 上傳文件攔截,設置最大上傳文件大小 10M = 10*1024*1024(B) = 10485760 bytes --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="maxUploadSize" value="${web.maxUploadSize}"/> </bean> </beans>
MyBatis 配置
創建 mybatis-config.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <!-- 全局參數 --> <settings> <!-- 打印 SQL 語句 --> <setting name="logImpl" value="STDOUT_LOGGING" /> <!-- 使全局的映射器啟用或禁用緩存。 --> <setting name="cacheEnabled" value="false"/> <!-- 全局啟用或禁用延遲加載。當禁用時,所有關聯對象都會即時加載。 --> <setting name="lazyLoadingEnabled" value="true"/> <!-- 當啟用時,有延遲加載屬性的對象在被調用時將會完全加載任意屬性。否則,每種屬性將會按需要加載。 --> <setting name="aggressiveLazyLoading" value="true"/> <!-- 是否允許單條 SQL 返回多個數據集 (取決於驅動的兼容性) default:true --> <setting name="multipleResultSetsEnabled" value="true"/> <!-- 是否可以使用列的別名 (取決於驅動的兼容性) default:true --> <setting name="useColumnLabel" value="true"/> <!-- 允許 JDBC 生成主鍵。需要驅動器支持。如果設為瞭 true,這個設置將強制使用被生成的主鍵,有一些驅動器不兼容不過仍然可以執行。 default:false --> <setting name="useGeneratedKeys" value="false"/> <!-- 指定 MyBatis 如何自動映射 數據基表的列 NONE:不映射 PARTIAL:部分 FULL:全部 --> <setting name="autoMappingBehavior" value="PARTIAL"/> <!-- 這是默認的執行類型 (SIMPLE: 簡單; REUSE: 執行器可能重復使用prepared statements語句;BATCH: 執行器可以重復執行語句和批量更新) --> <setting name="defaultExecutorType" value="SIMPLE"/> <!-- 使用駝峰命名法轉換字段。 --> <setting name="mapUnderscoreToCamelCase" value="true"/> <!-- 設置本地緩存范圍 session:就會有數據的共享 statement:語句范圍 (這樣就不會有數據的共享 ) defalut:session --> <setting name="localCacheScope" value="SESSION"/> <!-- 設置 JDBC 類型為空時,某些驅動程序 要指定值, default:OTHER,插入空值時不需要指定類型 --> <setting name="jdbcTypeForNull" value="NULL"/> </settings> </configuration>
整合 Druid
resources
目錄下創建 spring-context-druid.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 加載配置屬性文件 --> <context:property-placeholder ignore-unresolvable="true" location="classpath:ssm.properties"/> <!-- 數據源配置, 使用 Druid 數據庫連接池 --> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <!-- 數據源驅動類可不寫,Druid默認會自動根據URL識別DriverClass --> <property name="driverClassName" value="${jdbc.driverClass}"/> <!-- 基本屬性 url、user、password --> <property name="url" value="${jdbc.connectionURL}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> <!-- 配置初始化大小、最小、最大 --> <property name="initialSize" value="${jdbc.pool.init}"/> <property name="minIdle" value="${jdbc.pool.minIdle}"/> <property name="maxActive" value="${jdbc.pool.maxActive}"/> <!-- 配置獲取連接等待超時的時間 --> <property name="maxWait" value="60000"/> <!-- 配置間隔多久才進行一次檢測,檢測需要關閉的空閑連接,單位是毫秒 --> <property name="timeBetweenEvictionRunsMillis" value="60000"/> <!-- 配置一個連接在池中最小生存的時間,單位是毫秒 --> <property name="minEvictableIdleTimeMillis" value="300000"/> <!-- 配置監控統計攔截的filters --> <property name="filters" value="stat"/> </bean> </beans>
整合 MyBatis
resources
目錄下創建 spring-context-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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <!-- 配置 SqlSession --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <!-- 用於配置對應實體類所在的包,多個 package 之間可以用 ',' 號分割 --> <property name="typeAliasesPackage" value="com.antoniopeng.hello.ssm.entity"/> <!-- 用於配置對象關系映射配置文件所在目錄 --> <property name="mapperLocations" value="classpath*:/mapper/**/*.xml"/> <property name="configLocation" value="classpath:/mybatis-config.xml"></property> </bean> <!-- 掃描 Mapper --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.antoniopeng.hello.ssm.dao" /> </bean> </beans>
日志配置
創建 log4j.properties
日志配置文件
log4j.rootLogger=error, stdout log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=[service] %d - %c -%-4r [%t] %-5p %c %x - %m%n log4j.logger.com.ibatis = debug log4j.logger.com.ibatis.common.jdbc.SimpleDataSource = debug log4j.logger.com.ibatis.common.jdbc.ScriptRunner = debug log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate = debug log4j.logger.java.sql.Connection = debug log4j.logger.java.sql.Statement = debug log4j.logger.java.sql.PreparedStatement = debug log4j.logger.java.sql.ResultSet =debug log4j.logger.com.pro.mapper =debug
web.xml
完整的 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>/login</welcome-file> </welcome-file-list> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-context*.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <filter> <filter-name>encodingFilter</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>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <servlet> <servlet-name>springServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-mvc.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>springServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
創建訪問視圖
在 webapp
> WEB-INF
> views
目錄下新建 index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Index</title> </head> <body> <h1> Hello SSM </h1> </body> </html>
在 controller
目錄下創建 IndexController
類
package com.antoniopeng.hello.ssm.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class IndexController { @RequestMapping(value = "/") public String index() { return "index"; } }
部署到 Tomcat 服務器
點擊 Intellij IDEA
右上方 Add Configuration..
添加 Tomcat 本地服務器配置
配置下載好的 Tomcat 服務器
Tomcat8 官網下載地址
設置訪問端口號,默認 8080
將項目添加到 Tomcat 服務器
最後運行項目,訪問 http://localhost:8080/ 即可。
源碼地址:https://github.com/antoniopeng/ssm-example.git
到此這篇關於最優雅地整合 Spring & Spring MVC & MyBatis 搭建 Java 企業級應用(附源碼)的文章就介紹到這瞭,更多相關 Spring Spring MVC MyBatis 搭建 Java 企業級應用內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!
推薦閱讀:
- 使用Spring掃描Mybatis的mapper接口的三種配置
- 詳解Spring容器的使用流程
- 通過IEAD+Maven快速搭建SSM項目的過程(Spring + Spring MVC + Mybatis)
- Spring概述和快速構建的方式
- 一文詳解Spring加載properties文件的方式