温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

struts2获取工程根目录

发布时间:2020-08-01 04:24:11 来源:网络 阅读:1179 作者:nifu2010 栏目:开发技术

    最近学习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换成"/"即可。


向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI