回顧
上一篇筆者用Spring MVC框架改造了web服務(wù)阅懦,在這一篇中將通過集成MyBatis框架使用MySQL存儲數(shù)據(jù),同時利用servlet原生的方法實現(xiàn)處理圖片上傳的功能掠河。
環(huán)境
- Spring MVC:5.1.5
- MyBatis:3.5.0
- MySQL:8.0.13
- Tomcat:9.0.16
- Maven:3.6.0
- Git:2.20
- 操作系統(tǒng):windows10
集成MyBatis
- pom.xml添加依賴的jar包,包括mybatis和mysql-connector-java
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.13</version>
</dependency>
- resources目錄下新建MyBatis配置文件mybatis-config.xml,具體參考官方文檔奏甫,同時修改數(shù)據(jù)庫配置
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/yourdbname"/>
注意driver用的是com.mysql.cj.jdbc.Driver
尖飞,而不是com.mysql.jdbc.Driver
症副,后者已經(jīng)過時了。
- 創(chuàng)建映射文件UserMapper.xml政基,同樣參考上面這個網(wǎng)址
- 自行創(chuàng)建數(shù)據(jù)庫和表結(jié)構(gòu)
- 考慮到MyBatis中兩個最重要的類
SqlSessionFactory
和SqlSession
有不同的scope贞铣,設(shè)計上將SqlSessionFactory
對象存在靜態(tài)變量中,在程序初始化階段創(chuàng)建沮明;而SqlSession
對象因為是method或者session scope辕坝,這里筆者將它與一個request請求綁定,在每次處理一個新的請求時調(diào)用openSession
方法獲得荐健。
運行測試
- 第一次運行時提示時區(qū)不正確
com.mysql.cj.exceptions.InvalidConnectionAttributeException: The server time zone value '?D1ú±ê×?ê±??' is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver (via the serverTimezone configuration property) to use a more specifc time zone value if you want to utilize time zone support.
在配置的url中增加參數(shù)serverTimezone=UTC
即可
<property name="url" value="jdbc:mysql://localhost:3306/yourdbname?serverTimezone=UTC"/>
- 通過MyBatis插入的數(shù)據(jù)并未真正插入到mysql中
筆者在openSession
時忘了將autoCommit
設(shè)置為true酱畅,同時代碼中也沒有手動調(diào)用commit
方法琳袄,因此數(shù)據(jù)并未真正插入。解決方法為調(diào)用openSession(true)
即可纺酸。
servlet原生方式處理文件
- 大致思路是調(diào)用
HttpServletRequest
的getParts
方法獲得Part
對象的集合窖逗。每個Part
對象對應(yīng)一個上傳的文件,通過調(diào)用它的getInputStream
方法可以獲得輸入流餐蔬,然后按照正常的字節(jié)流方法處理即可碎紊。
public void upload(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
req.setCharacterEncoding("utf-8");
Collection<Part> parts = req.getParts();
for (Part part : parts) {
InputStream in = part.getInputStream();
// your code here
}
}
- 運行時會提示由于沒有提供multi-part配置,無法處理parts用含。根據(jù)servlet規(guī)約矮慕,有兩種方式可以解決這個問題。一是給servlet增加
@MultipartConfig
注解啄骇,由于這里用的是現(xiàn)成的DispatcherServlet
痴鳄,因此這個方法并不可行;二是在部署描述符中為servlet配置<multipart-config></multipart-config>
總結(jié)
- Spring項目手動集成MyBatis主要通過
SqlSessionFactory
和SqlSession
實現(xiàn) - 瀏覽器上傳的文件可以通過
HttpServletRequest
的getParts
方法獲得