服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Java教程 - JavaWeb文件上传流程

JavaWeb文件上传流程

2022-12-22 16:26小王Java Java教程

这篇文章主要介绍了JavaWeb文件上传流程,JavaWeb中最重要的技术之一,下文关于其文件上传的流程分享,需要的小伙伴可以参考一下

JavaWeb文件上传

本文我们学习JavaWeb中最重要的技术之一,文件上传,该案例我会用一个小型的用户管理系统实现,一步步带入,内容通俗易懂,下面我们步入正题!

做一个简单的用户管理系统

功能如下

用户注册,参数有用户名,用户名密码,用户头像,

用户登录,登录成功后跳转至主页显示用户头像和名称,支持注销账号,注销账号后,页面跳转至登录页

技术栈:后端采用JavaWebMySQL5.7Druid连接池、前端采用bootstrap框架结合jsp

先上效果

完整操作项目演示:

包含:用户注册,用户登录,用户登录后显示用户信息,即头像,账号名,最右侧显示注销,点击注销后跳转至登录页

JavaWeb文件上传流程

JavaWeb文件上传流程

项目结构Java源码

JavaWeb文件上传流程

前端页面jsp

JavaWeb文件上传流程

数据表准备

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文件准备

项目所需jar包如下

JavaWeb文件上传流程

jar文件放在WEB-INF/lib文件夹下,主要是为了安全。

文件上传需要的jar包:

JavaWeb文件上传流程

jar文件我会同步资源,小伙伴们不用担心哦~

项目结构简介

本项目采用三层架构实现,即:service层、dao层、servlet层

  • servlet层:

由于之前的servlet层类增删改查的类太过于多,导致代码冗余,所以在jsp页面发送请求时,采用模块化的方式进行访问,例如:

  • 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

这样一个对应的类解决该类的所有对数据库的增删改查操作,提高了程序的可维护性,减少代码的冗余,提高了程序的健壮性。
抽取出公共父类:BaseServletBaseServlet类核心代码

public class BaseServlet extends HttpServlet{
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//1.获取浏览器请求的资源
String uri = req.getRequestURI();
//2.获取请求的方法名,最后斜线后面的内容
String methodName = uri.substring(uri.lastIndexOf("/")+1);
try {
//3.根据方法名获取方法,通过反射获取
Method method = this.getClass().getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
//4.调用方法
method.invoke(this, req, resp);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
  • dao层

dao层抽取出公共数据库连接类,BaseDao,基于db.properties配置文件连接本地数据库

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 {
//采用单例模式实现,防止数据库连接超时
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{

//业务层类,用于调用业务层方法
UserService userService = new UserServiceImpl();

/**
* 注册用户
* @param req
* @param resp
*/
public void register(HttpServletRequest req, HttpServletResponse resp) {
//获取数据
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload fileUpload = new ServletFileUpload(factory);
try {
List<FileItem> fileItemList = fileUpload.parseRequest(req);
//获取当前项目的路径
String classesPath = this.getClass().getResource("/").getPath();

File f1 = new File(classesPath);
//项目路径
String projectPath = f1.getParentFile().getParentFile().getParentFile().getAbsolutePath();

//最后上传的路径
String uploadPath = projectPath + "ROOTupload";

File f2 = new File(uploadPath);
if (!f2.exists()) {
f2.mkdirs();
}
//存入数据库的路径
String headPortraitPath = "";
for (FileItem fileItem : fileItemList) {
if (!fileItem.isFormField()) {
//是文件域
String fileName = fileItem.getName();
//获取原来文件的后缀
String suffix = fileName.substring(fileName.lastIndexOf("."));
//生成新的文件名,为防止重复,采用随机数
String destFileName = UUID.randomUUID().toString().replace("-", "");

//存入数据库的路径拼接完毕,例如格式:随机文件名.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");
//验证参数是否合法,不为空
boolean flag = userService.exam(username, password);
if (flag) {
//将数据存入数据库
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) {
//获取数据
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();
}
}
}

到此这篇关于JavaWeb文件上传流程的文章就介绍到这了,更多相关JavaWeb文件上传内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文地址:https://blog.51cto.com/u_15500707/5320922

延伸 · 阅读

精彩推荐