struts2.0(40-50)

 

<action name="register" class="com.test.action.RegisterAction" method="test">

           <result name="success">/success.jsp</result>

           <result name="input">/register2.jsp</result>

           <!-- 增加拦截器或用栈也行 -->

           <interceptor-ref name="auth"></interceptor-ref>

           <interceptor-ref name="defaultStack"></interceptor-ref>

       </action>

 

 

文件上传和下载:

 

页面: enctype默认是字符串提交

<form action="result.jsp" method="post" enctype="multipart/form-data">

   

    Information: <input type="text" name="info"><br>

    File: <input type="file" name="file"><br>

   

    <input type="submit" name="submit" value=" submit ">

   

    </form>

 

result.jsp:

<body>

<%

    InputStream is = request.getInputStream();

 

    BufferedReader br = new BufferedReader(new InputStreamReader(is));

   

    String buffer = null;

   

    while((buffer = br.readLine()) != null)

    {

       out.print(buffer + "<br>");    

    }

%>

</body>

 

文件上传会遇到拦截器:一种是不用struts的包.注释web.xml

<!-- 

    <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>

 

-->

 

</web-app>

 

 

URL解码:

public class DecoderTest

{

 

    public static void main(String[] args)throws Exception

    {

       String str = "C%3A%5CDocuments+and+Settings%5Czhanglong%5C%D7%C0%C3%E6%5CNOTICE.txt";

      

       String result = URLDecoder.decode(str,"gbk");

      

       System.out.println(result);

    }

 

}

 

 

Struts文件上传(apche 方式)

加入包:

commons-fileupload-1.2.1.jar

commons-io-1.4.jar

 

页面:

<form action="/struts2/UploadServlet" method="post" enctype="multipart/form-data">

 

username: <input type="text" name="username"><br>

 

password: <input type="password" name="password"><br>

 

file1: <input type="file" name="file1"><br>

 

file2: <input type="file" name="file2"><br>

 

<input type="submit" value="submit">

 

</form>

 

建立servelet

package com.test.servlet;

 

import java.io.File;

import java.io.IOException;

import java.util.List;

 

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

 

import org.apache.commons.fileupload.FileItem;

import org.apache.commons.fileupload.disk.DiskFileItemFactory;

import org.apache.commons.fileupload.servlet.ServletFileUpload;

 

public class UploadServlet extends HttpServlet

{

 

    @SuppressWarnings("unchecked")

    public void doPost(HttpServletRequest request, HttpServletResponse response)

           throws ServletException, IOException

    {

       //创建工厂

       DiskFileItemFactory factory = new DiskFileItemFactory();

       String path = request.getRealPath("/upload");

        //设置临时存储目录

       factory.setRepository(new File(path));

        //设置超出大小,小于超出大小就放到内存,否则建立临时文件存放

       factory.setSizeThreshold(1024 * 1024);//1M

        //处理上传

       ServletFileUpload upload = new ServletFileUpload(factory);

       try

       {

           //接受传送信息

           List<FileItem> list = upload.parseRequest(request);

 

           for (FileItem item : list)

           {

              //判断是否是文件类型

              if (item.isFormField())

              {

                  String name = item.getFieldName();

 

                  String value = item.getString("gbk");

 

                  System.out.println(name);

 

                  request.setAttribute(name, value);

              }

              else//文件类型的操作

              {

                  String name = item.getFieldName();

                    //File表单的路径

                  String value = item.getName();

 

                  int start = value.lastIndexOf("//");

 

                  String fileName = value.substring(start + 1);

                    //处理名称

                  request.setAttribute(name, fileName);

                  //处理流

                  item.write(new File(path,fileName));

                 

 

//                OutputStream os = new FileOutputStream(new File(path,

//                       fileName));

//

//                InputStream is = item.getInputStream();

//

//                byte[] buffer = new byte[400];

//

//                int length = 0;

//

//                while ((length = is.read(buffer)) > 0)

//                {

//                   os.write(buffer, 0, length);

//                }

//

//                os.close();

//

//                is.close();

 

              }

           }

 

       }

 

       catch (Exception ex)

       {

           ex.printStackTrace();

       }

       request.getRequestDispatcher("upload/result2.jsp").forward(request,

              response);

 

    }

 

}

接收流:

<body>

 

<form action="/struts2/UploadServlet" method="post" enctype="multipart/form-data">

 

username: <input type="text" name="username"><br>

 

password: <input type="password" name="password"><br>

 

file1: <input type="file" name="file1"><br>

 

file2: <input type="file" name="file2"><br>

 

<input type="submit" value="submit">

 

</form>

 

Struts文件上传(struts2 方式)

提交页面:

<%@ page language="java" contentType="text/html; charset=GB18030"

    pageEncoding="GB18030"%>

   

<%@ 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=GB18030">

<title>Insert title here</title>

 

<script type="text/javascript">

 

function addMore()

{

    var td = document.getElementById("more");

   

    var br = document.createElement("br");

    var input = document.createElement("input");

    var button = document.createElement("input");

   

    input.type = "file";

    input.name = "file";

   

    button.type = "button";

    button.value = "Remove";

   

    button.onclick = function()

    {

       td.removeChild(br);

       td.removeChild(input);

       td.removeChild(button);

    }

   

    td.appendChild(br);

    td.appendChild(input);

    td.appendChild(button);

   

}

 

</script>

 

</head>

 

<body>

 

    <table align="center" width="50%">

           <tr>

              <td>

 

                  <s:fielderror cssStyle="color:red" />

 

              </td>

           </tr>

       </table>

 

 

       <s:form action="upload" theme="simple" enctype="multipart/form-data">

 

           <table align="center" width="50%" border="1">

              <tr>

                  <td>

                     username

                  </td>

                  <td>

                     <s:textfield name="username"></s:textfield>

                  </td>

              </tr>

 

              <tr>

                  <td>

                     password

                  </td>

                  <td>

                     <s:password name="password"></s:password>

                  </td>

              </tr>

 

 

              <tr>

                  <td>

                     file

                  </td>

             <!—多文件文件name要是一样的-->

                  <td id="more">

                     <s:file name="file"></s:file><input type="button" value="Add More.." onclick="addMore()">

                  </td>

              </tr>

             

              <tr>

                  <td>

                     <s:submit value=" submit "></s:submit>

                  </td>

 

                  <td>

                     <s:reset value=" reset "></s:reset>

                  </td>

              </tr>

           </table>

 

       </s:form>

 

</body>

 

</html>

 

 

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>

<!—全局属性的设置都在struts核心包里的default.properties;结果类型和拦截器都在struts-default.xml -->

    <!-- 国际化资源文件 -->

    <constant name="struts.custom.i18n.resources" value="message"></constant>

    <!-- 解决乱码问题 -->

    <constant name="struts.i18n.encoding" value="gbk"></constant>

    <!-- 设置临时目录 -->

    <constant name="struts.multipart.saveDir" value="c:/"></constant>

   

    <package name="struts2" extends="struts-default">

      

       <global-results>

           <result name="login" type="redirect">/login2.jsp</result>

       </global-results>

 

       <action name="upload" class="com.test.action.UploadAction">

           <result name="success">/uploadResult.jsp</result>

           <result name="input">/upload.jsp</result>

    <!-- 应用内置拦截器,拦截非法文件,最大大小,和文件类型 -->

           <interceptor-ref name="fileUpload">

              <param name="maximumSize">409600</param>

               <param name="allowedTypes">application/vnd.ms-powerpoint</param>

           </interceptor-ref>

           <interceptor-ref name="defaultStack"></interceptor-ref>

       </action>

      

    </package>

 

</struts>

上传AcTION

 

package com.test.action;

 

import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.InputStream;

import java.io.OutputStream;

import java.util.List;

 

import org.apache.struts2.ServletActionContext;

 

import com.opensymphony.xwork2.ActionSupport;

 

public class UploadAction extends ActionSupport

{

    private String username;

 

    private String password;

//要是单文件使用private File file;也可以使用数组的形式File[] file

 

    private List<File> file;

  //namestruts2里面的匹配格式文件名称+FileName,类型也一样,然后被自动注入进来

    private List<String> fileFileName;

 

    private List<String> fileContentType;

生成getset方法

   

    @Override

    public String execute() throws Exception

    {

//要是单文件使用去掉for循环

 

       for (int i = 0; i < file.size(); ++i)

       {

//要是单文件使用InputStream is = new FileInputStream(file);

 

           InputStream is = new FileInputStream(file.get(i));

 

           String root = ServletActionContext.getRequest().getRealPath(

                  "/upload");

//要是单文件使用his.getFileFileName()

           File destFile = new File(root, this.getFileFileName().get(i));

 

           OutputStream os = new FileOutputStream(destFile);

 

           byte[] buffer = new byte[400];

 

           int length = 0;

 

           while ((length = is.read(buffer)) > 0)

           {

              os.write(buffer, 0, length);

           }

 

           is.close();

 

           os.close();

       }

 

       return SUCCESS;

 

接收页面uploadResult.jsp

<%@ taglib prefix="s" uri="/struts-tags" %>

<body>

username: <s:property value="username"/><br>

 

password: <s:property value="password"/><br>

 

file: <s:property value="fileFileName"/>

</body>

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章