Struts(十一)Struts2的 命名空间与各种配置详解与文件上传

1.package元素的abstract属性表示该包是抽象的,不能直接使用,需要由子包继承才能使用。struts-defult这个package就是abstract的,因此需要我们继承这个包来使用。

2.命名空间,package元素的namespace属性起到命名空间分割的作用。通常将namespace的属性值定义成页面所在的目录名。name属性会被子包用到。namespace是路径名。最后的访问链接:http://localhost:8080/struts2/hello/login.jsp

<package name="frist" extend="struts-defult" namespace="/hello">

3.文件上传,进行文件上传时,必须将表单的method属性设置为post(因为GET支持文件大小是有限制的),将enctype属性设为multipart/form-data

 private String uploadContentType;//上传文件的类型,(Fileupload拦截器传入的参数)
 private File upload;//上传的文件,(Fileupload拦截器传入的参数)
 private String uploadFileName;//上传文件的真实文件名,(Fileupload拦截器传入的参数)

 4.限制文件大小

1)在struts.xml中配置常量,可以实现对所有<action>文件的大小限制

<constant name="struts.multipart.maxSize" value="5000000"/>
5M大小

2)在action下配置拦截器,可以实现单个<action>文件大小的限制


<interceptor-ref name="fileUpload">
    <param name="maximumSize">5000000</param>    
    </interceptor-ref>
    <interceptor-ref name="defaultStack"></interceptor-ref>

5.限制文件类型

<interceptor-ref name="fileUpload">
    <param name="allowedTypes">image/pjpeg,image/jpeg,image/gif,image/png</param>
    <param name="maximumSize">5000000</param>    
    </interceptor-ref>
    <interceptor-ref name="defaultStack"></interceptor-ref>

6.在配置文件内指定上传路径,其次,在UploadAction.java中新建一个变量uploadPath,为其设置set方法。同时在uploadMethod方法中将目标文件夹改为uploadPath.

<action name="UploadAction" class="action.UploadAction" method="uploadMethod">
            <param name="uploadPath">/home/amosli/develop/struts2_learn/</param>
.................
 

例子:fileload.jsp

<body>
    <form action="fileuploadResult.jsp" method="post" enctype="multipart/form-data">
        username:<input type="text" name="username" ><br>
        file:<input type="file" name="file"><br>
        <input type="submit" value="sumbit">
        
    
    </form>

fileuploadResult.jsp

<body>
    <%
        InputStream is = request.getInputStream();
        
        BufferedReader br = new BufferedReader(new InputStreamReader(is));//字符流与字节流的桥接
        
        String buffer = null;
    
        if(null != (buffer=br.readLine()))
        {
            out.print(buffer+"<br>");
        }
        
        br.close();
        is.close();
    
    
    %>
  </body>

4.处理文件上传fileupload组件(表单的method属性设为post,将enctype属性设为multipart/form-data)

我们主要使用Commons-fileupload.jar中的类,commons-io是提供流服务用的,我们没有对它进行操作。

  • FileItem 类 用来封装表单中的元素和数据。
  • ServletFileUpload类 处理表单数据,将数据封装到 FileItem 对象中。

  • DiskFileItemFactory类 设置FileItem 对象的工厂,可以设定缓冲区大小和存放临时文件目录。
  • ServletFileUpload 处理上传的文件的数据,优先保存在缓冲区,如果数据超过了缓冲区大小,则保存到硬盘上,存储在DiskFileItemFactory指定目录下的临时文件。数据都接收完后,它再在从临时文件中将数据写入到上传文件目录下的指定文件中,并删除临时文件。

fileload.jsp

 <form action="FileuploadServlet1" method="post" enctype="multipart/form-data">
        username:<input type="text" name="username" ><br>
        file:<input type="file" name="file"><br>
        file2:<input type="file" name="file2"><br>
        <input type="submit" value="sumbit">
        
    
    </form>

FileuploadServlet1

