当前位置: 代码网 > it编程>编程语言>Java > JSP+Servlet实现文件上传到服务器功能

JSP+Servlet实现文件上传到服务器功能

2024年05月18日 Java 我要评论
本文实例为大家分享了jsp+servlet实现文件上传到服务器功能的具体代码,供大家参考,具体内容如下项目目录结构大致如下:正如我在上图红线画的三个东西:dao、service、servlet 这三层

本文实例为大家分享了jsp+servlet实现文件上传到服务器功能的具体代码,供大家参考,具体内容如下

项目目录结构大致如下:

正如我在上图红线画的三个东西:dao、service、servlet 这三层是主要的结构,类似 mvc 架构,dao是模型实体类(逻辑层),service是服务层,servlet是视图层,三者协作共同完成项目。

这里的user是由user表来定义的一个类,再封装增删改查等操作,实现从数据库查询与插入,修改与删除等操作,并实现了分页操作,也实现了将图片放到服务器上运行的效果。

dao层:主要实现了user类的定义,接口iuserdao的定义与实现(userdaoimpl);

service层:直接定义一个接口类iuserservice,与iuserdao相似,再实现其接口类userserviceimpl,直接实例化userdaoimpl再调用其方法来实现自己的方法,重用了代码。详见代码吧;

servlet层:起初是将表user 的每个操作方法都定义成一个servlet 去实现,虽然简单,但是太多了,不好管理,于是利用 基类baseservlet 实现了“反射机制”,通过获取的 action 参数自己智能地调用对应的方法,而userservlet则具体实现自己的方法,以供调用,方便许多,详见之前的博文或下述代码。

将文件上传到 tomcat 服务器的编译后运行的过程的某个文件关键要在每次编译后手动为其创建该文件夹来存放相应的上传文件,否则会导致每次重启 tomcat 服务器后该编译后的工程覆盖了原先的,导致上传文件存放的文件夹不存在,导致代码找不到该文件夹而报错,即上传不成功。如下图所示:

主要是考虑图片路径的问题,手工设置路径肯定不能保证不重复,所以取到上传图片的后缀名后利用随机生成的随机数作为图片名,这样就不会重复名字了:

string extendedname = picturepath.substring(picturepath.lastindexof("."),// 截取从最后一个'.'到字符串结束的子串。
 picturepath.length());
 // 把文件名称重命名为全球唯一的文件名
 string uniquename = uuid.randomuuid().tostring();
 savefilename = uniquename + extendedname;// 拼接路径名

