热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

修正Strut2自带上传拦截器功能

Struts2字典的FileUploadInterceptor拦截器主要帮助获取上传文件的ContentType、fileName、文件对象。如果开发人员在开发过程中使用。则需要设置s
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>> fileParameterMap = new HashMap>>();//文件值对 //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 acceptedFiles = new ArrayList(files.length);
                                                List acceptedCOntentTypes= new ArrayList(files.length);
                                                List acceptedFileNames = new ArrayList(files.length);
                                                List renderNames = new ArrayList(files.length);
                                                String cOntentTypeName= inputName + "ContentType";
                                                String fileNameName = inputName + "FileName";
                                                for (int index = 0; 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> vfl=null;
                                                                if(fileParameterMap.containsKey(inputName)){//是否已存在
                                                                  vfl = fileParameterMap.get(inputName);
                                                                }else{
                                                                  vfl = new ArrayList>();
                                                                  fileParameterMap.put(inputName, vfl);
                                                                }
                                                                  Map value = new HashMap();
                                                                  value.put("contentType", contentType[index]);
                                                                  value.put("fileName", fileName[index]);
                                                                  value.put("acceptedFile", files[index]);
                  vfl.add(value);
                                                                
                                                        }
                                                }

                                                if (!acceptedFiles.isEmpty()) {
                                                        Map 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 uploads = new ArrayList();
        private List uploadFileNames = new ArrayList();
        private List uploadCOntentTypes= new ArrayList();

  public void setFileParameterMap(
      Map>> fileParameterMap) {
    this.fileParameterMap = fileParameterMap;
  }
  public List getUpload() {
                return this.uploads;
        }
        public void setUpload(List uploads) {
                this.uploads = uploads;
        }

        public List getUploadFileName() {
                return this.uploadFileNames;
        }
        
        
        public void setUploadFileName(List uploadFileNames) {
                this.uploadFileNames = uploadFileNames;
        }

        public List getUploadContentType() {
                return this.uploadContentTypes;
        }
        public void setUploadContentType(List contentTypes) {
                this.uploadCOntentTypes= contentTypes;
        }
        private Map>> fileParameterMap;

        public Map>> getFileParameterMap() {
    return fileParameterMap;
  }
        
        public String upload() throws Exception {
          Iterator iter = this.fileParameterMap.keySet().iterator();
    while(iter.hasNext()){
             String key = iter.next();
             List>    vs = this.fileParameterMap.get(key);
             System.out.println("key========"+key);
             for(Map 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
 输出key========upload2
contentType>>application/octet-stream
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


推荐阅读
  • 深入解析Android中的SQLite数据库使用
    本文详细介绍了如何在Android应用中使用SQLite数据库进行数据存储。通过自定义类继承SQLiteOpenHelper,实现数据库的创建与版本管理,并提供了具体的学生信息管理示例代码。 ... [详细]
  • 本文深入探讨了JavaScript中实现继承的四种常见方法,包括原型链继承、构造函数继承、组合继承和寄生组合继承。对于正在学习或从事Web前端开发的技术人员来说,理解这些继承模式对于提高代码质量和维护性至关重要。 ... [详细]
  • 探索古典密码学:凯撒密码、维吉尼亚密码与培根密码
    本文深入探讨古典密码学的基本概念及其主要类型,包括替换式密码和移位式密码。文章详细介绍了凯撒密码、维吉尼亚密码和培根密码的工作原理及加密解密方法。 ... [详细]
  • 本文探讨如何利用Java反射技术来模拟Webwork框架中的URL解析过程。通过这一实践,读者可以更好地理解Webwork及其后续版本Struts2的工作原理,尤其是它们在MVC架构下的角色。 ... [详细]
  • 本文详细介绍了如何在现有的Android Studio项目中集成JNI(Java Native Interface),包括下载必要的NDK和构建工具,配置CMakeLists.txt文件,以及编写和调用JNI函数的具体步骤。 ... [详细]
  • XWiki 数据模型开发指南
    本文档不仅介绍XWiki作为一个增强版的wiki引擎,还深入探讨了其数据模型,该模型可在用户界面层面被充分利用。借助其强大的脚本能力,XWiki的数据模型支持从简单的应用到复杂的系统构建,几乎无需直接接触XWiki的核心组件。 ... [详细]
  • 本文介绍如何在Windows Forms应用程序中使用C#实现DataGridView的多列排序功能,包括升序和降序排序。 ... [详细]
  • 交互式左右滑动导航菜单设计
    本文介绍了一种使用HTML和JavaScript实现的左右可点击滑动导航菜单的方法,适用于需要展示多个链接或项目的网页布局。 ... [详细]
  • Spring Cloud Config 使用 Vault 作为配置存储
    本文探讨了如何在Spring Cloud Config中集成HashiCorp Vault作为配置存储解决方案,基于Spring Cloud Hoxton.RELEASE及Spring Boot 2.2.1.RELEASE版本。文章还提供了详细的配置示例和实践建议。 ... [详细]
  • 在Java应用程序开发过程中,FTP协议被广泛用于文件的上传和下载操作。本文通过Jakarta Commons Net库中的FTPClient类,详细介绍如何实现文件的上传和下载功能。 ... [详细]
  • EasyMock实战指南
    本文介绍了如何使用EasyMock进行单元测试,特别是当测试对象的合作者依赖于外部资源或尚未实现时。通过具体的示例,展示了EasyMock在模拟对象行为方面的强大功能。 ... [详细]
  • 本文探讨了一个特定于 Spring 4.2.5 的问题,即在应用上下文刷新事件(ContextRefreshedEvent)触发时,带有 @Transactional 注解的 Bean 未能正确代理事务。该问题在 Spring 4.1.9 版本中正常运行,但在升级至 4.2.5 后出现异常。 ... [详细]
  • Go语言开发中的常见陷阱与解决方案
    本文探讨了在使用Go语言开发过程中遇到的一些典型问题,包括Map遍历的不确定性、切片操作的潜在风险以及并发处理时的常见错误。通过具体案例分析,提供有效的解决策略。 ... [详细]
  • Java 架构:深入理解 JDK 动态代理机制
    代理模式是 Java 中常用的设计模式之一,其核心在于代理类与委托类共享相同的接口。代理类主要用于为委托类提供预处理、过滤、转发及后处理等功能,以增强或改变原有功能的行为。 ... [详细]
  • 本文将深入探讨如何使用 SQLAlchemy 在数据库模型中定义和操作不同类型的表间关系,包括一对一、一对多及多对多的关系。 ... [详细]
author-avatar
牛涛fd_501
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有