新用户注册入口 老用户登录入口

[转载]20171105_shiyan_upanddown Struts上传、下载功能结合(集合模拟数据库)

文章作者:转载 更新时间:2023-11-12 20:53:42 阅读数量:139
文章标签:Struts文件上传文件下载ActionJava类
本文摘要:这篇文章详细介绍了在Struts框架中实现文件上传和下载功能的具体实现方式。通过`DocDownloadAction.java`和`DocUploadAction.java`两个核心Java类,分别处理文件的下载与上传操作,其中涉及到了输入流(InputStream)的读取、MIME类型的设置以及文件保存路径的管理。同时,利用自定义拦截器`LoginInterceptor.java`进行用户登录状态的验证,确保了只有已登录用户才能执行相关操作。在struts.xml配置文件中,进一步定义了Action映射及上传限制等参数。整体方案将Struts框架的Action、输入流处理机制、拦截器逻辑紧密结合,实现了安全且高效的文件上传下载功能。
转载文章

本篇文章为转载内容。原文链接:https://blog.csdn.net/qq_34101492/article/details/78811741。

该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。

作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。

如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。

Struts上传、下载功能结合

  • /20171105_shiyan_upanddown/src/nuc/sw/action/DocDownloadAction.java
package nuc.sw.action;import java.io.InputStream;import org.apache.struts2.ServletActionContext;import com.opensymphony.xwork2.ActionSupport;public class DocDownloadAction extends ActionSupport {  private String downPath;//返回InputStream流方法public InputStream getInputStream() throws Exception{       downPath = new String(downPath.getBytes("ISO8859-1"),"utf-8");//默认从WebAPP根目录下取资源return ServletActionContext.getServletContext().getResourceAsStream(downPath);}public String getDownPath(){return downPath;}public void setDownPath(String downPath){this.downPath=downPath;}public String getDownloadFileName(){//downPath.subString是截取downPath的一部分String downFileName=downPath.substring(7);try{downFileName = new String(downFileName.getBytes("iso8859-1"),"utf-8");//downFileName=new String(downFileName.getBytes(),"utf-8");}catch(Exception e){e.printStackTrace();}return downFileName;}@Overridepublic String execute() throws Exception {      return SUCCESS;}   }
  • /20171105_shiyan_upanddown/src/nuc/sw/action/DocUploadAction.java
package nuc.sw.action;import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;import org.apache.struts2.ServletActionContext;import com.opensymphony.xwork2.ActionSupport;public class DocUploadAction extends ActionSupport {private String name;private File[] upload;private String[] uploadContentType;private String[] uploadFileName;private String savePath;private Date createTime;public String getName() {return name;}public void setName(String name) {this.name = name;}public File[] getUpload() {return upload;}public void setUpload(File[] upload) {this.upload = upload;}public String[] getUploadContentType() {return uploadContentType;}public void setUploadContentType(String[] uploadContentType) {this.uploadContentType = uploadContentType;}public String[] getUploadFileName() {return uploadFileName;}public void setUploadFileName(String[] uploadFileName) {this.uploadFileName = uploadFileName;}public String getSavePath() {return savePath;}public void setSavePath(String savePath) {this.savePath = savePath;}public Date getCreateTime(){        createTime=new Date();return createTime;}public static void copy(File source,File target){       InputStream inputStream=null;OutputStream outputStream=null;try{inputStream=new BufferedInputStream(new FileInputStream(source));outputStream=new BufferedOutputStream(new FileOutputStream(target));byte[] buffer=new byte[1024];int length=0;while((length=inputStream.read(buffer))>0){outputStream.write(buffer, 0, length);} }catch(Exception e){e.printStackTrace();}finally{if(null!=inputStream){try {inputStream.close();} catch (IOException e2) {e2.printStackTrace();} }if(null!=outputStream){try{outputStream.close();}catch(Exception e2){e2.printStackTrace();} }} }@Overridepublic String execute() throws Exception {      for(int i=0;i<upload.length;i++){           String path=ServletActionContext.getServletContext().getRealPath(this.getSavePath())+"\\"+this.uploadFileName[i];File target=new File(path);copy(this.upload[i],target);}return SUCCESS;}   }
  • /20171105_shiyan_upanddown/src/nuc/sw/action/LoginAction.java
package nuc.sw.action;import java.util.regex.Pattern;import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;public class LoginAction extends ActionSupport {//属性驱动校验private String username;private String password;public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}//手动检验@Overridepublic void validate() {// TODO Auto-generated method stub//进行数据校验,长度6~15位   if(username.trim().length()<6||username.trim().length()>15||username==null) {this.addFieldError("username", "用户名长度不合法!");}if(password.trim().length()<6||password.trim().length()>15||password==null) {this.addFieldError("password", "密码长度不合法!");} }//登陆业务逻辑public String loginMethod() {if(username.equals("chenghaoran")&&password.equals("12345678")) {ActionContext.getContext().getSession().put("user", username);return "loginOK";}else {this.addFieldError("err","用户名或密码不正确!");return "loginFail";} }//手动校验validateXxxpublic void validateLoginMethod() {//使用正则校验if(username==null||username.trim().equals("")) {this.addFieldError("username","用户名不能为空!");}else {if(!Pattern.matches("[a-zA-Z]{6,15}", username.trim())) {this.addFieldError("username", "用户名格式错误!");} }if(password==null||password.trim().equals("")) {this.addFieldError("password","密码不能为空!");}else {if(!Pattern.matches("\\d{6,15}", password.trim())) {this.addFieldError("password", "密码格式错误!");} }}
}
  • /20171105_shiyan_upanddown/src/nuc/sw/interceptor/LoginInterceptor.java
package nuc.sw.interceptor;import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;public class LoginInterceptor extends AbstractInterceptor {@Overridepublic String intercept(ActionInvocation arg0) throws Exception {// TODO Auto-generated method stub//判断是否登陆,通过ActionContext访问SessionActionContext ac=arg0.getInvocationContext();String username=(String)ac.getSession().get("user");if(username!=null&&username.equals("chenghaoran")) {return arg0.invoke();//放行}else {((ActionSupport)arg0.getAction()).addActionError("请先登录!");return Action.LOGIN;} }}
  • /20171105_shiyan_upanddown/src/struts.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN""http://struts.apache.org/dtds/struts-2.1.7.dtd">
<struts><constant name="struts.i18n.encoding" value="utf-8"/><package name="default" extends="struts-default"><interceptors><interceptor name="login" class="nuc.sw.interceptor.LoginInterceptor"></interceptor></interceptors>     <action name="docUpload" class="nuc.sw.action.DocUploadAction"><!-- 使用fileUpload拦截器 --><interceptor-ref name="fileUpload"><!-- 指定允许上传的文件大小最大为50000字节 --><param name="maximumSize">50000</param></interceptor-ref><!-- 配置默认系统拦截器栈 --><interceptor-ref name="defaultStack"/><!-- param子元素配置了DocUploadAction类中savePath属性值为/upload --><param name="savePath">/upload</param><result>/showFile.jsp</result><!-- 指定input逻辑视图,即不符合上传要求,被fileUpload拦截器拦截后,返回的视图页面 --><result name="input">/uploadFile.jsp</result></action>       <action name="docDownload" class="nuc.sw.action.DocDownloadAction"><!-- 指定结果类型为stream --><result type="stream"><!-- 指定下载文件的文件类型  text/plain表示纯文本 --><param name="contentType">application/msword,text/plain</param><!-- 指定下载文件的入口输入流 --><param name="inputName">inputStream</param><!-- 指定下载文件的处理方式与文件保存名  attachment表示以附件形式下载,也可以用inline表示内联即在浏览器中直接显示,默认值为inline --><param name="contentDisposition">attachment;filename="${downloadFileName}"</param><!-- 指定下载文件的缓冲区大小,默认为1024 --><param name="bufferSize">40960</param></result></action><action name="loginAction" class="nuc.sw.action.LoginAction" method="loginMethod"><result name="loginOK">/uploadFile.jsp</result><result name="loginFail">/login.jsp</result><result name="input">/login.jsp</result></action>       </package>
</struts>
  • /20171105_shiyan_upanddown/WebContent/login.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>    
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>登录页</title>
<s:head/>
</head>
<body><s:actionerror/><s:fielderror fieldName="err"></s:fielderror><s:form action="loginAction" method="post"> <s:textfield label="用户名" name="username"></s:textfield><s:password label="密码" name="password"></s:password><s:submit value="登陆"></s:submit></s:form>
</body>
</html>
  • /20171105_shiyan_upanddown/WebContent/showFile.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>显示上传文档</title>
</head>
<body>
<center><font style="font-size:18px;color:red">上传者:<s:property value="name"/></font><table width="45%" cellpadding="0" cellspacing="0" border="1"><tr><th>文件名称</th><th>上传者</th><th>上传时间</th></tr><s:iterator value="uploadFileName" status="st" var="doc"><tr><td align="center"><a href="docDownload.action?downPath=upload/<s:property value="#doc"/>"><s:property value="#doc"/>              </a></td><td align="center"><s:property value="name"/></td><td align="center"><s:date name="createTime" format="yyyy-MM-dd HH:mm:ss"/></td></tr></s:iterator></table>
</center>
</body>
</html>
  • /20171105_shiyan_upanddown/WebContent/uploadFile.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>文件上传</title>
</head>
<body>
<center>
<s:form action="docUpload" method="post" enctype="multipart/form-data"><s:textfield name="name" label="姓名" size="20"/><s:file name="upload" label="选择文档" size="20"/><s:file name="upload" label="选择文档" size="20"/><s:file name="upload" label="选择文档" size="20"/><s:submit value="确认上传" align="center"/>
</s:form>
</center>
</body>
</html>

本篇文章为转载内容。原文链接:https://blog.csdn.net/qq_34101492/article/details/78811741。

该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。

作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。

如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。

相关阅读
文章标题:[转载][洛谷P1082]同余方程

更新时间:2023-02-18
[转载][洛谷P1082]同余方程
文章标题:[转载]webpack优化之HappyPack实战

更新时间:2023-08-07
[转载]webpack优化之HappyPack实战
文章标题:[转载]oracle 同时更新多表,在Oracle数据库中同时更新两张表的简单方法

更新时间:2023-09-10
[转载]oracle 同时更新多表,在Oracle数据库中同时更新两张表的简单方法
文章标题:[转载][Unity] 包括场景互动与射击要素的俯视角闯关游戏Demo

更新时间:2024-03-11
[转载][Unity] 包括场景互动与射击要素的俯视角闯关游戏Demo
文章标题:[转载]程序员也分三六九等?等级差异,一个看不起一个!

更新时间:2024-05-10
[转载]程序员也分三六九等?等级差异,一个看不起一个!
文章标题:[转载]海贼王 动漫 全集目录 分章节 精彩打斗剧集

更新时间:2024-01-12
[转载]海贼王 动漫 全集目录 分章节 精彩打斗剧集
名词解释
作为当前文章的名词解释,仅对当前文章有效。
StrutsStruts 是一个基于MVC(Model-View-Controller)设计模式的Java Web应用程序框架,它主要用于简化构建企业级Java Web应用的工作。在本文中,Struts被用来实现文件上传和下载功能,通过定义Action类、配置struts.xml文件以及使用拦截器等机制,实现了对HTTP请求的接收、处理及响应。
MIME类型(Multipurpose Internet Mail Extensions)MIME类型是一种标准,用于指定数据内容的格式类型,如文本、图像、视频或应用程序特定的数据。在Web开发中,特别是文件上传和下载场景,服务器端和客户端需要根据MIME类型来正确解析和处理不同类型的文件。例如,在Struts框架中,通过配置MIME类型可以指示浏览器如何打开或保存从服务器下载的文件。
拦截器(Interceptor)在Struts 2框架中,拦截器是一个可插拔的对象,它可以参与到Action执行的整个生命周期中,并在特定阶段进行预处理或后处理操作。文章中的LoginInterceptor就是一个自定义拦截器,它负责检查用户是否已经登录,只有当用户已登录时才允许继续执行后续的操作(如文件上传或下载)。通过这种方式,拦截器增强了系统的安全性,确保了只有经过验证的用户才能访问受限资源。
延伸阅读
作为当前文章的延伸阅读,仅对当前文章有效。
在深入理解了Struts框架中文件上传、下载功能的实现原理及用户登录拦截器的应用后,我们可以进一步探索现代Web开发框架对于文件处理和安全验证机制的最新实践与发展动态。
近期,Spring Boot作为主流Java Web开发框架,在其最新的2.5版本中增强了对文件上传的支持,不仅简化了配置流程,还优化了大文件分块上传与断点续传等功能。例如,开发者可以利用MultipartFile接口轻松处理多部分表单提交的文件,并结合云存储服务(如阿里云OSS或AWS S3)进行分布式文件存储与管理,极大地提高了系统的稳定性和可扩展性。
同时,针对安全性问题,Spring Security框架提供了更严格的CSRF保护和JWT token验证等机制,确保用户在执行敏感操作(如文件上传与下载)时的身份合法性。此外,OAuth 2.0授权协议在企业级应用中的普及,使得跨系统、跨平台的用户身份验证与授权更为便捷且安全。
另外,随着前端技术的发展,诸如React、Vue.js等现代前端框架也实现了对文件上传组件的高度封装,配合后端API能够提供无缝的用户体验。例如,通过axios库在前端发起multipart/form-data类型的POST请求,配合后端的RESTful API完成文件上传过程,而后再通过响应式编程实现文件上传状态的实时反馈。
综上所述,随着技术的演进,无论是后端框架还是前端技术,都在不断提升文件上传下载功能的安全性、易用性和性能表现。在实际项目开发中,除了掌握基础的文件处理方法外,还需关注行业前沿趋势,灵活运用新技术手段以满足不断变化的业务需求。
知识学习
实践的时候请根据实际情况谨慎操作。
随机学习一条linux命令:
pgrep process_name - 查找与进程名匹配的进程ID。
随便看看
拉到页底了吧,随便看看还有哪些文章你可能感兴趣。
RabbitMQ实战中因API版本问题导致消息丢失的排查与修复 03-12 jQuery元素滚动动画库插件-ScrollMagic 02-09 属性级联同步与实体管理:Hibernate实战案例详解 01-27 jQuery超酷3D包装盒封面旋转特效 05-16 ElSteps组件动态改变当前步骤时样式更新滞后问题的Vue.js解决方案 02-22 java中处理异常的方式和语句 01-13 AI助手的工作原理与限制:无法按特定要求撰写的原因及信息处理分析 12-27 代码写的html网红钟表 12-18 简约大气文艺工作者作品展示网站模板 09-21 本次刷新还10个文章未展示,点击 更多查看。
ClickHouse系统重启情境下的数据丢失风险与应对:写入一致性、同步模式及备份恢复策略实践 08-27 jQuery带放大镜的迷你幻灯片插件 08-16 简约手机UI设计公司网站模板下载 04-30 绿色经典响应式主机服务器托管网站模板 04-25 PostgreSQL中应对密码过期警告:安全更改密码的步骤与注意事项 04-17 docker改tag(docker改配置文件) 03-17 [转载]蓝桥 利息计算(Java) 03-11 jquery文字动画特效插件animatext 01-22 大气简洁手机电子产品展示柜台前端模板 01-22 [转载]ubuntu用户和权限介绍 01-10 可爱毛绒玩具网上商城响应式网站模板 01-05
时光飞逝
"流光容易把人抛,红了樱桃,绿了芭蕉。"