文章目錄
- 資料庫準備
- 1. dao層Spring整合MyBatis進行資料庫訪問(export_dao子工程)
- 1.1 需要spring和mybatis的整合包(前面已經匯入了)
- 1.2 export_dao下創建屬性檔案(連接資料庫c3p0連接池)
- 1.3 export_dao子工程下創建applicationContext-dao.xml
- 1.4 測驗能否自動裝載,能否查詢到資料庫
- 2. service依賴dao,測驗讀取dao的資訊,配置事務管理(export_system_service子工程)
- 2.1 關于classpath路徑讀取的使用
- 2.2 創建測驗類`TestCompanyService`
- 2.3 創建Service介面及其實作類
- 2.4 在export_system_service子工程創建spring事務管理
- 2.5 測驗運行
- 如果出現例外情況,參考下面幾種情況
- 3. Spring整合SpringMVC(export_web_manager子工程)
- 3.1 創建log4j.properties日志屬性檔案
- 3.2 web.xml配置
- 3.3 配置springmvc.xml
- 3.4 創建CompanyController進行測驗
- 3.5 創建company-list.jsp來測驗資料顯示
- 3.5 配置tomcat服務器通過地址訪問controller
- 3.6 SpringMVC對于日期字串向后臺提交轉Date問題
- 3.7 配置自定義日期型別轉換器實作Converter介面
- 3.8 在springmvc.xml中配置轉換工廠,并將轉換器放入注解驅動中,并測驗轉換情況
資料庫準備

需要sql檔案的可以點擊這個:
Saas-Export資料庫sql檔案
1. dao層Spring整合MyBatis進行資料庫訪問(export_dao子工程)
1.1 需要spring和mybatis的整合包(前面已經匯入了)
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>${mybatis.spring.version}</version>
</dependency>
需要匯入c3p0的依賴檔案
<!--c3p0資料庫連接池-->
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
1.2 export_dao下創建屬性檔案(連接資料庫c3p0連接池)
resources/properties/c3p0.properties
# key=value
#c3p0連接池屬性檔案
# 四大基本資訊
c3p0.driverClass=com.mysql.jdbc.Driver
c3p0.jdbcUrl=jdbc:mysql://localhost:3306/saas-export?useUnicode=true&characterEncoding=UTF-8&useSSL=false
c3p0.user=root
c3p0.password=861221293
# 初始化連接數 取值要在minPoolSize和maxPoolSize之間(可包含,閉區間) 默認值:3
c3p0.initialPoolSize=10
# 最大連接數 (連接池中的連接數不能超過maxPoolSize最大連接數) 默認值:15
c3p0.maxPoolSize=50
#最小連接數 默認值:3
c3p0.minPoolSize=5
#c3p0連接池中資料連接不夠時(無空閑連接可用),一次增長的個數(增長不能超過maxPoolSize最大連接個數) 默認值:3
c3p0.acquireIncrement=5
#連接的最大空閑時間,如果超過這個時間還沒有被使用,就斷開這個連接(設定為0或負數,就永遠都不會被斷開) 單位:秒 默認值 :0
c3p0.maxIdleTime=600
#從資料庫獲取新連接失敗后重復嘗試的次數,小于等于0表示無限次 默認值: 30
c3p0.acquireRetryAttempts=30
#兩次連接的中間間隔時間(重新嘗試的時間間隔) 單位:毫秒 默認值:1000
c3p0.acquireRetryDelay=1000
#連接關閉時,是否將所有未提交的操作進行事務回滾 默認值:false
c3p0.autoCommitOnClose = false
#當連接池用完時,客戶端呼叫getConnection()后等待獲取新連接的時間 單位:毫秒 默認值:0 (無限期等待) 按照設定的值,超時將拋出SQLException例外
c3p0.checkoutTimeout = 0
#每隔多少秒檢查所有連接池中的空閑連接 單位:秒 默認值:0
c3p0.idleConnectionTestPeriod=60
#配置PreparedStatement快取,設定連接池為資料源快取的PreparedStatement的總數,為0的時候不快取,同時maxStatementsPerConnection的配置無效,
# 由于PreparedStatement屬于單個Connection,所以這個數量應該根據應用中平均連接數乘以每個連接的平均PreparedStatement來計算
c3p0.maxStatements=1000
# 連接池為資料源單個Connection快取的PreparedStatement數,這個配置比maxStatements更有意義,因為它快取的服務物件是單個資料連接,如果設定的好,肯定是可以提高性能的,為0的時候不快取,
# c3p0.maxStatementsPerConnection
1.3 export_dao子工程下創建applicationContext-dao.xml
export_dao子工程交給spring來管理,創建一個對應的applicationContext-dao.xml
路徑:resources/spring/applicationContext-dao.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">
<!-- dao子工程交給Spirng來管理,創建一個對應的applicationContext-dao.xml -->
<!-- 引入c3p0的屬性檔案(里面是連接資料庫四大資訊鍵值對),在配置中通過占位使用 -->
<context:property-placeholder location="classpath:properties/c3p0.properties" />
<!-- 連接資料庫的四大基本資訊-->
<!-- 資料庫連接池c3p0 -->
<!-- 用c3p0資料源配置連接池,里面有連接池 ComboPooledDataSource資料庫連接池 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<!-- 連接池4大組件 -->
<property name="driverClass" value="${c3p0.driverClass}"/>
<property name="jdbcUrl" value="${c3p0.jdbcUrl}"/>
<property name="user" value="${c3p0.user}"/>
<property name="password" value="${c3p0.password}"/>
<!--初始化連接數 取值要在minPoolSize和maxPoolSize之間(可包含,閉區間) 默認值:3 -->
<property name="initialPoolSize" value="${c3p0.initialPoolSize}"/>
<!-- 最大連接數 (連接池中的連接數不能超過maxPoolSize最大連接數) 默認值:15-->
<property name="maxPoolSize" value="${c3p0.maxPoolSize}"/>
<!--最小連接數 默認值:3 -->
<property name="minPoolSize" value="${c3p0.minPoolSize}"/>
<!-- c3p0連接池中資料連接不夠時(無空閑連接可用),一次增長的個數(增長不能超過maxPoolSize最大連接個數) 默認值:3 -->
<property name="acquireIncrement" value="${c3p0.acquireIncrement}"/>
<!-- 連接的最大空閑時間,如果超過這個時間還沒有被使用,就斷開這個連接(設定為0或負數,就永遠都不會被斷開) 單位:秒 默認值 :0 -->
<property name="maxIdleTime" value="${c3p0.maxIdleTime}"/>
<!-- 從資料庫獲取新連接失敗后重復嘗試的次數,小于等于0表示無限次 默認值: 30-->
<property name="acquireRetryAttempts" value="${c3p0.acquireRetryAttempts}"/>
<!-- 兩次連接的中間間隔時間(重新嘗試的時間間隔) 單位:毫秒 默認值:1000 -->
<property name="acquireRetryDelay" value="${c3p0.acquireRetryDelay}"/>
<!-- 連接關閉時,是否將所有未提交的操作進行事務回滾 默認值:false -->
<property name="autoCommitOnClose" value="${c3p0.autoCommitOnClose}"/>
<!-- 當連接池用完時,客戶端呼叫getConnection()后等待獲取新連接的時間 單位:毫秒 默認值:0
如果值設為 0,將無限期等待,直到有空閑連接, 否則按照設定的值,超時將拋出SQLException例外
時間設定過小時會出現連接超時,這樣會拋出SQLException例外,設定時間時需要小心,按照實際情況設定適當的值-->
<property name="checkoutTimeout" value="${c3p0.checkoutTimeout}"/>
<!-- 每隔多少秒檢查所有連接池中的空閑連接 單位:秒 默認值:0 -->
<property name="idleConnectionTestPeriod" value="${c3p0.idleConnectionTestPeriod}"/>
<!-- 配置PreparedStatement快取,設定連接池為資料源快取的PreparedStatement的總數
為0的時候不快取,同時maxStatementsPerConnection的配置無效,
由于PreparedStatement屬于單個Connection,所以這個數量應該根據應用中平均連接數乘以每個連接的平均PreparedStatement來計算-->
<property name="maxStatements" value="${c3p0.maxStatements}"/>
</bean>
<!-- 獲取sqlSessionFactory-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!--配置資料源-->
<property name="dataSource" ref="dataSource"/>
<!-- 給整個包下的所有檔案起別名,就是類名的首字母小寫 com.xgf.domain.Person 簡化成 person-->
<property name="typeAliasesPackage" value="com.xgf.domain"/>
</bean>
<!-- 配置映射檔案掃描器 : IPersonDao.xml和IPersonDao.java-->
<bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 掃描dao介面和映射xml編譯后的類路徑 -->
<property name="basePackage" value="com.xgf.dao"/>
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
</bean>
</beans>
1.4 測驗能否自動裝載,能否查詢到資料庫
jaca》》com/xgf/dao/company/ICompanyDao
@Repository
public interface ICompanyDao {
//查詢所有的公司記錄
//select * from ss_company
List<Company> findAll();
}
resources》》com/xgf/dao/company/ICompanyDao.xml
<mapper namespace="com.xgf.dao.company.ICompanyDao">
<!-- 資料庫表欄位名(列名)與類的成員變數不一致的解決辦法
1. sql陳述句通過 as取別名,與類的成員變數一致
2. 使用mybatis的resultMap映射實作(column表的列名,property類的屬性名映射
-->
<resultMap id="companyMap" type="company">
<id column="id" property="id"/>
<result column="expiration_date" property="expirationDate"/>
<result column="license_id" property="licenseId"/>
<result column="company_size" property="companySize"/>
</resultMap>
<select id="findAll" resultMap="companyMap">
select
*
from ss_company
</select>
</mapper>
test》》com/xgf/dao/company/ICompanyDaoTest
//通過Spring自帶的junit測驗 - 兩個注解
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:spring/applicationContext-dao.xml")
public class TestCompanyDao {
//通過@Autowrie從spring中獲取dao的實作類物件
@Autowired
ICompanyDao companyDao;//自動裝載,就相當于ICompanyDao iCompanyDao = new iCompanyDao()
@Test
public void test01(){
//測驗自動裝載能否實作
System.out.println("companyDao物件:" + companyDao);
List<Company> companyList = companyDao.findAll();
System.out.println(companyList);
}
}
測驗結果:(自動裝載成功,查詢資料庫成功)

2. service依賴dao,測驗讀取dao的資訊,配置事務管理(export_system_service子工程)
子工程export_system_service依賴子工程export_domain,
2.1 關于classpath路徑讀取的使用
@ContextConfiguration("classpath*:spring/applicationContext-*.xml")
classpath:加載當前maven工程的resources目錄下的組態檔
classpath*::加載當前maven工程及其依賴工程的resources目錄下的組態檔
applicationContext-.xml*:讀取所有符合規則的檔案(比如前面的applicationContext-dao.xml檔案)
2.2 創建測驗類TestCompanyService
》test/com/xgf/service/company/TestCompanyService
//Spring的單元測驗
//@ContextConfiguration("classpath*:spring/applicationContext-*.xml")
// 加載當前maven工程及其依賴工程的resources目錄下的組態檔,讀取所有符合規則的檔案(tx和dao)
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath*:spring/applicationContext-*.xml")
public class TestCompanyService {
@Autowired
ICompanyService companyService;
@Test
public void test01(){
//1:撰寫了業務邏輯的測驗
//ICompanyService companyService = new CompanyServiceImpl();
List<Company> list = companyService.findAll();
System.out.println(list);
}
}
2.3 創建Service介面及其實作類
》test/com/xgf/service/company/ICompanyService
public interface ICompanyService {
public List<Company> findAll();
}
》test/com/xgf/service/impl/CompanyServiceImpl
@Service //注解 @Service,該類交由Spring管理創建
public class CompanyServiceImpl implements ICompanyService {
@Autowired
ICompanyDao companyDao;
public List<Company> findAll() {
//service要呼叫dao查詢資料,所以要注入
return companyDao.findAll();
}
}
2.4 在export_system_service子工程創建spring事務管理
》resources/spring/applicationContext-tx.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:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
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/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!-- Service子工程,進行事務管理,交給Spring事務管理,applicationContext-tx.xml -->
<!-- 掃描Service實作類@Service注解 -->
<context:component-scan base-package="com.xgf.service"/>
<!--配置Spring框架的 宣告式事務管理(底層是AOP):三個步驟 -->
<!--1. 配置事務管理器 DataSourceTransactionManager是spring給我們的管理事務的物件,
這個物件要用到連接池,用完需要將連接放回連接池
管理事務:DataSource.Connection.commit() rollback()方法-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<!-- 2. 配置事務通知 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<!--配置事務細節特征-->
<tx:attributes>
<!--查詢方法,使用默認的隔離級別 及 SUPPORTS傳播行為-->
<tx:method name="find*" isolation="DEFAULT" propagation="SUPPORTS"/>
<tx:method name="query*" isolation="DEFAULT" propagation="SUPPORTS"/>
<tx:method name="select*" isolation="DEFAULT" propagation="SUPPORTS"/>
<tx:method name="get*" isolation="DEFAULT" propagation="SUPPORTS"/>
<!--增刪改方法,使用默認的隔離級別 及 REQUIRED傳播行為-->
<tx:method name="*" isolation="DEFAULT" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
<!-- 3. 配置事務切面: 切面=通知+切入點 -->
<aop:config>
<!-- expression運算式的值,按照你的路徑配置
* com.xgf.service.impl.*ServiceImpl.*(..))
第一個* 是回傳值通配符
然后是包的路徑,*ServiceImpl表示配置的所有滿足類名+ServiceImpl后綴的且在com.xgf.service.*.impl目錄下的
*(..) : *表示所有方法 (..)表示匹配所有引數
-->
<!--配置切入點-->
<aop:pointcut id="pt" expression="execution(* com.xgf.service.*.impl.*ServiceImpl.*(..))"/>
<!-- 切面 = 通知+切入點 -->
<aop:advisor advice-ref="txAdvice" pointcut-ref="pt"/>
</aop:config>
</beans>
2.5 測驗運行

如果出現例外情況,參考下面幾種情況
- 如果出現applicationContext例外
可能是加載組態檔錯誤,因為我們要加載當前service子工程的
spring/applicationContext-tx.xml事務管理也要加載service所依賴的dao子工程的
spring/applicationContext-dao.xml模塊,所以用下面這種方式加載,
@ContextConfiguration("classpath*:spring/applicationContext-*.xml")
- 如果出現UTF-8例外,可能是父工程的pom.xml沒有配置UTF-8
去父工程,加上這個:
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
- 如果出現自己寫的類找不到例外
需要在每個工程的pom.xml寫packaging的打包方式
<!-- 父工程 export_parent 設定packaging為pom -->
<packaging>pom</packaging>
<!-- 非web子工程(export_domain、export_dao、export_system_service)設定packaging為jar -->
<packaging>jar</packaging>
<!-- web子工程 export_web_manager 設定packaging為war(因為tomcat只能運行war包) -->
<packaging>war</packaging>
3. Spring整合SpringMVC(export_web_manager子工程)
3.1 創建log4j.properties日志屬性檔案
直接創建在子工程的resources下
# 將debug等級(可修改)的日志資訊輸出到CONSOLE和LOGFILE這兩個目的地(多個按,逗號隔開)
# CONSOLE和LOGFILE定義在下面的代碼,【可以任意起名,可以有多個,不一定只是兩個】
# 等級:OFF、FATAL、ERROR、WARN、INFO、DEBUG、ALL
# 比如(配置OFF全部都不顯示,配置為INFO這樣只顯示INFO、WARN、ERROR的log資訊,而DEBUG資訊不會被顯示)
log4j.rootCategory=debug, CONSOLE, LOGFILE
# Set the enterprise logger category to FATAL and its only appender to CONSOLE.
log4j.logger.org.apache.axis.enterprise=FATAL, CONSOLE
# =======================================================================================
# CONSOLE配置(名稱可以自定義) - 這里配置控制臺輸出日志
# log4j.appender.CONSOLE --> 定義名為CONSOLE的輸出端是哪種型別,有五個值
# org.apache.log4j.ConsoleAppender(控制臺)
# org.apache.log4j.FileAppender(檔案)
# org.apache.log4j.DailyRollingFileAppender(每天產生一個日志檔案)
# org.apache.log4j.RollingFileAppender(檔案大小到達指定尺寸的時候產生一個新的檔案)
# org.apache.log4j.WriterAppender(將日志資訊以流格式發送到任意指定的地方)
# 這里CONSOLE輸出端是控制臺
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
# log4j.appender.CONSOLE.layout --> 定義名為CONSOLE的輸出端的layout布局方式是哪種型別,有四個值
# org.apache.log4j.PatternLayout(可以靈活地指定布局模式)【***】
# org.apache.log4j.HTMLLayout(以HTML表格形式布局)
#org.apache.log4j.SimpleLayout(包含日志資訊的級別和資訊字串)
#org.apache.log4j.TTCCLayout(包含日志產生的時間、執行緒、類別等等資訊)
# 這里設定為PatternLayout,可以靈活指定布局的模式
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
# log4j.appender.CONSOLE.layout.ConversionPattern
# 使用PatternLayout布局需要指定列印資訊的具體格式ConversionPattern,引數:
# %d 輸出日志時間,默認格式為ISO8601,也可以在其后指定格式,如:%d{yyyy-MM-dd HH:mm:ss,SSS},輸出類似:2020-10-16 17:02:28,968
# %r 輸出自應用啟動到輸出該log資訊耗費的毫秒數
# %t 輸出產生該日志事件的執行緒名(比如main、gc)
# %p 輸出優先級,即DEBUG,INFO,WARN,ERROR,FATAL等方式
# %c 輸出所屬的類目,通常就是所在類的全名;
# %m 輸出代碼中指定的訊息
# %M 輸出列印該條日志的方法名
# %n 輸出一個回車換行符,Windows平臺為"rn”,Unix平臺為"n”;
# %l 輸出日志事件的發生位置,及在代碼中的行數;
# [QC]是log資訊的開頭,可以為任意字符,一般為專案簡稱,
log4j.appender.CONSOLE.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} %-6r [%t] %-5p %30.30c - %m%n
# 輸出訊息編碼
#log4j.appender.CONSOLE.encoding=UTF-8
# =======================================================================================
# LOGFILE配置 (名稱可以自定義) 這里配置日志檔案存盤(存盤到指定路徑)
# log4j.appender.LOGFILE 用于定義名為LOGFILE的輸出端的型別為每天產生一個日志檔案,
log4j.appender.LOGFILE=org.apache.log4j.FileAppender
# log4j.appender.LOGFILE.File 定義名為LOGFILE的輸出端的檔案名為E:\logFile\SSM\ssm.log(可以自行修改)
log4j.appender.LOGFILE.File=E:\\logFile\\saas-export\\saas-export.log
log4j.appender.LOGFILE.Append=true
# log4j.appender.LOGFILE.layout 輸出日志布局設定PatternLayout,和上面的一樣
log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout
# log4j.appender.LOGFILE.layout.ConversionPattern 自定義格式輸出,和上面一樣
log4j.appender.LOGFILE.layout.ConversionPattern=%d{ISO8601} %-6r [t] %-5p %30.30c %x - %m%n
3.2 web.xml配置
加載spring核心組態檔applicationContext-*.xml,配置字符編碼過濾器,配置監聽器,配置前端控制器進行請求分發
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
<!--這些配置是有順序的 context-param引數,后面是filter過濾器,然后是listener監聽器,然后是servlet前端控制器 -->
<!--1. spring監聽器: 讀取applicationContext.xml組態檔
設定spring核心組態檔的路徑 applicationContext-tx.xml和applicationContext-dao.xml-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:spring/applicationContext-*.xml</param-value>
</context-param>
<!-- 2. 配置字符編碼過濾器characterEncodingFilter 解決中文亂碼(統一編碼) -->
<filter>
<filter-name>characterEncodingFilter</filter-name>
<!-- spring自帶編碼過濾器 -->
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<!-- 讀取鍵值對 key-取名 value-設定的編碼 -->
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<!-- /*攔截所有請求,都要被過濾器過濾 -->
<url-pattern>/*</url-pattern>
</filter-mapping>
<!--3. 配置Spring的監聽器,默認只加載WEB-INF目錄下的applicationContext.xml組態檔-->
<listener>
<!-- ContextLoaderListener監聽器的作用就是啟動Web容器時,自動裝配applicationContext的配置資訊 -->
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--4. 配置前端控制器,進行接收請求轉發至controller,解決Controller的問題(web層)-->
<servlet>
<!-- 前端控制器取名 可以更改,但是要和下面的一樣 -->
<servlet-name>DispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--加載springmvc.xml組態檔-->
<init-param>
<!-- 整合SpringMVC,需要加載springmvc核心組態檔 -->
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/springmvc.xml</param-value>
</init-param>
<!--數字越大優先級越低, 數字為1,啟動服務器,立即創建該servlet -->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<!-- 要和上面的前端控制器命名相同 -->
<servlet-name>DispatcherServlet</servlet-name>
<!-- *.do 表示所有后綴為do的請求 -->
<url-pattern>*.do</url-pattern>
</servlet-mapping>
</web-app>
3.3 配置springmvc.xml
路徑:resources/spring/springmvc.xml,開啟注解驅動,配置過濾檔案,配置視圖決議器,掃描controller,
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
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/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!--springmvc是web層(Controller處理請求) UserController @Controller -->
<!--1.掃描Controller所在包-->
<context:component-scan base-package="com.xgf.web"/>
<!--2. 配置的視圖決議器物件,success 路徑/WEB-INF/pages/success.jsp -->
<bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/"/>
<property name="suffix" value=".jsp"/>
</bean>
<!--3. 組態檔 - 過濾靜態資源 前面的前端控制器攔截所有,靜態css、js這些也都攔截
配置使.js .css img這些靜態檔案不被攔截,保證靜態檔案都不攔截
用過mvc標簽進行放行,這些目錄下檔案都不攔截 -->
<mvc:resources location="/css/" mapping="/css/**" />
<mvc:resources location="/images/" mapping="/images/**" />
<mvc:resources location="/js/" mapping="/js/**" />
<mvc:resources location="/fonts/" mapping="/fonts/**" />
<!-- 4. 開啟注解驅動,開啟SpringMVC的注解的支持 @RequestMapping @RequestBody @ResponseBody這些注解需要使用 -->
<mvc:annotation-driven/>
</beans>
3.4 創建CompanyController進行測驗
com/xgf/web/controller/company/CompanyController.java
@Controller
@RequestMapping("/company")
public class CompanyController {
private static final Logger l = LoggerFactory.getLogger(CompanyController.class);
@Autowired
ICompanyService companyService;
//list.do -> list 前端控制器攔截后綴為.do的檔案
@RequestMapping(path="/list.do",method = RequestMethod.GET)
public String list(Model model){
List<Company> list = companyService.findAll();
//列印重要資料
l.info("list list="+list);
model.addAttribute("list",list);
return "company/company-list";
}
}
3.5 創建company-list.jsp來測驗資料顯示
WEB-INF/pages/company/company-list.jsp
@Controller
@RequestMapping("/company")
public class CompanyController {
private static final Logger l = LoggerFactory.getLogger(CompanyController.class);
@Autowired
ICompanyService companyService;
//list.do -> list 前端控制器攔截后綴為.do的檔案
@RequestMapping(path="/list.do",method = RequestMethod.GET)
public String list(Model model){
List<Company> list = companyService.findAll();
//列印重要資料
l.info("list list="+list);
model.addAttribute("list",list);
return "company/company-list";
}
}
3.5 配置tomcat服務器通過地址訪問controller

3.6 SpringMVC對于日期字串向后臺提交轉Date問題
springMVC默認不支持頁面上的日期字串(類似2020-10-14或2020/10/14之類的)到后臺的Date的轉換,(會報400錯誤)
jsp頁面設定一個接收date資料的input,
<% pageContext.setAttribute("path",request.getContextPath()); %>
<form action="${path}/testDate.do" method="get">
請選擇日期:<input type="date" name="date">
<br/>
<input type="submit" value="提交"/>
</form>
后臺controller接收資料進行跳轉
@RequestMapping(path="/testDate.do",method = RequestMethod.GET)
//該引數接收瀏覽器提交的日期字符
public String testDate(Date date, Model model){
System.out.println("testDate date="+date);
model.addAttribute("date",date);
return "stringToDateConverter";
}
運行結果400錯誤

3.7 配置自定義日期型別轉換器實作Converter介面
export_web_manager/com/xgf/web/controller/TestStringToDateConverter
import org.springframework.core.convert.converter.Converter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/*自定義型別引數轉換器: 將字串日期格式轉成Date型別的資料.
Converter<S,T> S: 代表的是源,將要轉換的資料型別 T:目標型別,將會轉成什么資料型別
*/
//日期格式轉換器
public class DateFormatConverter implements Converter<String,Date>{
//轉換方法
//String source 將會傳遞過來的日期的字串
public Date convert(String source) {
//引數填寫為你想要轉換的資料格式
? SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
? try {
? Date date = sdf.parse(source);
? return date;
? } catch (ParseException e) {
? e.printStackTrace();
? }
? return null;
}
3.8 在springmvc.xml中配置轉換工廠,并將轉換器放入注解驅動中,并測驗轉換情況
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
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/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!--springmvc是web層(Controller處理請求) UserController @Controller -->
<!--1.掃描Controller所在包-->
<context:component-scan base-package="com.xgf.web"/>
<!--2. 配置的視圖決議器物件,success 路徑/WEB-INF/pages/success.jsp -->
<bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/"/>
<property name="suffix" value=".jsp"/>
</bean>
<!--3. 組態檔 - 過濾靜態資源 前面的前端控制器攔截所有,靜態css、js這些也都攔截
配置使.js .css img這些靜態檔案不被攔截,保證靜態檔案都不攔截
用過mvc標簽進行放行,這些目錄下檔案都不攔截 -->
<mvc:resources location="/css/" mapping="/css/**" />
<mvc:resources location="/images/" mapping="/images/**" />
<mvc:resources location="/js/" mapping="/js/**" />
<mvc:resources location="/fonts/" mapping="/fonts/**" />
<!-- 4. 開啟注解驅動,開啟SpringMVC的注解的支持 @RequestMapping @RequestBody @ResponseBody這些注解需要使用 -->
<mvc:annotation-driven/>
<!-- 5. 配置型別轉換器 -->
<!-- 創建型別轉換器物件 -->
<bean id="stringToDateConverter" class="com.xgf.web.converter.StringToDateConverter"/>
<!-- 把轉換器物件放入SpringMVC轉換器工廠中 -->
<bean id="conversionServiceFactory" class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters">
<set>
<!-- 引入日期轉換器物件(上面創建的) -->
<ref bean="stringToDateConverter"/>
<!-- 或者直接將轉換器類寫到這里面 -->
<!--<bean id="stringToDateConverter" class="com.xgf.web.converter.StringToDateConverter"/>-->
</set>
</property>
</bean>
<!--6. 把轉換器工廠放入到注解驅動,轉換器才會生效 -->
<mvc:annotation-driven conversion-service="conversionServiceFactory" />
</beans>
注意事項【】*
上述代碼中的<mvc:annotation-driven conversion-service=“conversionServiceFactory” />一定要放到springmvc的注解驅動mvc:annotation-driven/后面,不然就會報400錯誤,(你都沒有開啟注解驅動,怎么放進去呢?)
運行結果(轉換成功)

SSM環境搭建成功了
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/189914.html
標籤:其他
下一篇:java面向物件4-代碼塊
