最近学习struts2的文件上传和下载,由于书中的方法ServletActionContext.getRequest().getRealPath("/")已经过时,所以寻找了其它获取工程根目录方法。

    在尝试过程中曾试过使用相对路径方法,结果相对路径为eclipse的根目录,所以此方法行不通。

    由于工程路径封装在了Servlet的ServletContext中,我们可以在Action中直接访问Servlet API进行操作:struts2提供的Actioncontext不能直接访问servlet API实例,所以为了直接访问servlet API,struts2提供了如下三个接口:

    1. SerlvetContextAware:实现接口的Action可以访问web应用的ServletContext实例。

    2. ServletRequestAware:实现接口的Action可以访问用户请求的HttpServletRequest实例。

    3. ServletResponseAware: 实现接口的Action可以访问服务器响应的HttpServletResponse实例。

    获取路径需要让Action实现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中判断是否存在该文件夹,若不存在则创建该文件夹。此函数获取的路径后不带"\\"。

若获取跟目录则将files换成"/"即可。