原文鏈接 http://blog.csdn.net/qq184377902/article/details/51493642 結合自身情況加以修改搭建的框架,記錄以防備忘,方便日后學習參考。
Before building the project framework ...
項目環境
IntelliJ IDEA 2016.1.2、JDK 1.8.0_31、Apache-maven-3.5.0、Tomcat-9.0.0.M11
Maven項目搭建
自行百度 ..
Build project framework ...
- SSM框架即為Spring、Spring MVC、Mybatis。創建后的項目結構圖即為下圖。
- - spring-mybatis.xml:整合spring與mybatis,並實現spring基本功能。
- spring-mvc.xml:配置使用spring-mvc。
- jdbc.propertis:資源文件,用來保存數據庫相關信息。
- log4j.properties:配置日志文件。(配置文件及資源文件可先自行新建,后續修改)
1.項目pom.xml文件
<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.xiaonan.framework</groupId> <artifactId>maven-ssm-demo</artifactId> <packaging>war</packaging> <version>1.0-SNAPSHOT</version> <name>maven-ssm-demo Maven Webapp</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <!-- spring版本號 --> <spring.version>4.2.6.RELEASE</spring.version> <!-- mybatis版本號 --> <mybatis.version>3.4.0</mybatis.version> <!-- log4j日志文件管理包版本 --> <slf4j.version>1.7.7</slf4j.version> <log4j.version>1.2.17</log4j.version> <!--jackson版本號--> <jackson.version>2.7.1</jackson.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.3.0</version> </dependency> <dependency> <groupId>javax.mail</groupId> <artifactId>mail</artifactId> <version>1.4</version> </dependency> <!-- Oracle驅動包 --> <dependency> <groupId>com.oracle</groupId> <artifactId>ojdbc6</artifactId> <version>11.2.0.1.0</version> </dependency> <!-- dbcp,用來在applicationContext.xml中配置數據庫 --> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.2.2</version> </dependency> <!-- JSTL標簽類 --> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.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>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> </dependencies> <build> <finalName>maven-ssm-demo</finalName> </build> </project>
2.spring-mvc.xml
(第一句掃描注解,掃描出的注解對象都依賴注入到了Spring MVC容器中,這時不可再次掃描Service,不然事務不能用了,所以掃描時將Service除去,這時必須掃描Controller,不然服務會出404錯誤。)
<?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-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"> <!-- 自動掃描該包,使用SpringMVC認為包下用了@Controller注解的類是控制器,避免掃描@Service導致事務不能使用 --> <context:component-scan base-package = "com.xiaonan.project"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service"/> </context:component-scan> <!--避免IE執行AJAX時,返回JSON出現下載文件 --> <bean id = "mappingJacksonHttpMessageConverter" class = "org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> <property name = "supportedMediaTypes"> <list> <value>text/html;charset=UTF-8</value> </list> </property> </bean> <!-- 啟動SpringMVC的注解功能,完成請求和注解POJO的映射 --> <bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver"> <property name="order" value="1"/> <property name="defaultViews"> <list> <!-- JSON View --> <bean class="org.springframework.web.servlet.view.json.MappingJackson2JsonView"> </bean> </list> </property> </bean> <!-- 定義跳轉的文件的前后綴 ,視圖模式配置--> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!-- 自動給后面action的方法return的字符串加上前綴和后綴,變成一個 可用的url地址 --> <property name="prefix" value="/page/" /> <property name="suffix" value=".jsp" /> </bean> <!-- 添加后可以顯示welcome-file界面 --> <mvc:default-servlet-handler/> <!-- 啟動注解 --> <mvc:annotation-driven /> </beans>
3.spring-mybatis.xml
(第一句自動掃描是為了掃描包中的注解,然后進行依賴注入,這時所有掃描的注解對象都在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: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-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/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <!-- 自動掃描 --> <context:component-scan base-package="com.xiaonan.project"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> <!-- 引入數據庫配置文件 --> <bean id = "propertyConfigurer" class = "org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer"> <property name = "location" value="classpath:properties/jdbc.properties" /> </bean> <!-- 連接池 --> <bean id = "dataSource" class = "org.apache.commons.dbcp.BasicDataSource" destroy-method = "close"> <property name="driverClassName" value="${jdbc.driver}" /> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> <!-- 初始化連接大小 --> <property name="initialSize" value="${jdbc.initialSize}" /> <!-- 連接池最大數量 --> <property name="maxActive" value="${jdbc.maxActive}"/> <!-- 連接池最大空閑 --> <property name="maxIdle" value="${jdbc.maxIdle}" /> <!-- 連接池最小空閑 --> <property name="minIdle" value="${jdbc.minIdle}" /> <!-- 獲取連接最大等待時間 --> <property name="maxWait" value="${jdbc.maxWait}" /> </bean> <!-- 結合Spring和Mybatis --> <bean id = "sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <!-- 自動掃描mapping.xml文件 --> <property name = "mapperLocations" value="classpath:mapper/*Mapper.xml" /> </bean> <!-- DAO接口所在包名,Spring會自動查找其下的類 --> <bean class = "org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name = "basePackage" value="com.xiaonan.project.mapper" /> <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>
4.jdbc.properties
(設置好一些基本屬性,可以直接在spring-mybatis.xml中使用${屬性名}訪問)
## oracle 定義 jdbc.driver=oracle.jdbc.driver.OracleDriver jdbc.url=jdbc:oracle:thin:@127.0.0.1:1521:orcl jdbc.username=bms jdbc.password=bms #定義初始連接數 jdbc.initialSize=0 #定義最大連接數 jdbc.maxActive=100 #定義最大空閑 jdbc.maxIdle=20 #定義最小空閑 jdbc.minIdle=1 #定義最長等待時間 jdbc.maxWait=60000
5.log4j.properties
#定義LOG輸出級別 log4j.rootLogger=INFO,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
6.web.xml
(初始化加載spring-mybatis.xml文件。ContextLoaderListener監聽器的作用就是啟動Web容器時自動裝配ApplicationContext的配置信息。若無該語句,就無法依賴注入注解標注產生的對象)
<?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>Archetype Created Web Application</display-name> <!-- Spring和Mybatis的配置文件 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:application/spring-mybatis.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:application/spring-mvc.xml</param-value> </init-param> <!-- 容器在啟動時就加載這個servlet --> <load-on-startup>1</load-on-startup> <async-supported>true</async-supported> </servlet> <servlet-mapping> <servlet-name>SpringMVC</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!-- 設置默認首頁 --> <welcome-file-list> <welcome-file>/index.jsp</welcome-file> </welcome-file-list> </web-app>
Project code ...
TestController.java
- 最前方加上Controller注解。
- controller:控制文件,所有請求都是傳入到此文件夾中的類里。
- @Autowired @Qualifier("testService"):依賴注入Service服務對象,使用Qualifier注解是指定具體服務,不然會進行默認匹配。
- @ResponseBody:讓返回值為JSON,但是pojo對象必須實現了getter和setter方法,不然會出現轉換失敗的錯誤。
package com.xiaonan.project.controller; import com.xiaonan.project.model.Test; import com.xiaonan.project.service.TestService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; /** * 測試 */ @Controller @RequestMapping("/test") public class TestController { @Autowired @Qualifier("testService") private TestService testService; @RequestMapping(value = "/get", method = RequestMethod.GET) @ResponseBody public Test getTestById(@RequestParam("id") String id) { return testService.getById(Integer.parseInt(id)); } }
TestMapper.java
- 方法的名字就是xml文件中的id值。
package com.xiaonan.project.mapper; import com.xiaonan.project.model.Test; public interface TestMapper { Test selectByPrimaryKey(Integer id); }
Test.java package com.xiaonan.project.model; /** * 測試對象 */ public class Test { private Integer id; private Integer test1; private String test2; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Integer getTest1() { return test1; } public void setTest1(Integer test1) { this.test1 = test1; } public String getTest2() { return test2; } public void setTest2(String test2) { this.test2 = test2; } }
TestService.java package com.xiaonan.project.service; import com.xiaonan.project.model.Test; /** * 測試服務接口 */ public interface TestService { Test getById(int id); }
TestServiceImp.java
- Service注解,掃描后就可以依賴注入對象到Controller。
package com.xiaonan.project.service.impl; import com.xiaonan.project.mapper.TestMapper; import com.xiaonan.project.model.Test; import com.xiaonan.project.service.TestService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; /** * 測試服務 */ @Service("testService") public class TestServiceImp implements TestService { //@Autowired(required = false) @Autowired private TestMapper testMapper; public Test getById(int id) { return testMapper.selectByPrimaryKey(id); } }
TestMapper.xml
- mapping:mybatis的sql語句存儲的xml文件存儲在這里。
- mybatis的配置,更為具體的在mybatis官網中有詳細介紹,需要手動配置sql語句,增加了靈活性,但是切換數據庫就有一些麻煩。
<?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.xiaonan.project.mapper.TestMapper"> <resultMap id="BaseResultMap" type="com.xiaonan.project.model.Test"> <id column="id" property="id" jdbcType="INTEGER" /> <result column="test1" property="test1" jdbcType="INTEGER" /> <result column="test2" property="test2" jdbcType="VARCHAR" /> </resultMap> <sql id = "Base_Column_List"> id, test1, test2 </sql> <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer"> SELECT <include refid="Base_Column_List" /> FROM test WHERE id = #{id, jdbcType = INTEGER} </select> </mapper>
-
以上基本目錄就創建成功了,運行tomcat,以上配置中並沒有配置servlet-api.jar,需要手動依賴進本項目。
-
在數據庫中插入一條數據后,訪問http://localhost:8080/myproject/test/get?id=1,返回JSON。
- git源碼:https://github.com/ooxiaonanoo/maven-ssm-demo.git 親們可參考...