`
visionary_2006
  • 浏览: 129067 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

《struts2权威指南》学习笔记之struts2文件上传

阅读更多
struts2没有提供自己的请求解析器,也就是说,struts2不会自己区处理multipart/form-data的请求,它需要调用其他请求解析器,将HTTP请求中的表单域解析出来,但struts2在原有的上传解析器上作了进一步封装,更进一步简化了文件上传

Struts2的struts.properties配置文件中,配置struts2的上传文件解析器

struts.multipart.parser=jakarta  (srtuts2默认),也可以设置为常用的cos,pell等



配置上传页面:
引用
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GBK" />
<title>简单的文件上传</title>
</head>
<body>
<form action="upload.action" method="post" enctype="multipart/form-data">
      文件标题:<input type="text" name="title" /><br>
      选择文件:<input type="file" name="upload" /><br>
    <input value="上传" type="submit" />
</form>
</body>
</html>



配置上传action

引用

package lee;

import com.opensymphony.xwork2.Action;
import org.apache.struts2.ServletActionContext;
import java.io.File;
import java.io.*;

import com.opensymphony.xwork2.ActionSupport;



public class UploadAction extends ActionSupport
...{
    private String title;
    private File upload;
    private String uploadContentType;
    private String uploadFileName;

    //接受依赖注入的属性
    private String savePath;
    //接受依赖注入的方法
    public void setSavePath(String value)
    ...{
        this.savePath = value;
    }

    private String getSavePath() throws Exception
    ...{
        return ServletActionContext.getRequest().getRealPath(savePath);
    }
   
    public void setTitle(String title) ...{
        this.title = title;
    }

    public void setUpload(File upload) ...{
        this.upload = upload;
    }

    public void setUploadContentType(String uploadContentType) ...{
        this.uploadContentType = uploadContentType;
    }

    public void setUploadFileName(String uploadFileName) ...{
        this.uploadFileName = uploadFileName;
    }

    public String getTitle() ...{
        return (this.title);
    }

    public File getUpload() ...{
        return (this.upload);
    }

    public String getUploadContentType() ...{
        return (this.uploadContentType);
    }

    public String getUploadFileName() ...{
        return (this.uploadFileName);
    }
    @Override
    public String execute() throws Exception
    ...{
        System.out.println("开始上传单个文件-----------------------");
        System.out.println(getSavePath());
        System.out.println("==========" + getUploadFileName());
        System.out.println("==========" + getUploadContentType());
        System.out.println("==========" + getUpload());
        //以服务器的文件保存地址和原文件名建立上传文件输出流
        FileOutputStream fos = new FileOutputStream(getSavePath() + "\" + getUploadFileName());
        FileInputStream fis = new FileInputStream(getUpload());
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = fis.read(buffer)) > 0)
        ...{
            fos.write(buffer , 0 , len);
        }
        return SUCCESS;
    }
}



struts配置文件

引用

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">
   
<struts>

    <constant name="struts.custom.i18n.resources" value="globalMessages"/>
    <constant name="struts.i18n.encoding" value="GBK"/>

    <package name="lee" extends="struts-default">
   
        <action name="upload" class="lee.UploadAction">
            <param name="savePath">/upload</param>
            <result>/succ.jsp</result>   
        </action>       
    </package>
</struts>   



web.xml

引用

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <filter>
      <filter-name>struts2</filter-name>
      <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
    </filter>
    <filter-mapping>
      <filter-name>struts2</filter-name>
      <url-pattern>/*</url-pattern>
    </filter-mapping>


    <filter>
      <filter-name>struts-cleanup</filter-name>
      <filter-class>org.apache.struts2.dispatcher.ActionContextCleanUp</filter-class>
    </filter>
    <filter-mapping>
      <filter-name>struts-cleanup</filter-name>
      <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>



这里web.xml多配置了一个ActionContextCleanUp的配置,这个类是一个filter,他的作用是方便strut2与 sitemesh整合,与文件上传本没有关系,但不加载这个filter,可能在上传出出现莫名的异常,加入后就稳定了,可能是strut2的bug吧

文件上传工程页面:

引用

<%...@ page language="java" contentType="text/html; charset=GBK"%>
<%...@taglib prefix="s" uri="/struts-tags"%>
<html>
    <head>
        <title>上传成功</title>
    </head>
    <body>
        上传成功!<br>
        文件标题:<s:property value=" + title"/><br>
        文件为:<img src="<s:property value="'upload/' + uploadFileName"/>"/><br>
    </body>
</html>



运行,选择一个jpg图片,提交,就可以看到上传的页面显示出来了

通常,我们希望限定上传文件的类型,比如说只能上传图片,还需要进一步改造

首先改造Action,增加一个属性和一个方法,属性表示允许上传的文件类型,方法进行验证,是否允许上传

引用

package lee;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;

import org.apache.struts2.ServletActionContext;
import java.io.*;

import com.opensymphony.xwork2.ActionSupport;

/** *//**
* @author  yeeku.H.lee kongyeeku@163.com
* @version  1.0
* <br>Copyright (C), 2005-2008, yeeku.H.Lee
* <br>This program is protected by copyright laws.
* <br>Program Name:
* <br>Date:
*/

public class UploadAction extends ActionSupport
...{
    private String title;
    private File upload;
    private String uploadContentType;
    private String uploadFileName;
    private String allowTypes;

    //接受依赖注入的属性
    private String savePath;
    //接受依赖注入的方法
    public void setSavePath(String value)
    ...{
        this.savePath = value;
    }

    private String getSavePath() throws Exception
    ...{
        return ServletActionContext.getRequest().getRealPath(savePath);
    }
   
    public void setTitle(String title) ...{
        this.title = title;
    }

    public void setUpload(File upload) ...{
        this.upload = upload;
    }

    public void setUploadContentType(String uploadContentType) ...{
        this.uploadContentType = uploadContentType;
    }

    public void setUploadFileName(String uploadFileName) ...{
        this.uploadFileName = uploadFileName;
    }

    public String getTitle() ...{
        return (this.title);
    }

    public File getUpload() ...{
        return (this.upload);
    }

    public String getUploadContentType() ...{
        return (this.uploadContentType);
    }

    public String getUploadFileName() ...{
        return (this.uploadFileName);
    }
    @Override
    public String execute() throws Exception
    ...{
        System.out.println("开始上传单个文件-----------------------");
        System.out.println(getSavePath());
        System.out.println("==========" + getUploadFileName());
        System.out.println("==========" + getUploadContentType());
        System.out.println("==========" + getUpload());
       
        //判断是否允许上传
        String filterResult=filterType(this.getAllowTypes().split(","));
        if(filterResult!=null)...{
            ActionContext.getContext().put("typeError", "您要上传的文件类型不正确");
            return filterResult;
        }
        //以服务器的文件保存地址和原文件名建立上传文件输出流
        FileOutputStream fos = new FileOutputStream(getSavePath() + "\" + getUploadFileName());
        FileInputStream fis = new FileInputStream(getUpload());
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = fis.read(buffer)) > 0)
        ...{
            fos.write(buffer , 0 , len);
        }
        return SUCCESS;
    }
   
    public String filterType(String[] types)...{
        String fileType=this.getUploadContentType();
        for(String type:types)...{
            if(type.equals(fileType))...{
                return null;
            }
        }
        return INPUT;
    }

    public String getAllowTypes() ...{
        return allowTypes;
    }

    public void setAllowTypes(String allowTypes) ...{
        this.allowTypes = allowTypes;
    }
}



修改struts.xml定义文件类型及错误返回页面:

引用

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">
   
<struts>

    <constant name="struts.custom.i18n.resources" value="globalMessages"/>
    <constant name="struts.i18n.encoding" value="GBK"/>

    <package name="lee" extends="struts-default">
   
        <action name="upload" class="lee.UploadAction">
            <param name="allowTypes">image/bmp,image/jpg,image/png,image/gif,image/jpeg</param>
            <param name="savePath">/upload</param>
            <result>/succ.jsp</result>   
            <result name="input">/upload.jsp</result>   
        </action>       
    </package>
</struts>   



修改上传页面:upload.jsp
引用


<%...@ page language="java" contentType="text/html; charset=GBK"%>
<%...@taglib prefix="s" uri="/struts-tags"%>
<%...@ page isELIgnored="false" %>
<%...@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>


<head>

<meta http-equiv="Content-Type" content="text/html; charset=GBK" />
<title></title>
</head>
<body>
${requestScope.typeError}
<form action="upload.action" method="post" enctype="multipart/form-data">
      <input type="text" name="title" /><br>
      <input type="file" name="upload" /><br>
    <input value="upload" type="submit" />
</form>
</body>
</html>



文章来源:http://blog.csdn.net/daryl715/archive/2008/02/28/2127229.aspx
分享到:
评论

相关推荐

    Struts2权威指南完整版

    改为使用Convention插件提供“零配置”,Struts 2.1新增了Portlet支持……为了让众多Struts学习者、工作者快速从Struts 2.0的开发升级到Struts 2.1,笔者升级了《Struts 2权威指南》,第二版改写了第一版中所有程序...

    Struts2权威指南-带目录索引完整版.pdf

    Struts2权威指南 带目录索引完整版

    [Struts 2权威指南--基于WebWork核心的MVC开发(高清完整版) 1/12

    第1章 Struts 2概述,第2章 Struts 2下的HelloWorld,第3章 Struts 2基础,第4章 深入Struts 2,第5章 Struts 2的类型转换,第6章 文件的上传和下载.,第7章 Struts 2的拦截器,第8章 Struts 2的输入校验,9.2 ...

    Struts2权威指南 加源码

    本《Struts2权威指南》结合了源码分析,旨在帮助读者深入理解Struts2的工作原理以及如何在实际项目中有效利用它。 首先,Struts2的核心功能包括动作映射、结果类型、拦截器等。动作映射允许开发者将URL请求与特定的...

    Struts2权威指南.pdf 清晰中文完整版

    这本书《Struts2权威指南》显然是针对想要学习或深入理解Struts2框架的开发者设计的。下面我们将详细探讨Struts2的一些核心知识点。 1. **Struts2框架概述**:Struts2是Apache软件基金会的开源项目,它是Struts1的...

    struts2权威指南源代码

    Struts2是Apache软件基金会旗下的一个开源框架,用于构建企业级...通过深入研究《Struts2权威指南》的源代码,读者不仅可以学习到Struts2的基本用法,还能掌握其高级特性和最佳实践,从而更好地应用于实际项目开发中。

    Struts2权威指南完整版PDF

    Struts2权威指南完整版PDFStruts2权威指南完整版PDF

    Struts2权威指南完整版.pdf

    Struts2权威指南完整版.pdf 不错的Struts入门教程 也可以当工具书

    struts2 权威指南完整版PDF

    这本书《Struts2权威指南》全面深入地介绍了这个框架的核心概念、配置、最佳实践以及常见问题的解决方案。以下是基于该书和Struts2框架的一些主要知识点: 1. **Struts2框架基础**:Struts2是Struts1的升级版,解决...

    Struts2权威指南(完整版)含源码part13

    Struts2权威指南(完整版)含源码 Struts2权威指南(完整版)含源码

    Struts2权威指南全部源码

    总的来说,"Struts2权威指南全部源码"是一份宝贵的资源,通过深入学习和实践,你可以提升对Struts2的理解,掌握Web应用开发的关键技能。但同时,也要准备好面对可能的挑战,因为学习过程中遇到错误是正常的,关键...

    Struts2.1权威指南——基于WebWork核心的MVC开发.zip

    《Struts 2.1权威指南》特点为:1.经验丰富,针对性强 《Struts 2.1权威指南》凝聚了作者大量的实际开发经验和感悟。作者依照读者的学习规律,首先介绍基本概念和基本操作,然后对内容进行深入讲解。 2.讲解具体,...

    Struts 2权威指南源码.rar

    这个"Struts 2权威指南源码.rar"压缩包文件包含了《Struts 2权威指南》一书中的示例代码,这些源码对于学习和理解Struts 2框架的工作原理非常有帮助。 在深入探讨源码之前,让我们先了解Struts 2的核心特性: 1. *...

    struts2权威指南 电子书 配套源码-1

    struts2权威指南 电子书 配套源码 文件大小153mb 分为8个压缩包,每分卷1分,每分卷20兆(最多只让上传20兆,没有办法) struts2权威指南电子书连接:http://sdan250.download.csdn.net/user/sdan250/all/3

    struts2权威指南源码

    Struts2是Apache软件基金会旗下的一个开源框架,它基于Model-View-Controller(MVC)设计模式,为Java EE应用程序提供了强大的控制层解决方案。在深入理解Struts2框架的源码之前,我们需要先对它的基本架构和核心...

    struts2 学习重点笔记

    ### Struts2 学习重点知识点总结 #### 一、Struts2 概念与架构 **1.1 Struts2 简介** - **定义**:Struts2 是 Apache 组织提供的一个基于 MVC 架构模式的开源 Web 应用框架。 - **核心**:Struts2 的核心其实是 ...

    struts2四天的学习笔记

    13. ** strut2四天笔记**:这份学习笔记可能涵盖了以上所有知识点,包括如何创建Action,配置struts.xml,使用OGNL表达式,处理异常,以及实践中的各种技巧和最佳实践。 在四天的学习过程中,你应该通过实践和理解...

    Struts2权威指南

    Struts2权威指南Struts2权威指南Struts2权威指南

    struts2权威指南 struts2权威指南

    本资源《Struts2权威指南》可能是该领域的深度解析书籍,通过多个rar压缩包提供,暗示了内容可能非常详尽且分卷发布。 Struts2的核心是Model-View-Controller(MVC)设计模式,它简化了Java Web开发,使得开发者...

Global site tag (gtag.js) - Google Analytics