public class FileuploadServlet1 extends HttpServlet
{
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
    {
        request.setCharacterEncoding("utf-8");
        DiskFileItemFactory factory = new DiskFileItemFactory();
        
        String path = request.getRealPath("/fileupload");//设置文件上传的位置
        
        factory.setRepository(new File(path));//设置临时文件目录
        factory.setSizeThreshold(1024*1024);//设置默认文件的大小
        
        ServletFileUpload upload = new ServletFileUpload(factory);
        List<FileItem> list = null;
        try
        {
            list = (List<FileItem>) upload.parseRequest(request);//解析request请求
        }
        catch (FileUploadException e1)
        {
            e1.printStackTrace();
        }
        try
        {
            for(FileItem item:list)//FileItem包含了文件本身与文本域
            {
                String name = item.getFieldName();//获得name属性的值
                
                if(item.isFormField())//判断是否是文本域
                {
                    String value = item.getString();//获得value属性的值
                    
                    System.out.println(name+":"+value);
                    
                    request.setAttribute(name,value);
                }
                else //为文件本身
                {
                    String value = item.getName();//对于大部分浏览器获得文件名,个别浏览器获得路径
                    
                    int strat = value.lastIndexOf("\");//String 在此实例内的最后一个匹配项的索引位置。
                    String fileName = value.substring(strat+1);//从此实例检索子字符串。子字符串从指定的字符位置开始。
                    
                    request.setAttribute(name,value);
                    
                    item.write(new File(path,fileName));//写入文件
                    
                    InputStream is =item.getInputStream();
                    OutputStream os = new FileOutputStream(new File(path,fileName));
                    
                    byte[] buffer = new byte[400];
                    int length = 0;
                    while(-1 != (length = is.read(buffer)))
                    {
                        os.write(buffer);
                    }
                    os.close();
                    is.close();
} } } catch(Exception e) { e.printStackTrace(); } request.getRequestDispatcher("fileloadResult2.jsp").forward(request,response); } }

 5.Struts2的文件上传,通过两步实现的:

1)首先将客户端上传的文件保存到struts.multipart.saveDir键所指定的目录中,如果该键所对应的目录不存在,那么久保存到javax.servlet.contexe.tempdir环境变量所指定的目录中。

2)Action中所定义的File类型的成员变量file实际上指向的是临时目录中的临时文件,然后在服务器端通过io的方式将临时文件写入到指定的服务器目录中。

(1)单个文件上传

fileupload.jsp

<form action="FileUploadAction" method="post" enctype="multipart/form-data">
    username:<input type="text" name="username"><br>
    
    file:<input type="file" name="file"><br>
    
    <input type="submit" value="submit">
    </form>

FileUploadAction

public class FileUploadAction extends ActionSupport
{
    private String username;
    private File file;
    private String fileFileName;
    private String fileContentType;
    public String getFileFileName()
    {
        return fileFileName;
    }
    public void setFileFileName(String fileFileName)
    {
        this.fileFileName = fileFileName;
    }
    public String getFileContentType()
    {
        return fileContentType;
    }
    public void setFileContentType(String fileContentType)
    {
        this.fileContentType = fileContentType;
    }
    public String getUsername()
    {
        return username;
    }
    public void setUsername(String username)
    {
        this.username = username;
    }
    public File getFile()
    {
        return file;
    }
    public void setFile(File file)
    {
        this.file = file;
    }
    
    @Override
    public String execute() throws Exception
    {
        InputStream is = new FileInputStream(file);
        String path = ServletActionContext.getRequest().getRealPath("/fileupload");
        System.out.println(fileFileName);
        OutputStream os = new FileOutputStream(new File(path,fileFileName));
        
        byte[] buffer = new byte[400];
        int length = 0;
        while(-1 != (length = is.read(buffer)))
        {
            os.write(buffer,0,length);
        }
        
        os.close();
        is.close();
        
        
        
        return SUCCESS;
    }
}

struts.xml

<action name="FileUploadAction" class="com.liule.action.FileUploadAction">
        <result name="success">/fileuploadResult.jsp</result>
    
    </action>
        

fileuploadResult.jsp

<body>
       username:<s:property value="username"/><br>
       file:<s:property value="fileFileName"/>
  </body>

(2)多个文件上传

fileupload2.jsp

<form action="FileUploadAction2" method="post" enctype="multipart/form-data">
    username:<input type="text" name="username"><br>
    
    file:<input type="file" name="file"><br>
    file:<input type="file" name="file"><br>
    file:<input type="file" name="file"><br>
    
    <input type="submit" value="submit">
    </form>

