最近學(xué)習(xí)struts2的文件上傳和下載,由于書中的方法ServletActionContext.getRequest().getRealPath("/")已經(jīng)過時,所以尋找了其它獲取工程根目錄方法。
在嘗試過程中曾試過使用相對路徑方法,結(jié)果相對路徑為eclipse的根目錄,所以此方法行不通。
由于工程路徑封裝在了Servlet的ServletContext中,我們可以在Action中直接訪問Servlet API進(jìn)行操作:struts2提供的Actioncontext不能直接訪問servlet API實(shí)例,所以為了直接訪問servlet API,struts2提供了如下三個接口:
1. SerlvetContextAware:實(shí)現(xiàn)接口的Action可以訪問web應(yīng)用的ServletContext實(shí)例。
2. ServletRequestAware:實(shí)現(xiàn)接口的Action可以訪問用戶請求的HttpServletRequest實(shí)例。
3. ServletResponseAware: 實(shí)現(xiàn)接口的Action可以訪問服務(wù)器響應(yīng)的HttpServletResponse實(shí)例。
獲取路徑需要讓Action實(shí)現(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換成"/"即可。
創(chuàng)新互聯(lián)www.cdcxhl.cn,專業(yè)提供香港、美國云服務(wù)器,動態(tài)BGP最優(yōu)骨干路由自動選擇,持續(xù)穩(wěn)定高效的網(wǎng)絡(luò)助力業(yè)務(wù)部署。公司持有工信部辦法的idc、isp許可證, 機(jī)房獨(dú)有T級流量清洗系統(tǒng)配攻擊溯源,準(zhǔn)確進(jìn)行流量調(diào)度,確保服務(wù)器高可用性。佳節(jié)活動現(xiàn)已開啟,新人活動云服務(wù)器買多久送多久。
當(dāng)前題目:struts2獲取工程根目錄-創(chuàng)新互聯(lián)
文章源于:http://aaarwkj.com/article0/dopgoo.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供虛擬主機(jī)、定制網(wǎng)站、網(wǎng)站改版、微信小程序、電子商務(wù)、動態(tài)網(wǎng)站
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容