1. 程式人生 > >Struts2攔截器和檔案上傳

Struts2攔截器和檔案上傳

 

攔截器

首先需要建立一個攔截器OneInterceptor可以實現implements Interceptor介面
      也可以繼承extends AbstractInterceptor類注意這裡用的是xwork2包下面的

package zking.web;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;

public class OneInterceptor implements Interceptor {
    @Override
    public void destroy() {
/**
 * 攔截器銷燬
 */
    }

    @Override
    public void init() {
        System.out.println("攔截器初始化");
    }

    @Override
    public String intercept(ActionInvocation actionInvocation) throws Exception {
        System.out.println(actionInvocation.getClass().getName());
   /**
   * 執行方法
      */
        String invoke = actionInvocation.invoke();
        System.out.println("方法執行完畢");
        return null;
    }

然後在struts的配置檔案中配置Interceptor

    <interceptors>
            <interceptor name="oneInterceptor" class="zking.web.OneInterceptor"></interceptor>
        </interceptors>

然後在需要引用Interceptor的action引用就可也了

      <action name="loginaction" class="zking.web.LoginAction">
            <interceptor-ref name="oneInterceptor"></interceptor-ref>
            <result name="success">/success.jsp</result>
        </action>

攔截器和過濾器的區別用一張圖來表示畫的有點醜大家理解一下

上傳下載檔案

首先繼承Baseaction

package zking.web;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;

/**
 * 每一個開發的子控制器要用的屬性都定義在通用的action中。
 * @author Administrator
 *
 */
public class BaseAction implements ServletRequestAware, ServletResponseAware{
	/**
	 * 為了傳值使用
	 */
	protected HttpServletResponse response;
	protected HttpServletRequest request;
	protected HttpSession session;
	protected ServletContext application;
	
	/**
	 * 為了配置跳轉頁面所用
	 */
	protected final static String SUCCESS = "success";
	protected final static String FAIL = "fail";
	protected final static String LIST = "list";
	protected final static String ADD = "add";
	protected final static String EDIT = "edit";
	protected final static String DETAIL = "detail";
	
	/**
	 * 具體傳值欄位	後端向jsp頁面傳值所用欄位
	 */
	protected Object result;
	protected Object msg;
	protected int code;

	public Object getResult() {
		return result;
	}

	public Object getMsg() {
		return msg;
	}

	public int getCode() {
		return code;
	}

	@Override
	public void setServletResponse(HttpServletResponse arg0) {
		this.response = arg0;
		
	}

	@Override
	public void setServletRequest(HttpServletRequest arg0) {
		this.request = arg0;
		this.session = arg0.getSession();
		this.application = arg0.getServletContext();
	}
	

}

多個檔案上傳

package zking.web;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;

/**
 * 檔案上傳的三種形式
 * 1.上傳的檔案以2進位制的形式儲存到資料庫中 工作流框架
 * 2.上傳的檔案儲存到伺服器的指定硬碟 (cpu塊 硬碟大)
 * 3.將上傳的檔案儲存到tomcat伺服器中(對應的靜態資源伺服器 上線不重啟)
 *
 */
public class Fileaction extends  BaseAction{

    private File file;
    /**
     * 檔名
     */
    private String fileFileName;
    /**
     * 檔案型別
     */
    private String fileContentType;
    /**
     * 虛擬路徑
     */
    private  String   serverDir="/upload";

    public File getFile() {
        return file;
    }

    public void setFile(File file) {
        this.file = file;
    }

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

    /**
     * 上傳圖片到伺服器
     * @return
     */
    public String upload() throws IOException {
        System.out.println("名字" + fileFileName);
        System.out.println("型別" + fileContentType);
        //真實路徑
        String realPath = getRealPath(serverDir + "/" + fileFileName);
        System.out.println("真實路徑"+realPath);
        //複製
        FileUtils.copyFile(file, new File(realPath));
        return "success";
    }

    /**
     * 獲取檔案的真實路徑
     * @return
     */
    private String  getRealPath(String  path){

        return  this.request.getServletContext().getRealPath(path);
}

    /**
     *
     * @return
     */
    public  String SaveAs() throws IOException {
        //資料庫獲得這裡用的死資料實際上是從資料庫獲得
        String filename = "stationmaster_img.png";
        String filetype="image/png";
        response.setContentType(filetype);
        response.setHeader("Content-Disposition","attachment;filename=" + filename);
        String realPath=getRealPath(serverDir + "/" + filename);
        FileUtils.copyFile(new File(realPath),response.getOutputStream());
        return null;
    }

    /**
     * 開啟圖片
     * @return
     */
    public String OPenAs() throws IOException {
        //資料庫獲得
        String filename = "stationmaster_img.png";
        String filetype="image/png";
        response.setContentType(filetype);
        response.setHeader("Content-Disposition","filename=" + filename);
        String realPath=getRealPath(serverDir + "/" + filename);
        FileUtils.copyFile(new File(realPath),response.getOutputStream());
        return null;
    }
}
   private File[] file;
    private String[] fileFileName;
    private String[] fileContentType;
    private String serverDir = "/upload";

    public File[] getFile() {
        return file;
    }

    public void setFile(File[] file) {
        this.file = file;
    }

    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;
    }
    /**
     * 獲取資料夾的真實路徑
     *
     * @param Path
     * @return
     */
    private String getRealPath(String Path) {
        return this.request.getServletContext().getRealPath(Path);
    }



    /**
     * 上傳
     *
     * @return
     */
    public String upload() throws IOException {
        for (int i = 0; i < file.length; i++) {
            System.out.println("名字" + fileFileName[i]);
            System.out.println("型別" + fileContentType[i]);
            //真實路徑  ,檔名前面加上uuid是因為可能會因為檔名相同而覆蓋
            String realPath = getRealPath(serverDir + "/" + UUID.randomUUID().toString() +fileFileName[i]);
            System.out.println(realPath);
            //複製
            FileUtils.copyFile(file[i], new File(realPath));
        }


        return "success";
    }