您好,登錄后才能下訂單哦!
這篇文章主要介紹如何使用Maven搭建SpringMVC+Spring+MyBatis框架,文中介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們一定要看完!
SSM(Spring+SpringMVC+Mybatis),目前較為主流的企業級架構方案。標準的MVC設計模式,將整個系統劃分為顯示層、Controller層、Service層、Dao層四層,使用SpringMVC負責請求的轉發和視圖管理,Spring實現業務對象管理, MyBatis作為數據對象持久化引擎。
一. 框架詳情
Spring是一個輕量級的Java開發框架,它是為了解決企業應用開發的復雜性而創建的。Spring的用途不僅限于服務器端的開發。從簡單性、可測試性和松耦合的角度而言,任何Java應用都可以從Spring中受益。 簡單來說,Spring是一個輕量級的控制反轉(IoC)和面向切面(AOP)的容器框架
SpringMVC屬于SpringFrameWork的后續產品,分離了控制器、模型對象、分派器以及處理程序對象的角色,這種分離讓它們更容易進行定制
MyBatis是一個基于Java的持久層框架。MyBatis提供的持久層框架包括SQL Maps和Data Access Objects(DAO)它消除了幾乎所有的JDBC代碼和參數的手工設置以及結果集的檢索。MyBatis 使用簡單的 XML或注解用于配置和原始映射,將接口和 Java映射成數據庫中的記錄
二. 創建Maven項目
1、Eclipse中用Maven創建項目
2、按默認Next
3、找到maven-archetype-webapp后,點擊next
4、填寫相應的信息,GroupID是項目組織唯一的標識符,實際對應JAVA的包的結構。ArtifactID就是項目的唯一的標識符,實際對應項目的名稱,就是項目根目錄的名稱。Package填了默認給你建一個包,不寫也可以。
5、剛建好的目錄如下
6、Maven規定必須添加以下Source Folder:
src/main/resources
src/main/java
src/test/resources
src/test/java
在這步之前最好先項目上右鍵選擇properties,然后點擊java build path,在Librarys下,編輯JRE System Library,選擇workspace default jre。
7、分別修改輸出路徑為,對應關系如下:
8、將項目轉換成Dynamic Web Project,在項目上右鍵Properties,在左側選擇 Project Facets。
9、設置部署時的文件發布路徑,刪除test的兩項,因為test是測試使用,并不需要部署。
設置將Maven的jar包發布到lib下。Add -> Java Build Path Entries -> Maven Dependencies -> Finish
三. Maven引入需要的JAR包
<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/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.yingjun.test</groupId> <artifactId>TradingState</artifactId> <packaging>war</packaging> <version>2.0.1</version> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.build.timestamp.format>yyyyMMddHHmmss</maven.build.timestamp.format> <spring.version>3.2.9.RELEASE</spring.version> <mybatis.version>3.1.1</mybatis.version> <mybatisspring.version>1.1.1</mybatisspring.version> </properties> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</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-test</artifactId> <version>${spring.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>${mybatisspring.version}</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.34</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> <dependency> <groupId>c3p0</groupId> <artifactId>c3p0</artifactId> <version>0.9.1.2</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.8.1</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>3.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.2</version> <scope>provided</scope> </dependency> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.1</version> </dependency> <dependency> <groupId>commons-lang</groupId> <artifactId>commons-lang</artifactId> <version>2.6</version> </dependency> <dependency> <groupId>commons-codec</groupId> <artifactId>commons-codec</artifactId> <version>1.9</version> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.10</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.7.10</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.1.41</version> </dependency> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-asl</artifactId> <version>1.9.13</version> </dependency> </dependencies> <build> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>2.3.2</version> <configuration> <source>1.7</source> <target>1.7</target> </configuration> </plugin> <plugin> <artifactId>maven-war-plugin</artifactId> <version>2.2</version> <configuration> <version>3.0</version> <failOnMissingWebXml>false</failOnMissingWebXml> </configuration> </plugin> </plugins> <finalName>${project.artifactId}_${project.version}_${maven.build.timestamp}</finalName> </build> </project>
四. 相關配置文件配置,整合SSM框架
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/j2ee" xmlns:web="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" version="2.4"> <!-- 配置 Spring --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 防止Spring內存溢出監聽器 --> <listener> <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class> </listener> <!-- 配置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:spring-mvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springMVC</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!-- 字符集過濾器 --> <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> </web-app>
spring.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:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd "> <!-- 掃描service、dao組件 --> <context:component-scan base-package="com.yingjun.test" /> <!-- 分解配置 jdbc.properites --> <context:property-placeholder location="classpath:jdbc.properties" /> <!-- 數據源c3p0 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="${jdbc.driverClassName}" /> <property name="jdbcUrl" value="${jdbc.url}" /> <property name="user" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> <property name="maxPoolSize" value="${c3p0.pool.size.max}" /> <property name="minPoolSize" value="${c3p0.pool.size.min}" /> <property name="initialPoolSize" value="${c3p0.pool.size.ini}" /> <property name="acquireIncrement" value="${c3p0.pool.size.increment}" /> </bean> <!-- sessionFactory 將spring和mybatis整合 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="configLocation" value="classpath:spring-mybatis.xml" /> <property name="mapperLocations" value="classpath*:com/yingjun/test/mapping/**/*.xml" /> </bean> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com,yingjun.test.dao" /> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" /> </bean> <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="datagrid*" propagation="SUPPORTS" /> <tx:method name="*" propagation="SUPPORTS" /> </tx:attributes> </tx:advice> <aop:config> <aop:pointcut id="transactionPointcut" expression="execution(* com.yingjun.test.service..*Impl.*(..))" /> <aop:advisor pointcut-ref="transactionPointcut" advice-ref="transactionAdvice" /> </aop:config> </beans>
為了代替手工使用 SqlSessionDaoSupport 或 SqlSessionTemplate 編寫數據訪問對象 (DAO)的代碼,MyBatis-Spring 提供了一個動態代理的實現:MapperFactoryBean。這個類 可以讓你直接注入數據映射器接口到你的 service 層 bean 中。當使用映射器時,你僅僅如調 用你的 DAO 一樣調用它們就可以了,但是你不需要編寫任何 DAO 實現的代碼,因為 MyBatis-Spring 將會為你創建代理。
spring-mybatis.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> <!-- 暫時不需要其他配置--> </configuration>
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.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"> <!-- 默認的注解映射的支持 --> <mvc:annotation-driven /> <!-- 自動掃描該包,使SpringMVC認為包下用了@controller注解的類是控制器 --> <context:component-scan base-package="com.yingjun.test.controller" /> <!--避免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> <!-- 定義跳轉的文件的前后綴 ,視圖模式配置 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!-- 這里的配置我的理解是自動給后面action的方法return的字符串加上前綴和后綴,變成一個 可用的url地址 --> <property name="prefix" value="/WEB-INF/jsp/" /> <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>
log4j.properties
jdbc.driverClassName=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://192.168.1.194:3306/test?useUnicode=true&characterEncoding=UTF-8 jdbc.username=root jdbc.password=root c3p0.pool.size.max=20 c3p0.pool.size.min=5 c3p0.pool.size.ini=3 c3p0.pool.size.increment=2
jdbc.properties
log4j.rootLogger=info, console, debug, app, error ###Console ### 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 = %d %p[%C:%L]- %m%n ### debug ### log4j.appender.debug = org.apache.log4j.DailyRollingFileAppender log4j.appender.debug.File = log/debug.log log4j.appender.debug.Append = true log4j.appender.debug.Threshold = DEBUG log4j.appender.debug.DatePattern='.'yyyy-MM-dd log4j.appender.debug.layout = org.apache.log4j.PatternLayout log4j.appender.debug.layout.ConversionPattern = %d %p[%c:%L] - %m%n ### app ### log4j.appender.app = org.apache.log4j.DailyRollingFileAppender log4j.appender.app.File = log/app.log log4j.appender.app.Append = true log4j.appender.app.Threshold = INFO log4j.appender.app.DatePattern='.'yyyy-MM-dd log4j.appender.app.layout = org.apache.log4j.PatternLayout log4j.appender.app.layout.ConversionPattern = %d %p[%c:%L] - %m%n ### Error ### log4j.appender.error = org.apache.log4j.DailyRollingFileAppender log4j.appender.error.File = log/error.log log4j.appender.error.Append = true log4j.appender.error.Threshold = ERROR log4j.appender.error.DatePattern='.'yyyy-MM-dd log4j.appender.error.layout = org.apache.log4j.PatternLayout log4j.appender.error.layout.ConversionPattern =%d %p[%c:%L] - %m%n
五. 利用MyBatis Generator自動創建實體類、映射文件以及DAO接口
MyBatis屬于一種半自動的ORM框架,所以主要的工作就是配置Mapping映射文件,但是由于手寫映射文件很容易出錯,所以可利用MyBatis生成器自動生成實體類、DAO接口和Mapping映射文件。這樣可以省去很多的功夫,將生成的代碼copy到項目工程中即可。
生成代碼需要的文件和jar并建立如下目錄結構:
在generatorl.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="mysql-connector-java-5.1.34.jar" /> <context id="DB2Tables" targetRuntime="MyBatis3"> <commentGenerator> <property name="suppressDate" value="true" /> <!-- 是否去除自動生成的注釋 true:是 : false:否 --> <property name="suppressAllComments" value="true" /> </commentGenerator> <!--數據庫鏈接URL,用戶名、密碼 --> <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://192.168.1.194:3306/noc" userId="root" password="root"> </jdbcConnection> <javaTypeResolver> <property name="forceBigDecimals" value="false" /> </javaTypeResolver> <!-- 生成模型的包名和位置 --> <javaModelGenerator targetPackage="com.yingjun.test.model" targetProject="src"> <property name="enableSubPackages" value="true" /> <property name="trimStrings" value="true" /> </javaModelGenerator> <!-- 生成映射文件的包名和位置 --> <sqlMapGenerator targetPackage="com.yingjun.test.mapping" targetProject="src"> <property name="enableSubPackages" value="true" /> </sqlMapGenerator> <!-- 生成DAO的包名和位置 --> <javaClientGenerator type="XMLMAPPER" targetPackage="com.yingjun.test.dao" targetProject="src"> <property name="enableSubPackages" value="true" /> </javaClientGenerator> <!-- 要生成的表 tableName是數據庫中的表名或視圖名 domainObjectName是實體類名 --> <table tableName="other_list" domainObjectName="OtherList" enableCountByExample="fasle" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false" > </table> </context> </generatorConfiguration>
打開CMD窗口 進入該目錄結構,輸入命令行:
java -jar mybatis-generator-core-1.3.2.jar -configfile generator.xml -overwrite
運行完成后會生成相應的dao mapper 和model,是不是很爽。
六. 建立Service層以及conrorller層
package com.yingjun.test.service; public interface OtherServiceI { public String getOterList(); }
package com.yingjun.test.service; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.serializer.SerializerFeature; import com.yingjun.test.dao.OtherListMapper; import com.yingjun.test.model.OtherList; import com.yingjun.test.model.OtherListDomain; @Service public class OtherServiceImpl implements OtherServiceI { @Autowired private OtherListMapper otherListMapper; @Override public String getOterList() { Set<String> set=new HashSet<String>(); List<OtherList> list=otherListMapper.selectAll(); List<OtherListDomain> jsonList=new ArrayList<OtherListDomain>(); for(OtherList other:list){ String title=other.getTitle(); if(set.contains(title)){ continue; }else{ List<OtherList> t_list=new ArrayList<OtherList>(); for(OtherList data:list){ if(title.equals(data.getTitle())){ t_list.add(data); } } OtherListDomain domain=new OtherListDomain(); domain.setTitle(title); domain.setItems(t_list); jsonList.add(domain); set.add(other.getTitle()); } } return JSON.toJSONString(jsonList, SerializerFeature.WriteMapNullValue); } }
package com.yingjun.test.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.alibaba.fastjson.JSON; import com.yingjun.test.service.OtherServiceI; import com.yingjun.test.service.StockStatusServiceI; @Controller @RequestMapping(value = "/") public class TSSController { @Autowired private OtherServiceI otherService; @RequestMapping(value="/getOtherList",produces="text/html;charset=UTF-8" ) @ResponseBody private String getOtherList(){ String json=otherService.getOterList(); return json; } }
七. 建立測試類
import java.util.List; import org.apache.log4j.LogManager; import org.apache.log4j.Logger; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = {"classpath:spring.xml"}) public class TestMybatis { @Autowired private OtherServiceI service; @Test public void test() { String list=service.getOterList(); logger.info(list); } }
八. 通過瀏覽器進行驗證
http://localhost:8080/TzyjStateService/getOtherList
以上是“如何使用Maven搭建SpringMVC+Spring+MyBatis框架”這篇文章的所有內容,感謝各位的閱讀!希望分享的內容對大家有幫助,更多相關知識,歡迎關注億速云行業資訊頻道!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。