JavaWeb文件上傳流程
JavaWeb文件上傳
本文我們學(xué)習(xí)JavaWeb中最重要的技術(shù)之一,文件上傳,該案例我會(huì)用一個(gè)小型的用戶管理系統(tǒng)實(shí)現(xiàn),一步步帶入,內(nèi)容通俗易懂,下面我們步入正題!
做一個(gè)簡(jiǎn)單的用戶管理系統(tǒng)
功能如下
用戶注冊(cè),參數(shù)有用戶名,用戶名密碼,用戶頭像,
用戶登錄,登錄成功后跳轉(zhuǎn)至主頁(yè)顯示用戶頭像和名稱,支持注銷賬號(hào),注銷賬號(hào)后,頁(yè)面跳轉(zhuǎn)至登錄頁(yè)
技術(shù)棧:后端采用JavaWeb、MySQL5.7、Druid連接池、前端采用bootstrap框架結(jié)合jsp
先上效果
完整操作項(xiàng)目演示:
包含:用戶注冊(cè),用戶登錄,用戶登錄后顯示用戶信息,即頭像,賬號(hào)名,最右側(cè)顯示注銷,點(diǎn)擊注銷后跳轉(zhuǎn)至登錄頁(yè)
項(xiàng)目結(jié)構(gòu)Java源碼
前端頁(yè)面jsp
數(shù)據(jù)表準(zhǔn)備
t_user_info
CREATE TABLE `t_user_info` ( `noid` int(11) NOT NULL AUTO_INCREMENT, `username` varchar(32) COLLATE utf8mb4_unicode_ci NOT NULL, `password` varchar(32) COLLATE utf8mb4_unicode_ci NOT NULL, `head_portrait_path` varchar(64) COLLATE utf8mb4_unicode_ci NOT NULL, PRIMARY KEY (`noid`) ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
Jar文件準(zhǔn)備
項(xiàng)目所需jar包如下:
jar文件放在WEB-INF/lib文件夾下,主要是為了安全。
文件上傳需要的jar包:
jar文件我會(huì)同步資源,小伙伴們不用擔(dān)心哦~
項(xiàng)目結(jié)構(gòu)簡(jiǎn)介
本項(xiàng)目采用三層架構(gòu)實(shí)現(xiàn),即:service層、dao層、servlet層
- servlet層:
由于之前的servlet層類增刪改查的類太過(guò)于多,導(dǎo)致代碼冗余,所以在jsp頁(yè)面發(fā)送請(qǐng)求時(shí),采用模塊化的方式進(jìn)行訪問(wèn),例如:
- http://localhost/Blog/user/addUser 訪問(wèn)user模塊的addUser
- http://localhost/Blog/user/getUserList 訪問(wèn)user模塊的getUserList
- http://localhost/Blog/dept/addDept 訪問(wèn)dept的addDept
- http://localhost/Blog/dept/getDeptList 訪問(wèn)dept的getDeptList
這樣一個(gè)對(duì)應(yīng)的類解決該類的所有對(duì)數(shù)據(jù)庫(kù)的增刪改查操作,提高了程序的可維護(hù)性,減少代碼的冗余,提高了程序的健壯性。
抽取出公共父類:BaseServletBaseServlet類核心代碼
public class BaseServlet extends HttpServlet{ @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //1.獲取瀏覽器請(qǐng)求的資源 String uri = req.getRequestURI(); //2.獲取請(qǐng)求的方法名,最后斜線后面的內(nèi)容 String methodName = uri.substring(uri.lastIndexOf("/")+1); try { //3.根據(jù)方法名獲取方法,通過(guò)反射獲取 Method method = this.getClass().getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class); //4.調(diào)用方法 method.invoke(this, req, resp); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
- dao層
dao層抽取出公共數(shù)據(jù)庫(kù)連接類,BaseDao,基于db.properties配置文件連接本地?cái)?shù)據(jù)庫(kù)
db.properties配置文件:
driverClassName=com.mysql.jdbc.Driver url=jdbc:mysql://127.0.0.1/db_blog?useSSL=true username=root password=111111
BaseDao核心代碼
public class BaseDao { //采用單例模式實(shí)現(xiàn),防止數(shù)據(jù)庫(kù)連接超時(shí) private static DataSource ds = null; public QueryRunner initQueryRunner() throws Exception { if (ds == null) { String dbFile = this.getClass().getClassLoader().getResource("/").getFile(); dbFile = dbFile.substring(1) + "db.properties"; FileReader fr = new FileReader(dbFile); Properties pro = new Properties(); pro.load(fr); ds = DruidDataSourceFactory.createDataSource(pro); } QueryRunner qur = new QueryRunner(ds); return qur; } }
Userservlet核心代碼
@WebServlet("/user/*") public class UserServlet extends BaseServlet{ //業(yè)務(wù)層類,用于調(diào)用業(yè)務(wù)層方法 UserService userService = new UserServiceImpl(); /** * 注冊(cè)用戶 * @param req * @param resp */ public void register(HttpServletRequest req, HttpServletResponse resp) { //獲取數(shù)據(jù) DiskFileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload fileUpload = new ServletFileUpload(factory); try { List<FileItem> fileItemList = fileUpload.parseRequest(req); //獲取當(dāng)前項(xiàng)目的路徑 String classesPath = this.getClass().getResource("/").getPath(); File f1 = new File(classesPath); //項(xiàng)目路徑 String projectPath = f1.getParentFile().getParentFile().getParentFile().getAbsolutePath(); //最后上傳的路徑 String uploadPath = projectPath + "\\ROOT\\upload\\"; File f2 = new File(uploadPath); if (!f2.exists()) { f2.mkdirs(); } //存入數(shù)據(jù)庫(kù)的路徑 String headPortraitPath = ""; for (FileItem fileItem : fileItemList) { if (!fileItem.isFormField()) { //是文件域 String fileName = fileItem.getName(); //獲取原來(lái)文件的后綴 String suffix = fileName.substring(fileName.lastIndexOf(".")); //生成新的文件名,為防止重復(fù),采用隨機(jī)數(shù) String destFileName = UUID.randomUUID().toString().replace("-", ""); //存入數(shù)據(jù)庫(kù)的路徑拼接完畢,例如格式:隨機(jī)文件名.txt headPortraitPath = destFileName + suffix; //寫(xiě)入硬盤(pán)的路徑 uploadPath += headPortraitPath; //獲取輸入流 InputStream is = fileItem.getInputStream(); //輸出流 FileOutputStream fos = new FileOutputStream(uploadPath); //將上傳的文件寫(xiě)入指定路徑 try { byte[] buf = new byte[10240]; while (true) { int realLen = is.read(buf, 0, buf.length); if (realLen < 0) { break; } fos.write(buf, 0, realLen); } } finally { if (fos != null) fos.close(); if (is != null) is.close(); } } else { //不是文件域,是普通控件 //獲取輸入框的名稱 String fieldName = fileItem.getFieldName(); //獲取輸入框中的值 String fieldVal = fileItem.getString("utf-8"); //加入請(qǐng)求域中 req.setAttribute(fieldName, fieldVal); } } String username = (String) req.getAttribute("username"); String password = (String) req.getAttribute("password"); //驗(yàn)證參數(shù)是否合法,不為空 boolean flag = userService.exam(username, password); if (flag) { //將數(shù)據(jù)存入數(shù)據(jù)庫(kù) User user = new User(); user.setUsername(username); user.setPassword(password); user.setHead_portrait_path(headPortraitPath); if (userService.save(user)) { resp.sendRedirect(req.getContextPath()+"/login.jsp"); } } else { resp.sendRedirect(req.getContextPath()+"/register.jsp"); } } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } /** * 用戶登錄 * @param req * @param resp */ public void login(HttpServletRequest req, HttpServletResponse resp) { //獲取數(shù)據(jù) String username = req.getParameter("username"); String password = req.getParameter("password"); //驗(yàn)證是否存在該用戶 User user = new User(); try { if (userService.exam(username, password)) { user.setUsername(username); user.setPassword(password); user = userService.getByUser(user); if (user.getHead_portrait_path() != null) { HttpSession s1 = req.getSession(); s1.setAttribute("user", user); resp.sendRedirect(req.getContextPath()+"/index.jsp"); } else { resp.sendRedirect(req.getContextPath()+"/login.jsp"); } } else { resp.sendRedirect(req.getContextPath()+"/login.jsp"); } } catch(Exception e) { e.printStackTrace(); } } }
到此這篇關(guān)于JavaWeb文件上傳流程的文章就介紹到這了,更多相關(guān)JavaWeb文件上傳內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
SpringBoot日志進(jìn)階實(shí)戰(zhàn)之Logback配置經(jīng)驗(yàn)和方法
本文給大家介紹在SpringBoot中使用Logback配置日志的經(jīng)驗(yàn)和方法,并提供了詳細(xì)的代碼示例和解釋,包括:滾動(dòng)文件、異步日志記錄、動(dòng)態(tài)指定屬性、日志級(jí)別、配置文件等常用功能,覆蓋日常Logback配置開(kāi)發(fā)90%的知識(shí)點(diǎn),感興趣的朋友跟隨小編一起看看吧2023-06-06Spring集成PageHelper的簡(jiǎn)單用法示例
這篇文章主要介紹了Spring集成PageHelper的簡(jiǎn)單用法示例,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-08-08Java?ServletContext與ServletConfig接口使用教程
ServletConfig對(duì)象,叫Servlet配置對(duì)象。主要用于加載配置文件的初始化參數(shù)。我們知道一個(gè)Web應(yīng)用里面可以有多個(gè)servlet,如果現(xiàn)在有一份數(shù)據(jù)需要傳給所有的servlet使用,那么我們就可以使用ServletContext對(duì)象了2022-09-09Java開(kāi)發(fā)工具IntelliJ IDEA安裝圖解
這篇文章主要介紹了Java開(kāi)發(fā)工具IntelliJ IDEA安裝圖解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-11-11對(duì)比Java講解Kotlin中?.與!!.的區(qū)別
這篇文章主要給大家介紹了關(guān)于對(duì)比Java,實(shí)例講解Kotlin中?.與!!.的區(qū)別,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者使用kotlin具有一定參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2018-06-06IDEA部署Docker鏡像的實(shí)現(xiàn)示例
本文主要介紹了IDEA部署Docker鏡像的實(shí)現(xiàn)示例,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2023-04-04java中l(wèi)ong(Long)與int(Integer)之間的轉(zhuǎn)換方式
這篇文章主要介紹了java中l(wèi)ong(Long)與int(Integer)之間的轉(zhuǎn)換方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-10-10