增加用户时代码如下:

 // 增
 public void add(httpservletrequest request, httpservletresponse response)
 throws servletexception, ioexception {
 system.out.println("add方法被调用");
 // 获取数据
 int id = 0;
 string username = null;
 string password = null;
 string sex = null;
 date birthday = null;
 string address = null;
 string savefilename = null;
 string picturepath = null;
 // 得到表单是否以enctype="multipart/form-data"方式提交
 boolean ismulti = servletfileupload.ismultipartcontent(request);
 if (ismulti) {
 // 通过fileitemfactory得到文件上传的对象
 fileitemfactory fif = new diskfileitemfactory();
 servletfileupload upload = new servletfileupload(fif);
 
 try {
 list<fileitem> items = upload.parserequest(request);
 for (fileitem item : items) {
 // 判断是否是普通表单控件,或者是文件上传表单控件
 boolean isform = item.isformfield();
 if (isform) {// 是普通表单控件
 string name = item.getfieldname();
 if ("id".equals(name)) {
 id = integer.parseint(item.getstring("utf-8"));
 system.out.println(id);
 }
 if ("sex".equals(name)) {
 sex = item.getstring("utf-8");
 system.out.println(sex);
 }
 if ("username".equals(name)) {
 username = item.getstring("utf-8");
 system.out.println(username);
 }
 if ("password".equals(name)) {
 password = item.getstring("utf-8");
 system.out.println(password);
 }
 if ("birthday".equals(name)) {
 string birthdaystr = item.getstring("utf-8");
 simpledateformat sdf = new simpledateformat(
  "yyyy-mm-dd");
 try {
 birthday = sdf.parse(birthdaystr);
 } catch (parseexception e) {
 e.printstacktrace();
 }
 system.out.println(birthday);
 }
 if ("address".equals(name)) {
 address = item.getstring("utf-8");
 system.out.println(address);
 }
 if ("picturepath".equals(name)) {
 picturepath = item.getstring("utf-8");
 system.out.println(picturepath);
 }
 } else {// 是文件上传表单控件
 // 得到文件名 xxx.jpg
 string sourcefilename = item.getname();
 // 得到文件名的扩展名:.jpg
 string extendedname = sourcefilename.substring(
 sourcefilename.lastindexof("."),
 sourcefilename.length());
 // 把文件名称重命名为全球唯一的文件名
 string uniquename = uuid.randomuuid().tostring();
 savefilename = uniquename + extendedname;
 // 得到上传到服务器上的文件路径
 // c:\\apache-tomcat-7.0.47\\webapps\\taobaoservlet4\\upload\\xx.jpg
 string uploadfilepath = request.getsession()
 .getservletcontext().getrealpath("upload/");
 file savefile = new file(uploadfilepath, savefilename);
 // 把保存的文件写出到服务器硬盘上
 try {
 item.write(savefile);
 } catch (exception e) {
 e.printstacktrace();
 }
 }
 }
 } catch (numberformatexception e) {
 // todo auto-generated catch block
 e.printstacktrace();
 } catch (fileuploadexception e) {
 // todo auto-generated catch block
 e.printstacktrace();
 }
 }
 // 2、封装数据
 user user = new user(id, username, password, sex, birthday, address,
 savefilename);
 // 3、调用逻辑层api
 iuserservice iuserservice = new userserviceimpl();
 // 4、控制跳转
 httpsession session = request.getsession();
 if (iuserservice.save(user) > 0) {
 system.out.println("添加新用户成功!");
 list<user> users = new arraylist<user>();
 users = iuserservice.listall();
 session.setattribute("users", users);
 response.sendredirect("userservlet?action=getpage");
 } else {
 system.out.println("添加新用户失败!");
 printwriter out = response.getwriter();
 out.print("<script type='text/javascript'>");
 out.print("alert('添加新用户失败!请重试!');");
 out.print("</script>");
 }
 }

