,,最近学习struts2的文件上传和下载,由于书中的方法ServletActionContext.getRequest () .getRealPath(“/?已经过时,所以寻找了其它获取工程根目录方法。
,,在尝试过程中曾试过使用相对路径方法,结果相对路径为eclipse的根目录,所以此方法行不通。
,,由于工程路径封装在了Servlet的ServletContext中,我们可以在行动中直接访问Servlet API进行操作:struts2提供的Actioncontext不能直接访问Servlet API实例,所以为了直接访问Servlet API, struts2提供了如下三个接口:
,,1. SerlvetContextAware:实现接口的行动可以访问网络应用的ServletContext实例。
,,2. ServletRequestAware:实现接口的行动可以访问用户请求的HttpServletRequest实例。
,,3.ServletResponseAware:实现接口的行动可以访问服务器响应的HttpServletResponse实例。
,,获取路径需要让行动实现SerlvetContextAware接口,行动代码如下:
,,,
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 标题; private File 还是; servletcontext private ServletContext ; public String  getTitle (), { return 标题; } public void  setTitle (String 标题),{ 时间=this.title 标题; } public File  getUploadFile (), { return 还是; } public void  setUploadFile (File 还是),{ 时间=this.uploadFile 还是; } ,,,private String getPath () { ,,,,,,,return servletcontext.getRealPath(“文件”); ,,,} ,,,, ,,,public String 执行(),throws Exception { ,,,,String name =, getTitle (); ,,,,String path =, getPath (), +,“\ \”, +, getTitle (); ,,,,FileOutputStream fos =, new FileOutputStream(路径); ,,,,FileInputStream fis =, new FileInputStream (getUploadFile ()); ,,,,时间=byte [], buffer new 字节[1024]; ,,,,int 兰; ,,,,而(,(=len fis.read(缓冲)),祝辞,0){ ,,,,fos.write(缓冲区,,0,,len); ,,,,} ,,,,ActionContext.getContext () .put(“路径”,路径); ,,,,return “成功”; ,,,, ,,,} @Override public void  setServletContext (ServletContext arg0), { 时间=this.servletcontext arg0; } }
serlvetcontext.getRealPath(“文件”)为获取根目录下文件文件夹的路径,文件文件夹必须存在,可以在行动中判断是否存在该文件夹,若不存在则创建该文件夹。此函数获取的路径后不带“\ \”。
若获取跟目录则将文件换成“/奔纯伞?/p>