JavaWeb文件上傳流程
JavaWeb文件上傳
本文我們學(xué)習(xí)JavaWeb中最重要的技術(shù)之一,文件上傳,該案例我會用一個小型的用戶管理系統(tǒng)實現(xiàn),一步步帶入,內(nèi)容通俗易懂,下面我們步入正題!
做一個簡單的用戶管理系統(tǒng)
功能如下
用戶注冊,參數(shù)有用戶名,用戶名密碼,用戶頭像,
用戶登錄,登錄成功后跳轉(zhuǎn)至主頁顯示用戶頭像和名稱,支持注銷賬號,注銷賬號后,頁面跳轉(zhuǎn)至登錄頁
技術(shù)棧:后端采用JavaWeb、MySQL5.7、Druid連接池、前端采用bootstrap框架結(jié)合jsp
先上效果
完整操作項目演示:
包含:用戶注冊,用戶登錄,用戶登錄后顯示用戶信息,即頭像,賬號名,最右側(cè)顯示注銷,點擊注銷后跳轉(zhuǎn)至登錄頁


項目結(jié)構(gòu)Java源碼

前端頁面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)備
項目所需jar包如下:

jar文件放在WEB-INF/lib文件夾下,主要是為了安全。
文件上傳需要的jar包:

jar文件我會同步資源,小伙伴們不用擔(dān)心哦~
項目結(jié)構(gòu)簡介
本項目采用三層架構(gòu)實現(xiàn),即:service層、dao層、servlet層
- servlet層:
由于之前的servlet層類增刪改查的類太過于多,導(dǎo)致代碼冗余,所以在jsp頁面發(fā)送請求時,采用模塊化的方式進(jìn)行訪問,例如:
- http://localhost/Blog/user/addUser 訪問user模塊的addUser
- http://localhost/Blog/user/getUserList 訪問user模塊的getUserList
- http://localhost/Blog/dept/addDept 訪問dept的addDept
- http://localhost/Blog/dept/getDeptList 訪問dept的getDeptList
這樣一個對應(yīng)的類解決該類的所有對數(shù)據(jù)庫的增刪改查操作,提高了程序的可維護(hù)性,減少代碼的冗余,提高了程序的健壯性。
抽取出公共父類:BaseServletBaseServlet類核心代碼
public class BaseServlet extends HttpServlet{
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//1.獲取瀏覽器請求的資源
String uri = req.getRequestURI();
//2.獲取請求的方法名,最后斜線后面的內(nèi)容
String methodName = uri.substring(uri.lastIndexOf("/")+1);
try {
//3.根據(jù)方法名獲取方法,通過反射獲取
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ù)庫連接類,BaseDao,基于db.properties配置文件連接本地數(shù)據(jù)庫
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 {
//采用單例模式實現(xiàn),防止數(shù)據(jù)庫連接超時
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();
/**
* 注冊用戶
* @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)前項目的路徑
String classesPath = this.getClass().getResource("/").getPath();
File f1 = new File(classesPath);
//項目路徑
String projectPath = f1.getParentFile().getParentFile().getParentFile().getAbsolutePath();
//最后上傳的路徑
String uploadPath = projectPath + "\\ROOT\\upload\\";
File f2 = new File(uploadPath);
if (!f2.exists()) {
f2.mkdirs();
}
//存入數(shù)據(jù)庫的路徑
String headPortraitPath = "";
for (FileItem fileItem : fileItemList) {
if (!fileItem.isFormField()) {
//是文件域
String fileName = fileItem.getName();
//獲取原來文件的后綴
String suffix = fileName.substring(fileName.lastIndexOf("."));
//生成新的文件名,為防止重復(fù),采用隨機數(shù)
String destFileName = UUID.randomUUID().toString().replace("-", "");
//存入數(shù)據(jù)庫的路徑拼接完畢,例如格式:隨機文件名.txt
headPortraitPath = destFileName + suffix;
//寫入硬盤的路徑
uploadPath += headPortraitPath;
//獲取輸入流
InputStream is = fileItem.getInputStream();
//輸出流
FileOutputStream fos = new FileOutputStream(uploadPath);
//將上傳的文件寫入指定路徑
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");
//加入請求域中
req.setAttribute(fieldName, fieldVal);
}
}
String username = (String) req.getAttribute("username");
String password = (String) req.getAttribute("password");
//驗證參數(shù)是否合法,不為空
boolean flag = userService.exam(username, password);
if (flag) {
//將數(shù)據(jù)存入數(shù)據(jù)庫
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");
//驗證是否存在該用戶
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)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
SpringBoot日志進(jìn)階實戰(zhàn)之Logback配置經(jīng)驗和方法
本文給大家介紹在SpringBoot中使用Logback配置日志的經(jīng)驗和方法,并提供了詳細(xì)的代碼示例和解釋,包括:滾動文件、異步日志記錄、動態(tài)指定屬性、日志級別、配置文件等常用功能,覆蓋日常Logback配置開發(fā)90%的知識點,感興趣的朋友跟隨小編一起看看吧2023-06-06
Java?ServletContext與ServletConfig接口使用教程
ServletConfig對象,叫Servlet配置對象。主要用于加載配置文件的初始化參數(shù)。我們知道一個Web應(yīng)用里面可以有多個servlet,如果現(xiàn)在有一份數(shù)據(jù)需要傳給所有的servlet使用,那么我們就可以使用ServletContext對象了2022-09-09
java中l(wèi)ong(Long)與int(Integer)之間的轉(zhuǎn)換方式
這篇文章主要介紹了java中l(wèi)ong(Long)與int(Integer)之間的轉(zhuǎn)換方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-10-10