修改用户时注意考虑图片更改和没更改这两种情况,图片更改时要先获取原图片并删除其在服务器上的图片,再添加新图片到服务器;图片不更改时则无需更新图片路径。

 // 改
 public void update(httpservletrequest request, httpservletresponse response)
 throws servletexception, ioexception {
 system.out.println("update方法被调用");
 httpsession session = request.getsession();
 // 获取数据
 int id = (int)session.getattribute("id");
 string username = null;
 string password = null;
 string sex = null;
 date birthday = null;
 string address = null;
 string savefilename = null;
 string picturepath = null;
 iuserservice iuserservice = new userserviceimpl();
 // 得到表单是否以enctype="multipart/form-data"方式提交
 boolean ismulti = servletfileupload.ismultipartcontent(request);
 if (ismulti) {
 // 通过fileitemfactory得到文件上传的对象
 fileitemfactory fif = new diskfileitemfactory();
 servletfileupload upload = new servletfileupload(fif);
 try {
 list<fileitem> items = upload.parserequest(request);
 for (fileitem item : items) {
 // 判断是否是普通表单控件,或者是文件上传表单控件
 boolean isform = item.isformfield();
 if (isform) {// 是普通表单控件
 string name = item.getfieldname();
 if ("sex".equals(name)) {
 sex = item.getstring("utf-8");
 system.out.println(sex);
 }
 if ("username".equals(name)) {
 username = item.getstring("utf-8");
 system.out.println(username);
 }
 if ("password".equals(name)) {
 password = item.getstring("utf-8");
 system.out.println(password);
 }
 if ("birthday".equals(name)) {
 string birthdaystr = item.getstring("utf-8");
 simpledateformat sdf = new simpledateformat(
  "yyyy-mm-dd");
 try {
 birthday = sdf.parse(birthdaystr);
 } catch (parseexception e) {
 e.printstacktrace();
 }
 system.out.println(birthday);
 }
 if ("address".equals(name)) {
 address = item.getstring("utf-8");
 system.out.println(address);
 }
 if ("picturepath".equals(name)) {
 picturepath = item.getstring("utf-8");
 system.out.println(picturepath);
 }
 } else {// 是文件上传表单控件
 // 得到文件名 xxx.jpg
 picturepath = item.getname();
 if (picturepath != "") {// 有选择要上传的图片
 // 得到文件名的扩展名:.jpg
 string extendedname = picturepath.substring(
  picturepath.lastindexof("."),// 截取从最后一个'.'到字符串结束的子串。
  picturepath.length());
 // 把文件名称重命名为全球唯一的文件名
 string uniquename = uuid.randomuuid().tostring();
 savefilename = uniquename + extendedname;// 拼接路径名
 // 得到上传到服务器上的文件路径
 // c:\\apache-tomcat-7.0.47\\webapps\\commonhelloworldservlet\\upload\\xx.jpg
 string uploadfilepath = request.getsession()
  .getservletcontext().getrealpath("upload/");
 file savefile = new file(uploadfilepath,
  savefilename);
 // 把保存的文件写出到服务器硬盘上
 try {
 item.write(savefile);
 } catch (exception e) {
 e.printstacktrace();
 }
 // 3、调用逻辑层 api
 // 根据id查询用户并获取其之前的图片
 user user = iuserservice.getuserbyid(id);
 string oldpic = user.getpicturepath();
 string oldpicpath = uploadfilepath + "\\" + oldpic;
 file oldpictodelete = new file(oldpicpath);
 oldpictodelete.delete();// 删除旧图片
 }
 }
 }
 } catch (numberformatexception e) {
 e.printstacktrace();
 } catch (fileuploadexception e) {
 e.printstacktrace();
 }
 }
 system.out.println(id + "\t" + username + "\t" + password + "\t" + sex
 + "\t" + address + "\t" + picturepath + "\t" + birthday);
 
 // 2、封装数据
 user user = new user(id, username, password, sex, birthday, address,
 savefilename);
 
 if (iuserservice.update(user) > 0) {
 system.out.println("修改数据成功!");
 list<user> users = new arraylist<user>();
 users = iuserservice.listall();
 session.setattribute("users", users);
 // 4、控制跳转
 response.sendredirect("userservlet?action=getpage");
 } else {
 system.out.println("修改数据失败!");
 printwriter out = response.getwriter();
 out.print("<script type='text/javascript'>");
 out.print("alert('修改数据失败!请重试!');");
 out.print("</script>");
 }
 }

删除的话就比较简单了,直接获取原图片路径并删除,则原图片在服务器上被删除。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持代码网。

(0)

相关文章:

  • jsp实现简单用户7天内免登录

    jsp实现简单用户7天内免登录

    本文实例为大家分享了jsp实现简单用户7天内免登录的具体代码,供大家参考,具体内容如下(1)登陆页面:login.jsp<%@ page language... [阅读全文]
  • JSP使用过滤器防止Xss漏洞

    JSP使用过滤器防止Xss漏洞

    在用java进行web业务开发的时候,对于页面上接收到的参数,除了极少数是步可预知的内容外,大量的参数名和参数值都是不会出现触发xss漏洞的字符。而通常为了避免... [阅读全文]
  • JSP数据交互实现过程解析

    JSP数据交互实现过程解析

    这篇文章主要介绍了jsp数据交互实现过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下1.jsp内置对象... [阅读全文]
  • jsp实现登录验证的过滤器

    jsp实现登录验证的过滤器

    本文实例为大家分享了jsp实现登录验证的过滤器,供大家参考,具体内容如下1.新建一个dynamic web project项目,里面新建1个filter文件、1... [阅读全文]
  • jsp实现用户自动登录功能

    理解并掌握cookie的作用以及利用cookie实现用户的自动登录功能,实现下图效果当服务器判断出该用户是首次登录的时候,会自动跳转到登录界面等待用户登录,并填入相关信息。通过设置…

    2024年05月18日 编程语言
  • servlet+jsp实现过滤器 防止用户未登录访问

    servlet+jsp实现过滤器 防止用户未登录访问

    我们可能经常会用到这一功能,比如有时,我们不希望用户没有进行登录访问后台的操作页面,而且这样的非法访问会让系统极为的不安全,所以我们常常需要进行登录才授权访问其... [阅读全文]

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com