FileUploadAction2

public class FileUploadAction2 extends ActionSupport
{
    private String username;
    private List<File> file;
    private List<String> fileFileName;
    private List<String> fileContentType;
    public String getUsername()
    {
        return username;
    }
    public void setUsername(String username)
    {
        this.username = username;
    }
    public List<File> getFile()
    {
        return file;
    }
    public void setFile(List<File> file)
    {
        this.file = file;
    }
    public List<String> getFileFileName()
    {
        return fileFileName;
    }
    public void setFileFileName(List<String> fileFileName)
    {
        this.fileFileName = fileFileName;
    }
    public List<String> getFileContentType()
    {
        return fileContentType;
    }
    public void setFileContentType(List<String> fileContentType)
    {
        this.fileContentType = fileContentType;
    }
    
    
    @Override
    public String execute() throws Exception
    {
        for(int i = 0 ;i <file.size();i++)
        {
            String path = ServletActionContext.getRequest().getRealPath("/fileupload");
        
            OutputStream os = new FileOutputStream(new File(path,fileFileName.get(i)));
            
            InputStream is = new FileInputStream(file.get(i));
            
            byte[] buffer = new byte[400];
            int length =0;
            while(-1 != (length=is.read(buffer)))
            {
                os.write(buffer,0,length);
            }
            
            is.close();
            os.close();
        }
        
        
        
        return SUCCESS;
    }
        
}

fileupload2Result.jsp

<body>
    username:<s:property value="username"/><br>
    
    <s:iterator value="fileFileName" id="f">
        
        file:<s:property value="#f"/><br>    

    
    </s:iterator>
  </body>

6.文件下载

fileDownload.jsp

<body>
    <a href="DownloadFile.action">文件下载</a>
  </body>

DownloadAction

public class DownloadAction extends ActionSupport
{
    
    public InputStream getDownloadFile()
    {
        return ServletActionContext.getServletContext().getResourceAsStream("/fileupload/新建文本文档 (2).zip");
    }
    @Override
    public String execute() throws Exception
    {
        return SUCCESS;
    }
}

struts.xml

<action name="DownloadFile" class="com.liule.action.DownloadAction">
        <result type="stream">
            <param name="contextDisPosition">attachment;filename="新建文本文档 (2).zip"</param>
            <param name="inputName">downloadFile</param>
        </result>
    
    </action>

灵活下载:

downloadFile.jsp

<body>
       <a href="DownloadFile.action?number=1">下载</a>
  </body>

DownloadFile

public class DownloadFile extends ActionSupport
{
    private int number;
    private String filename;
    
    public int getNumber()
    {
        return number;
    }
    public void setNumber(int number)
    {
        this.number = number;
    }
    
    public String getFilename()
    {
        return filename;
    }
    public void setFilename(String filename)
    {
        this.filename = filename;
    }
    public InputStream getDownloadFile()
    {
        if(1 == number)
        {
            this.filename="新建文本文档 (2).txt";
            try
            {
                this.filename = new String(this.filename.getBytes("gbk"),
                        "8859_1");
            }
            catch (UnsupportedEncodingException e)
            {
                
                e.printStackTrace();
            }
            ServletActionContext.getServletContext().getResourceAsStream("/file/新建文本文档 (2).txt");
        }
        else
        {
            this.filename="新建文本文档 (2).zip";
            try
            {
                this.filename = new String(this.filename.getBytes("gbk"),
                        "8859_1");
            }
            catch (UnsupportedEncodingException e)
            {
                
                e.printStackTrace();
            }
            ServletActionContext.getServletContext().getResourceAsStream("/file/新建文本文档 (2).zip");
        }
        
        return null;
        
    }
    
    @Override
    public String execute() throws Exception
    {
        return SUCCESS;
    }
}

struts.xml

    <action name="DownloadFile" class="com.liule.action.DownloadFile">
                <result type="stream">
                    <param name="contentDisposition">attachment;filename=${filename}</param>
                    <param name="inputName">downloadFile</param>
                
                </result>
            
            
            </action>

 http://www.cnblogs.com/liunanjava/p/4389661.html

原文地址:https://www.cnblogs.com/liu-Gray/p/4951780.html