JavaWeb文件上传流程(Java 文件上传)

网友投稿 315 2022-07-28


目录javaWeb文件上传做一个简单的用户管理系统先上效果数据表准备Jar文件准备项目结构简介

JavaWeb文件上传

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

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

功能如下

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

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

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

先上效果

完整操作项目演示:

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

项目结构Java源码

前端页面jsp

数据表准备

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包如下:

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

文件上传需要的jar包:

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

项目结构简介

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

servlet层:

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

http://localhost/Blog/user/addUser 访问user模块的addUserhttp://localhost/Blog/user/getUserList 访问user模块的getUserListhttp://localhost/Blog/dept/addDept 访问dept的addDepthttp://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("/")+1HrYKJvWPR);

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("/").http://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 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 + "\\ROOT\\upload\\";

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();

}

}

}


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:使用IntelliJ IDEA调式Stream流的方法步骤(使用intellij新建模块出错)
下一篇:SpringBoot集成Jasypt敏感信息加密的操作方法(springboot jasypt解密)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~