SpringMVC + Spring + Mybatis + Maven整合例項
一、說明:
目前工作中的開發框架主要是 spring ,使用的是 springMVC+ spring + spring JdbcTemplate ,最近學習了一下Mybatis、Maven這些內容,所以嘗試使用 springMVC + Spring + Mybatis + Maven來搭建一個簡單的demo ,功能很簡單,主要是對於一個表的CRUD。
專案結構圖:
二、環境搭建流程
① 、新建一個Maven工程,並改專案為WEB專案,創建出相應的專案結構。
步驟:New---》Project----》Maven Project
之後選擇Next:
選中 Create a simple project 選項,然後Next
然後點選Finish ,工程建立完成,結構如下:
然後,右鍵選中專案,開啟Properties選項
將圖中的Dynamic Web Module 選項去掉,點選OK儲存
然後再次選中專案開啟上述的選單,並且選中Dynamic Web Module 選項,對話框出現下圖的提示:
此時,點選下面的:Further configuration avaaliable選項 ,出現如下對話方塊
將web目錄改為src/main/webapp ,之後ok儲存,發現在專案的src/main.webapp下面多出了WEB-INF與META-INF檔案,同時還生成了web.xml 檔案,如下圖:
②、配置相關的配置檔案
1)、配置Maven的pom.xml檔案,引入整合所需要的jar包:
XML Code
<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.elgin |
注:我使用的是oschina的Maven倉庫,庫不匹配的時候可能部分jar包加不進來。
2)、配置 web.xml 檔案:
XML Code
<?xml version="1.0" encoding="utf-8"?><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"><!-- 宣告專案的初始化引數 ,這裡聲明瞭spring配置檔案的位置 --><context-param><param-name>contextConfigLocation</param-name><param-value>classpath:applicationContext*.xml</param-value></context-param><!-- 加入spring支援 --><listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener><!-- 加入springMVC支援 --><!-- springmvc 配置檔案預設載入路徑為:WEB-INF/[servlet-name]-servlet.xml [servlet-name]為下面配置中的servlet-name元素的值,此處為springmvc --><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:springmvc*.xml</param-value></init-param><!-- 1 代表容器初始化時載入servlet --><load-on-startup>1</load-on-startup></servlet><servlet-mapping><servlet-name>springmvc</servlet-name><url-pattern>/</url-pattern></servlet-mapping><!-- 專案編碼過濾器 --><filter><filter-name>encodingFileter</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>encodingFileter</filter-name><url-pattern>/*</url-pattern></filter-mapping><!-- log4j2 支援 --><context-param><param-name>log4jConfiguration</param-name><param-value>/WEB-INF/classes/log4j2.xml</param-value></context-param><listener><listener-class>org.apache.logging.log4j.web.Log4jServletContextListener</listener-class></listener><filter><filter-name>log4jFilter</filter-name><filter-class>org.apache.logging.log4j.web.Log4jServletFilter</filter-class></filter><filter-mapping><filter-name>log4jFilter</filter-name><url-pattern>/*</url-pattern></filter-mapping></web-app> |
3 )、配置spring的配置檔案applicationContext.xml
在原始碼包src/main/resources下新建xml配置檔案:applicationContext.xml,內容如下:
XML Code
<?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" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd 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-4.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd"> <!-- 匯入properties屬性檔案 --><context:property-placeholder location="classpath:properties/datasource.properties" /><!-- 配置資料來源 --><bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"><property name="username" value="${jdbc.username}"></property><property name="password" value="${jdbc.password}"></property><property name="url" value="${jdbc.url}"></property><property name="driverClassName" value="${jdbc.driver}"></property></bean><!-- 配置sqlSessionFactory--><bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"><property name="dataSource" ref="dataSource"></property><property name="configLocation" value="classpath:mybatis/mybatis-config.xml"></property><property name="mapperLocations" value="classpath:mapper/*.xml"></property></bean><!-- 自動掃描mapper檔案對應的介面類,將其中的介面自動建立成 MapperFactoryBean --><bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"><property name="basePackage" value="com.elgin.dao"></property></bean><!-- 配置事務管理器 --><bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"><property name="dataSource" ref="dataSource"></property></bean><!-- 事務的傳播屬性 --><tx:advice id="taansactionAdvice" transaction-manager="transactionManager"><tx:attributes><tx:method name="add*" propagation="REQUIRED" /><tx:method name="create*" propagation="REQUIRED" /><tx:method name="delete*" propagation="REQUIRED" /><tx:method name="remove*" propagation="REQUIRED" /><tx:method name="update*" propagation="REQUIRED" /><tx:method name="get*" read-only="true" /><tx:method name="find*" read-only="true" /><tx:method name="*" read-only="true" /></tx:attributes></tx:advice><!-- 參與事務的service --><aop:config><aop:pointcut expression="execution(* com.elgin.service.*.*(..))" id="servicePointCut" /><aop:advisor advice-ref="taansactionAdvice" pointcut-ref="servicePointCut" /></aop:config></beans> |
4)、配置springMVC的配置檔案:
在原始碼包src/main/resources下新建xml配置檔案:springmvc.xml,內容如下:
XML Code
<?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:p="http://www.springframework.org/schema/p" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd 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-4.1.xsd"> <!-- 配置spring註解掃描的包 --><context:component-scan base-package="com.elgin"></context:component-scan><!-- 開啟註解驅動 --><!-- 會自動註冊DefaultAnnotationHandlerMapping 與AnnotationMethodHandlerAdapter 這兩個bean, 所以就沒有機會再給DefaultAnnotationHandlerMapping注入interceptors屬性,無法指定攔截器。 可以通過人工配置上面的兩個Bean,不使用 <mvc:annotation-driven />,就可以 給interceptors屬性 注入攔截器了 --><mvc:annotation-driven></mvc:annotation-driven><!-- 靜態資源訪問,解決頁面無法訪問到js、img和css資料夾中的檔案的問題 --><mvc:resources location="/imgages/" mapping="/imgages/**"/><mvc:resources location="/js/" mapping="/js/**"/><mvc:resources location="/css/" mapping="/css/**"/><!-- 檢視解析器:InternalResourceViewResolver UrlBasedViewResolver 的子類,通常用於查詢 JSP(類 InternalResourceView)和 JSTL(類 JstlView,InternalResourceView 的子類)等檢視 --><bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"><property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property><property name="prefix" value="/WEB-INF/jsp"></property><property name="suffix" value=".jsp"></property></bean><!-- 檔案上傳限制 --><bean class="org.springframework.web.multipart.commons.CommonsMultipartResolver"><property name="defaultEncoding" value="UTF-8"></property><property name="maxUploadSize" value="5242880"></property><property name="maxInMemorySize" value="20480"></property></bean></beans> |
5)、配置mybatis的配置檔案:
在原始碼包src/main/resources下新建package:mybatis ,然後在mybatis包下新建mybatis的配置檔案:mybatis-config.xml, 內容如下:
XML Code<?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><!-- 類的別名 --><typeAliases><typeAlias type="com.elgin.entities.User" alias="User"/></typeAliases></configuration> |
6)、資料庫相關配置:
在原始碼包src/main/resourecs下新建package:properties ,然後在properties包下新建:datasource.properties ,內容如下:
jdbc.username=root jdbc.password=root jdbc.url=jdbc:mysql://localhost:3306/test jdbc.driver=com.mysql.jdbc.Driver |
7)、mybatis的dao介面對映檔案:
在原始碼包src/main/resourecs下新建package:mapper,然後在mapper包下新建:userMapper.xml,內容如下:
XML Code
<?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.elgin.dao.UserDao"><!-- 新增一條記錄 --><insert id="addUser" parameterType="User"> insert into t_user(username,password,email,phone)values(#{username},#{password},#{email},#{phone}) </insert><!-- 刪除一條記錄 --><delete id="deleteUser" parameterType="Integer"> delete from t_user where id = #{id} </delete><!-- 更新一條記錄的資料 --><update id="updateUser" parameterType="User"> update t_user set username=#{username},password=#{password},email=#{email},phone=#{phone} where id=#{id} </update><!-- 查詢單條記錄 --><select id="getUser" parameterType="Integer" resultType="User"> SELECT * FROM t_user WHERE id = #{id} </select><!-- 查詢多條記錄 --><select id="getUserList" resultType="User"> select * from t_user </select></mapper> |
8)、配置log4j2配置檔案:
在原始碼包src/main/resourecs下新建xml配置檔案:log4j2.xml ,內容如下:
XML Code<?xml version="1.0" encoding="utf-8"?><Configuration status="OFF"><Appenders><!-- 輸出到檔案 --><File name="file" fileName="d:/myapp.log" append="true"><PatternLayout pattern="%d %-5p %c - %m%n" /></File><!--輸出到控制檯配置--><Console name="Console"><PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss } %p %l %m%n" /></Console><!-- 日誌檔案定期整理處理 --><RollingFile name="RollingFile" fileName="logs/app.log" filePattern="d:/logs/$${date:yyyy-MM}/app-%d{MM-dd-yyyy}-%i.log.gz"><PatternLayout><Pattern>%d{yyyy-MM-dd HH:mm:ss } %p %l %m%n</Pattern></PatternLayout><Policies><TimeBasedTriggeringPolicy /><SizeBasedTriggeringPolicy size="20MB" /></Policies></RollingFile></Appenders><Loggers><Logger level="debug" name="com.elgin" additivity="false"><AppenderRef ref="Console" /><AppenderRef ref="file" /></Logger><Root level="warn"><AppenderRef ref="file" /><AppenderRef ref="RollingFile" /></Root></Loggers></Configuration> |
9)、開發dao,service,controller,實體entitis相關程式碼:
在原始碼包src/main/java中新建如下各個包:
實體類User:
Java Code
package com.elgin.entities; publicclass User { private Integer id; privateString username; privateString password; privateString email; privateString phone; public Integer getId() { return id; } publicvoid setId(Integer id) { this.id = id; } publicString getUsername() { return username; } publicvoid setUsername(String username) { this.username = username; } publicString getPassword() { return password; } publicvoid setPassword(String password) { this.password = password; } publicString getEmail() { return email; } publicvoid setEmail(String email) { this.email = email; } publicString getPhone() { return phone; } publicvoid setPhone(String phone) { this.phone = phone; } } |
dao介面類:UserDao
Java Code
package com.elgin.dao; import java.util.List; import com.elgin.entities.User; publicinterface UserDao { publicint addUser(User user); publicint deleteUser(Integer id); publicint updateUser(User user); public User getUser(Integer id); public List<User> getUserList(); } |
service介面類: UserService
Java Code
package com.elgin.service; import java.util.List; import com.elgin.entities.User; publicinterface UserService { publicint addUser(User user); publicint deleteUser(Integer id); publicint updateUser(User user); public User getUser(Integer id); public List<User> getUserList(); } |
service實現類: UserServiceImpl
Java Code