項目整合數據庫使用Mysql,數據訪問框架採用mybatis3.4.5,繼承spring+spring mvc,版本4.3.12,前端採用freemarker2.3.23,項目日誌採用log4j1.2.17,並作一些經常使用配置。css
右鍵項目è點擊Propertieshtml
看看項目結構:前端
注意:content directory:建議填寫src/main/webappjava
由於利用Maven 的jetty插件運行項目時,這是默認路徑,不然須要自行配置,mysql
還有即是Maven打war包時,這也是默認路徑,不然也須要專門配置,比較麻煩^_^。web
建議將項目編碼改成utf-8spring
打開項目的pom.xml,添加如下代碼sql
<properties>數據庫 <!-- 文件拷貝時的編碼 -->express <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <!-- 編譯時的編碼 --> <maven.compiler.encoding>UTF-8</maven.compiler.encoding> </properties> |
右鍵項目è點擊Properties
打開pom.xml,添加如下代碼,版本能夠自行修改
<build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.1</version> <configuration> <source>1.7</source> <target>1.7</target> </configuration> </plugin> </plugins> </build> |
由於是web項目因此咱們須要打包爲war
打開pom.xml添加以下代碼
<packaging>war</packaging> |
也能夠不配置,配置了能夠mvn jetty:run直接運行項目,若是不配置須要打成war包放到web服務器中運行。
在pom.xml中添加以下代碼,固然jetty插件的版本,本身能夠自行配置
<build> <plugins> <!-- jetty運行插件 --> <plugin> <groupId>org.eclipse.jetty</groupId> <artifactId>jetty-maven-plugin</artifactId> <version>9.4.4.v20170414</version> <configuration> <scanIntervalSeconds>30</scanIntervalSeconds> </configuration> </plugin> </plugins> </build> |
既然是maven項目,添加依賴jar包就是往pom.xml添加依賴配置。
maven庫查詢網站http://mvnrepository.com/,能夠從裏面搜索依賴
在複製依賴的時候注意jar包的依賴關係
首先讓咱們看看sprng的架構圖,核心包必須導入
spring-beans,spring-core,spring-context,spring-expression
由於咱們搭建的是基於spring mvc的web程序,
因此咱們須要導入servlet模塊,即spring-mvc,由於spring-mvc依賴於spring-web,和spring-aop以及核心包。
由於一會要整合mybatis,還須要導入Transactions模塊,即spring-tx,爲了接管mybatis的事務,還有須要導入spring-jdbc(mybatis-spring須要的依賴,且配置事務也須要)。
json處理是web程序處理的屢見不鮮,spring-mvc還有一個可選的依賴jackson-databind用來處理json,這個jar包還有兩個必選依賴jackson-core和jackson-annotations。
若是項目採用jsp做爲頁面的話,就不須要導入了,不過咱們這裏採用freemarker做爲頁面處理類庫,因此咱們還要導入freemarker依賴,在整合freemarker時須要導入spring-context-support依賴。
è須要導入的依賴
spring-beans spring-core spring-context spring-expression spring-web spring-aop spring-tx spring-jdbc jackson-databind jackson-core jackson-annotations freemarker spring-context-support |
添加mybatis依賴,添加mybatis-spring依賴(整合spring使用),鏈接數據庫須要數據庫驅動,咱們這裏鏈接mysql,因此須要mysql-connector-java(mysql java版數據庫驅動包)依賴。咱們採用數據dbcp2數據源,因此咱們須要添加commons-dbcp2依賴,commons-dbcp2又有兩個必選依賴commons-pool2和commons-logging。
è須要導入的依賴
mybatis mybatis-spring mysql-connector-java commons-dbcp2 commons-pool2 commons-logging |
這裏採用log4j做爲日誌處理。
è須要導入的依賴
log4j |
<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.base</groupId> <artifactId>ssm</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <properties> <!-- 項目編碼設置 --> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <maven.compiler.encoding>UTF-8</maven.compiler.encoding> <!-- jar包版本配置 --> <spring.version>4.3.12.RELEASE</spring.version> <log4j.version>1.2.17</log4j.version> <jackson.version>2.8.10</jackson.version> <freemarker.version>2.3.23</freemarker.version> <commons-logging.version>1.2</commons-logging.version> <commons-dbcp2.version>2.1.1</commons-dbcp2.version> <commons-pool2.version>2.4.2</commons-pool2.version> <mybatis.version>3.4.5</mybatis.version> <spring-mybatis.version>1.3.1</spring-mybatis.version> <mysql-connector-java.version>6.0.6</mysql-connector-java.version> </properties> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.7</source> <target>1.7</target> </configuration> </plugin> <!-- jetty運行插件 --> <plugin> <groupId>org.eclipse.jetty</groupId> <artifactId>jetty-maven-plugin</artifactId> <version>9.4.4.v20170414</version> <configuration> <scanIntervalSeconds>30</scanIntervalSeconds> </configuration> </plugin> </plugins> </build> <dependencies> <!-- mybatis配置 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${mybatis.version}</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>${spring-mybatis.version}</version> </dependency> <!-- mysql數據庫鏈接驅動 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql-connector-java.version}</version> </dependency> <!-- spring相關包配置 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-expression</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-web</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-tx</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring.version}</version> </dependency>
<!-- jackson相關依賴,json處理 --> <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-core</artifactId> <version>${jackson.version}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>${jackson.version}</version> </dependency> <!-- freemarker頁面處理 --> <dependency> <groupId>org.freemarker</groupId> <artifactId>freemarker</artifactId> <version>${freemarker.version}</version> </dependency>
<!-- 數據源依賴jar配置 --> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-dbcp2</artifactId> <version>${commons-dbcp2.version}</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-pool2</artifactId> <version>${commons-pool2.version}</version> </dependency>
<dependency> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> <version>${commons-logging.version}</version> </dependency> <!-- log4j配置 --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>${log4j.version}</version> </dependency> </dependencies> </project> |
雖然寫了不少,但在這個教程裏項目採用方式一配置日誌。
在src/main/resources文件夾下創建log4j.properties,代碼以下,能夠根據需求自行配置
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 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 |
注意:log4j框架會自動去classpath路徑下加載log4j.properties文件,也就是說按照以上規則配置,會自動生效,固然採用這種方式配置每次更改配置後都須要重啓項目才能生效,且文件名不能更改,且不能放在classpath之外的路徑。
咱們還有一種配置方式,那即是在web.xml配置監聽的方式,這種方式改完配置後不須要每次都重啓項目且配置文件名能夠隨意,路徑隨意,只要配置好就能夠,固然這種方式也必須先配置好log4j.properties(能夠不叫log4j),代碼以下:
<context-param> <param-name>log4jConfigLocation</param-name> <param-value>classpath:log4j.properties</param-value> </context-param>
<context-param> <param-name>log4jRefreshInterval</param-name> <param-value>6000</param-value> </context-param>
<context-param> <param-name>webAppRootKey</param-name> <param-value>com.base.ssm</param-value> </context-param>
<listener> <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class> </listener> |
log4jConfigLocation: log4j配置文件路徑,既然能夠指定路徑固然名字能夠隨便起,路徑也自由選擇。
log4jRefreshInterval:爲6000表示 開一條watchdog線程每6秒掃描一下配置文件的變化
webAppRootKey:不配置默認是webapp.root,webAppRootKey爲web工程的根目錄在系統環境變量中的key ,若是web容器中有多個項目都沒有設置webAppRootKey或者重複,若是都向系統變量中去註冊,那麼就會報錯,即拋出異常。在配置log4j.properties時可使用${com.base.ssm}引用項目根目錄,例如:
log4j.appender.file.File=${ com.base.ssm }/WEB-INF/logs/sample.log |
在聲明一遍,咱們採用的是dbcp2數據源,固然也能夠不用它的^_^。
首先讓咱們在src/main/resources文件夾下建立jdbc.properties,內容以下
#數據庫驅動類 driver=com.mysql.jdbc.Driver #鏈接url url=jdbc:mysql://127.0.0.1:3306/mydb?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&autoReconnect=true&serverTimezone=UTC #用戶名 username=root #密碼 password=root #鏈接池最大空閒 maxIdle=4 #鏈接池最小空閒 minIdle=2 #最大活動數 maxTotal=4 |
注意:配置文件在建立數據源的時候使用關於dbcp2數據源的具體配置,請自行百度^_^, url serverTimezone參數若是不指定容易拋出異常
com.mysql.cj.core.exceptions.InvalidConnectionAttributeException: The server time zone value '��� |
還要說明的一點是,使用6.0.6 版本的mysql驅動,控制檯報這麼一句話,是說明咱們用的驅動類是過期的,且數據庫驅動會自動註冊,不須要手動配置,也就是說配置datasource時不須要配置驅動類了。
Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary. |
在src/main/resources文件夾下新建mybatisConfig.xml配置文件,mybatis和spring整合後,mybatisConfig.xml文件的做用就小了不少,可是仍是有些用的嗎,好比能夠爲實體類起別名,方便訪問,例如
<typeAliases> <typeAlias type="com.base.domain.Test" alias="Test" /> </typeAliases> |
完整代碼以下,具體配置根據須要自行添加:
<?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>
</typeAliases> <mappers>
</mappers> </configuration> |
在src/main/resources文件夾下建立spring-dao.xml(名字隨便起)。
<!-- 加載properties配置文件 --> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location" value="classpath:jdbc.properties"></property> </bean> |
<!-- 配置數據源 --> <bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="${driver}" /> <property name="url" value="${url}" /> <property name="username" value="${username}" /> <property name="password" value="${password}" /> <!-- 鏈接池最大空閒 --> <property name="maxIdle" value="${maxIdle}"/> <!-- 鏈接池最小空閒 --> <property name="minIdle" value="${minIdle}"/> <!-- 最大活動數 --> <property name="maxTotal" value="${maxTotal}"/> </bean> |
<!-- 配置session工廠 --> <bean id="sqlSessionBean" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"></property> <property name="configLocation" value="classpath:mybatisConfig.xml"></property> </bean> |
首先在src/main/java下新建包com.base.dao
<!-- 根據dao接口和mapper文件代理生成實例供spring注入使用 --> <bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!-- 自動掃描生成的包 --> <property name="basePackage" value="com.base.dao"></property> <!-- session工廠 --> <property name="sqlSessionFactoryBeanName" value="sqlSessionBean"></property> </bean> |
什麼是事務?摘抄自網上(csdn shu_lin博客)
在編寫業務的過程當中,會須要進行事務處理,當須要執行多條插入語句時,若是前幾條成功,而最後一條失敗,那麼咱們須要回滾數據庫操做,保持數據的一致性和完整性,此時,就須要利用DB的事務處理。事務是恢復和併發控制的基本單位。 |
如下兩種方式能夠同時配置,項目中能夠同時使用^_^,若是想了解具體請看文檔或找度娘。
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean> <!-- 開啓事務控制的註解支持 --> <tx:annotation-driven transaction-manager="transactionManager"/> |
在代碼中可使用@Transactional註解到方法上使用事務,注意@Transactional只能被應用到public方法上,對於其它非public的方法,若是標記了@Transactional也不會報錯,但方法沒有事務功能。
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean> <bean id="transactionTemplate" class="org.springframework.transaction.support.TransactionTemplate"> <property name="transactionManager"> <ref bean="transactionManager"/> </property> </bean> |
使用事務模板須要首先在代碼中加入事務模板的注入
@Autowired private TransactionTemplate transactionTemplate; |
使用:
//返回值根據需求本身調整 int result = (int)transactionTemplate .execute(new TransactionCallback() { @Override public Object doInTransaction(TransactionStatus status) { //要執行的代碼 return 1; } }); |
<?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:mybatis-spring="http://mybatis.org/schema/mybatis-spring" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring-1.2.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.3.xsd">
<!-- 加載properties配置文件 --> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location" value="classpath:jdbc.properties"></property> </bean> <!-- 配置數據源 --> <bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource"> <property name="driverClassName" value="${driver}" /> <property name="url" value="${url}" /> <property name="username" value="${username}" /> <property name="password" value="${password}" /> <!-- 鏈接池最大空閒 --> <property name="maxIdle" value="${maxIdle}" /> <!-- 鏈接池最小空閒 --> <property name="minIdle" value="${minIdle}" /> <!-- 最大活動數 --> <property name="maxTotal" value="${maxTotal}" /> </bean> <!-- 配置session工廠 --> <bean id="sqlSessionBean" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"></property> <property name="configLocation" value="classpath:mybatisConfig.xml"></property> </bean> <!-- 根據dao接口和mapper文件代理生成實例供spring注入使用 --> <bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.base.dao"></property> <!-- 若是隻有一個sqlSession --> <property name="sqlSessionFactoryBeanName" value="sqlSessionBean"></property> </bean> <!—事務管理器--> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <!-- 開啓事務控制的註解支持 --> <tx:annotation-driven transaction-manager="transactionManager" /> <!-- 事務模板 --> <bean id="transactionTemplate" class="org.springframework.transaction.support.TransactionTemplate"> <property name="transactionManager"> <ref bean="transactionManager" /> </property> </bean>
</beans> |
在src/main/java下新建包com.base.service,用來存儲業務代碼
在src/main/resources下新建spring-service.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-4.3.xsd"> <!-- 自動掃描生成bean --> <context:component-scan base-package="com.base.service"/> <!-- 隱式地向 Spring容器註冊AutowiredAnnotationBeanPostProcessor、RequiredAnnotationBeanPostProcessor、CommonAnnotationBeanPostProcessor以及PersistenceAnnotationBeanPostProcessor這4個BeanPostProcessor 聲明後就能夠在代碼中使用@Resource、@PostConstruct、@PreDestroy、@Autowired、@PersistenceContext等註解 --> <context:annotation-config/> </beans> |
在src/main/java下新建包com.base.web.controller,用來存放控制器
在src/main/webapp/WEB-INF新建views文件夾,用來存放視圖文件
在src/main/webapp/WEB-INF下新建spring-mvc.xml文件
<!-- 啓用Mvc註解@controller等 --> <mvc:annotation-driven> <!--避免IE執行AJAX時,返回JSON出現下載文件 --> <mvc:message-converters> <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>text/html;charset=UTF-8</value> </list> </property> </bean> </mvc:message-converters> </mvc:annotation-driven> |
<!-- 自動掃描controller --> <context:component-scan base-package="com.base.web.controller"/> |
<!-- 配置freeMarker的模板路徑 --> <bean class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer"> <property name="templateLoaderPath" value="/WEB-INF/views/" /> <property name="defaultEncoding" value="UTF-8" /> </bean> <!-- 配置基本的視圖解析器,解析freemarker ftl--> <bean id="viewResolver" class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver"> <property name="cache" value="true" /> <property name="prefix" value="" /> <property name="suffix" value=".ftl" /> <property name="contentType" value="text/html;charset=UTF-8" /> <property name="exposeSpringMacroHelpers" value="true" /> <property name="exposeRequestAttributes" value="true" /> <property name="exposeSessionAttributes" value="true" /> </bean> |
<!-- 配置靜態資源 --> <mvc:resources location="/static/js/" mapping="/js/**"/> <mvc:resources location="/static/css/" mapping="/css/**"/> |
<?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" xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.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.3.xsd"> <!-- 自動掃描controller --> <context:component-scan base-package="com.base.web.controller"/> <!-- 配置靜態資源 --> <mvc:resources location="/static/js/" mapping="/js/**"/> <mvc:resources location="/static/css/" mapping="/css/**"/> <!-- 配置freeMarker的模板路徑 --> <bean class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer"> <property name="templateLoaderPath" value="/WEB-INF/views/" /> <property name="defaultEncoding" value="UTF-8" /> </bean> <!-- 配置基本的視圖解析器,解析freemarker ftl--> <bean id="viewResolver" class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver"> <property name="cache" value="true" /> <property name="prefix" value="" /> <property name="suffix" value=".ftl" /> <property name="contentType" value="text/html;charset=UTF-8" /> <property name="exposeSpringMacroHelpers" value="true" /> <property name="exposeRequestAttributes" value="true" /> <property name="exposeSessionAttributes" value="true" /> </bean> <!-- 啓用Mvc註解@controller等 --> <mvc:annotation-driven> <!--避免IE執行AJAX時,返回JSON出現下載文件 --> <mvc:message-converters> <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>text/html;charset=UTF-8</value> </list> </property> </bean> </mvc:message-converters> </mvc:annotation-driven> </beans> |
<?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>ssm</display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> </welcome-file-list> <!-- 配置spring的配置文件 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value> classpath:spring-dao.xml, classpath:spring-service.xml </param-value> </context-param> <!-- 配置spring監聽 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 配置DispatcherServlet --> <servlet> <servlet-name>appServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/spring-mvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>appServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!-- 設置編碼過濾器 --> <filter> <filter-name>characterFilter</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> </filter> <filter-mapping> <filter-name>characterFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app> |
-- MySQL Script generated by MySQL Workbench -- Wed Nov 8 17:14:18 2017 -- Model: New Model Version: 1.0 -- MySQL Workbench Forward Engineering
SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0; SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0; SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='TRADITIONAL,ALLOW_INVALID_DATES';
-- ----------------------------------------------------- -- Schema mydb -- ----------------------------------------------------- DROP SCHEMA IF EXISTS `mydb` ;
-- --s--------------------------------------------------- -- Schema mydb -- ----------------------------------------------------- CREATE SCHEMA IF NOT EXISTS `mydb` DEFAULT CHARACTER SET utf8 ; USE `mydb` ;
-- ----------------------------------------------------- -- Table `mydb`.`test` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `mydb`.`test` ( `test_id` VARCHAR(64) NOT NULL, `test_content` TEXT NULL, PRIMARY KEY (`test_id`)) ENGINE = InnoDB;
SET SQL_MODE=@OLD_SQL_MODE; SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS; SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS; |
INSERT INTO `test` VALUES ('1','ssm框架整合!'); |
在src/main/java下建立com.base.domain包,在包中建立Test類,代碼以下
package com.base.domain;
import java.io.Serializable;
/** * @author xuzhen * */ public class Test implements Serializable{
private static final long serialVersionUID = -227124296105328094L; private String testId; private String testContent; public Test() {} public String getTestId() { return testId; } public void setTestId(String testId) { this.testId = testId; } public String getTestContent() { return testContent; } public void setTestContent(String testContent) { this.testContent = testContent; }
} |
在com.base.dao包下建立TestMapper.接口,代碼以下:
package com.base.dao;
import java.util.List;
import com.base.domain.Test;
public interface TestMapper { List<Test> getTests(); } |
在src/main/resources/mapper文件夾下建立TestMapper.xml,配置以下:
<?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.base.dao.TestMapper"> <resultMap type="com.base.domain.Test" id="TESTMAP"> <id column="test_id" property="testId"/> <result column="test_content" property="testContent"/> </resultMap>
<select id="getTests" resultMap="TESTMAP"> select * from test </select> </mapper> |
在mappers標籤內添加
<mapper resource="mapper/TestMapper.xml"/> |
在com.base.service包下建立TestManager接口
建立com.base.service.impl包,在包中建立TestManager的實現類TestManagerImpl,代碼以下
TestManager.java
package com.base.service;
import java.util.List;
import com.base.domain.Test;
public interface TestManager { List<Test> list(); } |
TestManagerImpl.java
package com.base.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service;
import com.base.dao.TestMapper; import com.base.domain.Test; import com.base.service.TestManager; @Service public class TestManagerImpl implements TestManager { @Autowired private TestMapper testMapper; @Override public List<Test> list() { // TODO Auto-generated method stub return testMapper.getTests(); }
} |
在com.base.web.controller包中建立TestController類,代碼以下
package com.base.web.controller;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView;
import com.base.service.TestManager;
@Controller public class TestController { @Autowired private TestManager testManager; @RequestMapping("/") public ModelAndView index() { ModelAndView mav = new ModelAndView("index"); mav.addObject("tests", testManager.list()); return mav; } } |
在src/main/webapp/WEB-INF/views下新建index.ftl文件,代碼以下
<!DOCTYPE HTML> <html> <head> <meta charset="utf-8"/> <title>index</title> </head> <body> <h1>歡迎來到ssm框架整合!</h1> <#list tests as test> <p>${test.testId} ------ ${test.testContent}</p> </#list> </body> </html> |
右鍵項目,點擊Run As,而後點擊Maven Build,命令中輸入jetty:run
在瀏覽器上輸入localhost:8080(maven jetty插件默認端口8080),效果以下