溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

struts2獲取工程根目錄

發(fā)布時間:2020-08-01 04:24:11 來源:網(wǎng)絡(luò) 閱讀:1156 作者:nifu2010 欄目:開發(fā)技術(shù)

    最近學(xué)習(xí)struts2的文件上傳和下載,由于書中的方法ServletActionContext.getRequest().getRealPath("/")已經(jīng)過時,所以尋找了其它獲取工程根目錄方法。

    在嘗試過程中曾試過使用相對路徑方法,結(jié)果相對路徑為eclipse的根目錄,所以此方法行不通。

    由于工程路徑封裝在了Servlet的ServletContext中,我們可以在Action中直接訪問Servlet API進(jìn)行操作:struts2提供的Actioncontext不能直接訪問servlet API實例,所以為了直接訪問servlet API,struts2提供了如下三個接口:

    1. SerlvetContextAware:實現(xiàn)接口的Action可以訪問web應(yīng)用的ServletContext實例。

    2. ServletRequestAware:實現(xiàn)接口的Action可以訪問用戶請求的HttpServletRequest實例。

    3. ServletResponseAware: 實現(xiàn)接口的Action可以訪問服務(wù)器響應(yīng)的HttpServletResponse實例。

    獲取路徑需要讓Action實現(xiàn)SerlvetContextAware接口,Action代碼如下:

    

package org.struts2;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import javax.servlet.ServletContext;
import org.apache.struts2.util.ServletContextAware;
import com.opensymphony.xwork2.ActionContext;

public class FileUpLoadAction implements ServletContextAware{
	private String title;
	private File uploadFile;
	private ServletContext servletcontext;
	
	public String getTitle() {
		return title;
	}
	public void setTitle(String title) {
		this.title = title;
	}
	public File getUploadFile() {
		return uploadFile;
	}
	public void setUploadFile(File uploadFile) {
		this.uploadFile = uploadFile;
	}
	
    private String getPath(){
        return servletcontext.getRealPath("files");
    }
    
    public String execute() throws Exception {
    	String name = getTitle();
    	String path = getPath() + "\\" + getTitle();
    	FileOutputStream fos = new FileOutputStream(path);
    	FileInputStream fis = new FileInputStream(getUploadFile());
    	byte[] buffer = new byte[1024];
    	int len;
    	while( (len = fis.read(buffer)) > 0){
    		fos.write(buffer, 0, len);
    	}
    	ActionContext.getContext().put("path", path);
    	return "success";
    	
    }
	@Override
	public void setServletContext(ServletContext arg0) {
		this.servletcontext = arg0;
		
	}

}

serlvetcontext.getRealPath("files")為獲取根目錄下files文件夾的路徑,files文件夾必須存在,可以在action中判斷是否存在該文件夾,若不存在則創(chuàng)建該文件夾。此函數(shù)獲取的路徑后不帶"\\"。

若獲取跟目錄則將files換成"/"即可。


向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI