修正Strut2 自带上传拦截器功能
上传 功能 自带 拦截器 修正
2023-09-14 09:01:03 时间
Struts2字典的FileUploadInterceptor 拦截器 主要帮助获取上传文件的ContentType、fileName、文件对象。如果开发人员在开发过程中使用。则需要设置set/get方法:
setXXXContentType()
getXXXFileName()
getXXXContentType()
setXXXFileName()
getXXXFile()
setXXXFile() 其中,"xxx"为渲染器的name. 问题在这里 第一,如果除了ContentType/File/FileName ,还需要其他的消息怎么办呢。拦截器就无能为力了。 这个可以忽略。 第二,平时在开发过程中,我们经常有动态添加附件功能。如果上传的附件同属于一类的话,还尚可。但是,如果一个页面中,需要上传多种类型的附件,而且每个附件类型动态增加的。拦截器就有点力不从心了。只能针对每个类型的附件,在Action中写多个方法。 setType1File(); setType2File(); setType1ContentType(); setType2ContentType(); setType1FileName(); setType2FileName(); --------- 问题在这里。如果我再增加一个类型呢? 在深层挖掘一下,如果我想做一个公共的文件上传处理类,怎么办。 本人研究了下自带的拦截器,在此基础上,通过自己的实践,提出自己的一个解决方案。 我通过Map 来管理上传的文件列表。这样就不惧怕多类型文件上传,且可扩展性也提高了。 修正后的Strut2 FileUploadInterceptor 如下
public String intercept(ActionInvocation invocation) throws Exception {
ActionContext ac = invocation.getInvocationContext();
HttpServletRequest request = (HttpServletRequest) ac.get(ServletActionContext.HTTP_REQUEST);
if (!(request instanceof MultiPartRequestWrapper)) {
if (LOG.isDebugEnabled()) {
ActionProxy proxy = invocation.getProxy();
LOG.debug(getTextMessage("struts.messages.bypass.request", new Object[]{proxy.getNamespace(), proxy.getActionName()}, ac.getLocale()));
}
return invocation.invoke();
}
ValidationAware validation = null;
Object action = invocation.getAction();
if (action instanceof ValidationAware) {
validation = (ValidationAware) action;
}
MultiPartRequestWrapper multiWrapper = (MultiPartRequestWrapper) request;
if (multiWrapper.hasErrors()) {
for (String error : multiWrapper.getErrors()) {
if (validation != null) {
validation.addActionError(error);
}
LOG.warn(error);
}
}
// bind allowed Files
Enumeration fileParameterNames = multiWrapper.getFileParameterNames();
Map String,List Map String,Object fileParameterMap = new HashMap String,List Map String,Object //文件值对 //zhaogy
while (fileParameterNames != null fileParameterNames.hasMoreElements()) {
// get the value of this input tag
String inputName = (String) fileParameterNames.nextElement();
// get the content type
String[] contentType = multiWrapper.getContentTypes(inputName);
if (isNonEmpty(contentType)) {
// get the name of the file from the input tag
String[] fileName = multiWrapper.getFileNames(inputName);
if (isNonEmpty(fileName)) {
// get a File object for the uploaded File
File[] files = multiWrapper.getFiles(inputName);
if (files != null files.length 0) {
List File acceptedFiles = new ArrayList File (files.length);
List String acceptedContentTypes = new ArrayList String (files.length);
List String acceptedFileNames = new ArrayList String (files.length);
List String renderNames = new ArrayList String (files.length);
String contentTypeName = inputName + "ContentType";
String fileNameName = inputName + "FileName";
for (int index = 0; index files.length; index++) {
if (acceptFile(action, files[index], fileName[index], contentType[index], inputName, validation, ac.getLocale())) {
acceptedFiles.add(files[index]);
acceptedContentTypes.add(contentType[index]);
acceptedFileNames.add(fileName[index]);
List Map String, Object vfl=null;
if(fileParameterMap.containsKey(inputName)){//是否已存在
vfl = fileParameterMap.get(inputName);
}else{
vfl = new ArrayList Map String,Object ();
fileParameterMap.put(inputName, vfl);
}
Map String, Object value = new HashMap String,Object
value.put("contentType", contentType[index]);
value.put("fileName", fileName[index]);
value.put("acceptedFile", files[index]);
vfl.add(value);
}
}
if (!acceptedFiles.isEmpty()) {
Map String, Object params = ac.getParameters();
params.put(inputName, acceptedFiles.toArray(new File[acceptedFiles.size()]));
params.put(contentTypeName, acceptedContentTypes.toArray(new String[acceptedContentTypes.size()]));
params.put(fileNameName, acceptedFileNames.toArray(new String[acceptedFileNames.size()]));
params.put("fileParameterMap", fileParameterMap);// zhaogy
}
}
} else {
LOG.warn(getTextMessage(action, "struts.messages.invalid.file", new Object[]{inputName}, ac.getLocale()));
}
} else {
LOG.warn(getTextMessage(action, "struts.messages.invalid.content.type", new Object[]{inputName}, ac.getLocale()));
}
}
// invoke action
String result = invocation.invoke();
// cleanup
fileParameterNames = multiWrapper.getFileParameterNames();
while (fileParameterNames != null fileParameterNames.hasMoreElements()) {
String inputValue = (String) fileParameterNames.nextElement();
File[] files = multiWrapper.getFiles(inputValue);
for (File currentFile : files) {
if (LOG.isInfoEnabled()) {
LOG.info(getTextMessage(action, "struts.messages.removing.file", new Object[]{inputValue, currentFile}, ac.getLocale()));
}
if ((currentFile != null) currentFile.isFile()) {
if (currentFile.delete() == false) {
LOG.warn("Resource Leaking: Could not remove uploaded file " + currentFile.getCanonicalPath() + ".");
}
}
}
}
return result;
} 测试代码:
/*
* $Id: MultipleFileUploadUsingListAction.java 660522 2008-05-27 14:08:00Z jholmes $
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
// START SNIPPET: entire-file
package org.apache.struts2.showcase.fileupload;
import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import com.opensymphony.xwork2.ActionSupport;
/**
* Showcase action - multiple file upload using List
* @version $Date: 2008-05-27 16:08:00 +0200 (Tue, 27 May 2008) $ $Id: MultipleFileUploadUsingListAction.java 660522 2008-05-27 14:08:00Z jholmes $
*/
public class MultipleFileUploadUsingListAction extends ActionSupport {
private List File uploads = new ArrayList File
private List String uploadFileNames = new ArrayList String
private List String uploadContentTypes = new ArrayList String
public void setFileParameterMap(
Map String, List Map String, Object fileParameterMap) {
this.fileParameterMap = fileParameterMap;
}
public List File getUpload() {
return this.uploads;
}
public void setUpload(List File uploads) {
this.uploads = uploads;
}
public List String getUploadFileName() {
return this.uploadFileNames;
}
public void setUploadFileName(List String uploadFileNames) {
this.uploadFileNames = uploadFileNames;
}
public List String getUploadContentType() {
return this.uploadContentTypes;
}
public void setUploadContentType(List String contentTypes) {
this.uploadContentTypes = contentTypes;
}
private Map String,List Map String,Object fileParameterMap;
public Map String, List Map String, Object getFileParameterMap() {
return fileParameterMap;
}
public String upload() throws Exception {
Iterator String iter = this.fileParameterMap.keySet().iterator();
while(iter.hasNext()){
String key = iter.next();
List Map String, Object vs = this.fileParameterMap.get(key);
System.out.println("key========"+key);
for(Map String, Object v : vs){
Object contentType = v.get("contentType");
Object fileName = v.get("fileName");
Object file = v.get("acceptedFile");
System.out.println("contentType "+contentType);
System.out.println("fileName "+fileName);
System.out.println("file "+file);
}
}
// System.out.println("\n\n upload1");
// System.out.println("files:");
// for (File u: uploads) {
// System.out.println("*** "+u+"\t"+u.length());
// }
// System.out.println("filenames:");
// for (String n: uploadFileNames) {
// System.out.println("*** "+n);
// }
// System.out.println("content types:");
// for (String c: uploadContentTypes) {
// System.out.println("*** "+c);
// }
// System.out.println("\n\n");
return SUCCESS;
}
}
// END SNIPPET: entire-file
fileName xm_xvs.cfg
file D:\Tomcat-6.0.20\work\Catalina\localhost\struts2-showcase\upload_8c1aaae_1372ca9bef5__8000_00000011.tmp
contentType text/html
fileName login.html
file D:\Tomcat-6.0.20\work\Catalina\localhost\struts2-showcase\upload_8c1aaae_1372ca9bef5__8000_00000012.tmp
key========upload
contentType text/plain
fileName 说明.txt
file D:\Tomcat-6.0.20\work\Catalina\localhost\struts2-showcase\upload_8c1aaae_1372ca9bef5__8000_00000008.tmp
contentType application/vnd.openxmlformats-officedocument.wordprocessingml.document
fileName 孕妇饮食注意事项.docx
file D:\Tomcat-6.0.20\work\Catalina\localhost\struts2-showcase\upload_8c1aaae_1372ca9bef5__8000_00000009.tmp
一套过滤器,让你的代码高处不胜寒! 过滤器模式,顾名思义,从名字上就可以看出主要用于过滤对象,实现起来也很简单! 从设计的角度看,过滤器模式涉及到三个角色: 抽象过滤器角色:主要定义过滤器的行为; 具体滤器角色:实现或者继承抽象过滤器,完善具体算法; 客户端:客户类提出使用具体类的请求; 话不多说,代码直接撸起来~
SSH框架整合——strut2完成forword跳转 strut2固定是request的请求重定向方式进行跳转 如果界面中用forword来完成跳转: 会报请求错误的异常,所以需要在web.xml中修改strut2的配置 struts2 /* FORWORD REQUEST 这样既可以接收request请求,又...
getXXXFileName()
getXXXContentType()
setXXXFileName()
getXXXFile()
setXXXFile() 其中,"xxx"为渲染器的name. 问题在这里 第一,如果除了ContentType/File/FileName ,还需要其他的消息怎么办呢。拦截器就无能为力了。 这个可以忽略。 第二,平时在开发过程中,我们经常有动态添加附件功能。如果上传的附件同属于一类的话,还尚可。但是,如果一个页面中,需要上传多种类型的附件,而且每个附件类型动态增加的。拦截器就有点力不从心了。只能针对每个类型的附件,在Action中写多个方法。 setType1File(); setType2File(); setType1ContentType(); setType2ContentType(); setType1FileName(); setType2FileName(); --------- 问题在这里。如果我再增加一个类型呢? 在深层挖掘一下,如果我想做一个公共的文件上传处理类,怎么办。 本人研究了下自带的拦截器,在此基础上,通过自己的实践,提出自己的一个解决方案。 我通过Map 来管理上传的文件列表。这样就不惧怕多类型文件上传,且可扩展性也提高了。 修正后的Strut2 FileUploadInterceptor 如下
public String intercept(ActionInvocation invocation) throws Exception {
ActionContext ac = invocation.getInvocationContext();
HttpServletRequest request = (HttpServletRequest) ac.get(ServletActionContext.HTTP_REQUEST);
if (!(request instanceof MultiPartRequestWrapper)) {
if (LOG.isDebugEnabled()) {
ActionProxy proxy = invocation.getProxy();
LOG.debug(getTextMessage("struts.messages.bypass.request", new Object[]{proxy.getNamespace(), proxy.getActionName()}, ac.getLocale()));
}
return invocation.invoke();
}
ValidationAware validation = null;
Object action = invocation.getAction();
if (action instanceof ValidationAware) {
validation = (ValidationAware) action;
}
MultiPartRequestWrapper multiWrapper = (MultiPartRequestWrapper) request;
if (multiWrapper.hasErrors()) {
for (String error : multiWrapper.getErrors()) {
if (validation != null) {
validation.addActionError(error);
}
LOG.warn(error);
}
}
// bind allowed Files
Enumeration fileParameterNames = multiWrapper.getFileParameterNames();
Map String,List Map String,Object fileParameterMap = new HashMap String,List Map String,Object //文件值对 //zhaogy
while (fileParameterNames != null fileParameterNames.hasMoreElements()) {
// get the value of this input tag
String inputName = (String) fileParameterNames.nextElement();
// get the content type
String[] contentType = multiWrapper.getContentTypes(inputName);
if (isNonEmpty(contentType)) {
// get the name of the file from the input tag
String[] fileName = multiWrapper.getFileNames(inputName);
if (isNonEmpty(fileName)) {
// get a File object for the uploaded File
File[] files = multiWrapper.getFiles(inputName);
if (files != null files.length 0) {
List File acceptedFiles = new ArrayList File (files.length);
List String acceptedContentTypes = new ArrayList String (files.length);
List String acceptedFileNames = new ArrayList String (files.length);
List String renderNames = new ArrayList String (files.length);
String contentTypeName = inputName + "ContentType";
String fileNameName = inputName + "FileName";
for (int index = 0; index files.length; index++) {
if (acceptFile(action, files[index], fileName[index], contentType[index], inputName, validation, ac.getLocale())) {
acceptedFiles.add(files[index]);
acceptedContentTypes.add(contentType[index]);
acceptedFileNames.add(fileName[index]);
List Map String, Object vfl=null;
if(fileParameterMap.containsKey(inputName)){//是否已存在
vfl = fileParameterMap.get(inputName);
}else{
vfl = new ArrayList Map String,Object ();
fileParameterMap.put(inputName, vfl);
}
Map String, Object value = new HashMap String,Object
value.put("contentType", contentType[index]);
value.put("fileName", fileName[index]);
value.put("acceptedFile", files[index]);
vfl.add(value);
}
}
if (!acceptedFiles.isEmpty()) {
Map String, Object params = ac.getParameters();
params.put(inputName, acceptedFiles.toArray(new File[acceptedFiles.size()]));
params.put(contentTypeName, acceptedContentTypes.toArray(new String[acceptedContentTypes.size()]));
params.put(fileNameName, acceptedFileNames.toArray(new String[acceptedFileNames.size()]));
params.put("fileParameterMap", fileParameterMap);// zhaogy
}
}
} else {
LOG.warn(getTextMessage(action, "struts.messages.invalid.file", new Object[]{inputName}, ac.getLocale()));
}
} else {
LOG.warn(getTextMessage(action, "struts.messages.invalid.content.type", new Object[]{inputName}, ac.getLocale()));
}
}
// invoke action
String result = invocation.invoke();
// cleanup
fileParameterNames = multiWrapper.getFileParameterNames();
while (fileParameterNames != null fileParameterNames.hasMoreElements()) {
String inputValue = (String) fileParameterNames.nextElement();
File[] files = multiWrapper.getFiles(inputValue);
for (File currentFile : files) {
if (LOG.isInfoEnabled()) {
LOG.info(getTextMessage(action, "struts.messages.removing.file", new Object[]{inputValue, currentFile}, ac.getLocale()));
}
if ((currentFile != null) currentFile.isFile()) {
if (currentFile.delete() == false) {
LOG.warn("Resource Leaking: Could not remove uploaded file " + currentFile.getCanonicalPath() + ".");
}
}
}
}
return result;
} 测试代码:
/*
* $Id: MultipleFileUploadUsingListAction.java 660522 2008-05-27 14:08:00Z jholmes $
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
// START SNIPPET: entire-file
package org.apache.struts2.showcase.fileupload;
import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import com.opensymphony.xwork2.ActionSupport;
/**
* Showcase action - multiple file upload using List
* @version $Date: 2008-05-27 16:08:00 +0200 (Tue, 27 May 2008) $ $Id: MultipleFileUploadUsingListAction.java 660522 2008-05-27 14:08:00Z jholmes $
*/
public class MultipleFileUploadUsingListAction extends ActionSupport {
private List File uploads = new ArrayList File
private List String uploadFileNames = new ArrayList String
private List String uploadContentTypes = new ArrayList String
public void setFileParameterMap(
Map String, List Map String, Object fileParameterMap) {
this.fileParameterMap = fileParameterMap;
}
public List File getUpload() {
return this.uploads;
}
public void setUpload(List File uploads) {
this.uploads = uploads;
}
public List String getUploadFileName() {
return this.uploadFileNames;
}
public void setUploadFileName(List String uploadFileNames) {
this.uploadFileNames = uploadFileNames;
}
public List String getUploadContentType() {
return this.uploadContentTypes;
}
public void setUploadContentType(List String contentTypes) {
this.uploadContentTypes = contentTypes;
}
private Map String,List Map String,Object fileParameterMap;
public Map String, List Map String, Object getFileParameterMap() {
return fileParameterMap;
}
public String upload() throws Exception {
Iterator String iter = this.fileParameterMap.keySet().iterator();
while(iter.hasNext()){
String key = iter.next();
List Map String, Object vs = this.fileParameterMap.get(key);
System.out.println("key========"+key);
for(Map String, Object v : vs){
Object contentType = v.get("contentType");
Object fileName = v.get("fileName");
Object file = v.get("acceptedFile");
System.out.println("contentType "+contentType);
System.out.println("fileName "+fileName);
System.out.println("file "+file);
}
}
// System.out.println("\n\n upload1");
// System.out.println("files:");
// for (File u: uploads) {
// System.out.println("*** "+u+"\t"+u.length());
// }
// System.out.println("filenames:");
// for (String n: uploadFileNames) {
// System.out.println("*** "+n);
// }
// System.out.println("content types:");
// for (String c: uploadContentTypes) {
// System.out.println("*** "+c);
// }
// System.out.println("\n\n");
return SUCCESS;
}
}
// END SNIPPET: entire-file
fileName xm_xvs.cfg
file D:\Tomcat-6.0.20\work\Catalina\localhost\struts2-showcase\upload_8c1aaae_1372ca9bef5__8000_00000011.tmp
contentType text/html
fileName login.html
file D:\Tomcat-6.0.20\work\Catalina\localhost\struts2-showcase\upload_8c1aaae_1372ca9bef5__8000_00000012.tmp
key========upload
contentType text/plain
fileName 说明.txt
file D:\Tomcat-6.0.20\work\Catalina\localhost\struts2-showcase\upload_8c1aaae_1372ca9bef5__8000_00000008.tmp
contentType application/vnd.openxmlformats-officedocument.wordprocessingml.document
fileName 孕妇饮食注意事项.docx
file D:\Tomcat-6.0.20\work\Catalina\localhost\struts2-showcase\upload_8c1aaae_1372ca9bef5__8000_00000009.tmp
本文出自 “简单” 博客,请务必保留此出处http://dba10g.blog.51cto.com/764602/857866
一套过滤器,让你的代码高处不胜寒! 过滤器模式,顾名思义,从名字上就可以看出主要用于过滤对象,实现起来也很简单! 从设计的角度看,过滤器模式涉及到三个角色: 抽象过滤器角色:主要定义过滤器的行为; 具体滤器角色:实现或者继承抽象过滤器,完善具体算法; 客户端:客户类提出使用具体类的请求; 话不多说,代码直接撸起来~
SSH框架整合——strut2完成forword跳转 strut2固定是request的请求重定向方式进行跳转 如果界面中用forword来完成跳转: 会报请求错误的异常,所以需要在web.xml中修改strut2的配置 struts2 /* FORWORD REQUEST 这样既可以接收request请求,又...
相关文章
- 微信公众号平台图片上传失败不知道是哪张_看公众号的同时回微信
- DEDECMS织梦后台编辑器增加MP4视频上传功能的解决方法
- vue上传文件到Minio
- 文件上传测试:Windows 创建指定大小的文件
- (小说版)【简历优化平台-2】四个部分初显现,上传按钮打头前
- pytest + yaml 框架 -17.文件上传功能
- 【git】使用git上传文件到仓库失败bug记录
- 数据库开发知识:SpringBoot 怎么集成MongoDB实现文件上传功能
- 利用Java API通过路径过滤上传多文件至HDFS详解大数据
- jsp使用uploadify前台上传文件详解编程语言
- 阿里云图片压缩上传代码详解编程语言
- Spring MVC环境中的文件上传功能实现详解编程语言
- YouTube取消社区上传字幕功能 现在更多创作者正在自己制作字幕
- MongoDB实现图片上传功能(mongodb上传图片)
- Linux服务器实现文件上传功能(linux服务器上传文件)
- 原因排查及解决方案Mysql上传数据失败(mysql 上传数据失败)
- asp.net上传大文件解决方案
- Javascript&DHTML实例编程(教程)(三)初级实例篇1—上传文件控件实例
- PHP文件上传功能实现代码
- jspSmartUpload实现上传功能代码
- asp.netUpdatePanel实现无刷新上传图片
- Easy.Ajax部分源代码支持文件上传功能,兼容所有主流浏览器
- ecshop批量上传(加入自定义属性)
- IIS7中设置文件上传大小限制设置方法
- thinkphp实现图片上传功能分享
- Thinkphp多文件上传实现方法
- 配置php.ini实现PHP文件上传功能
- ajaxFileUpload.js插件支持多文件上传的方法