struts2获取工程根目录-创新互联

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

商城ssl适用于网站、小程序/APP、API接口等需要进行数据传输应用场景,ssl证书未来市场广阔!成为创新互联的ssl证书销售渠道,可以享受市场价格4-6折优惠!如果有意向欢迎电话联系或者加微信:13518219792(备注:SSL证书合作)期待与您的合作!

  在尝试过程中曾试过使用相对路径方法,结果相对路径为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换成"/"即可。

创新互联www.cdcxhl.cn,专业提供香港、美国云服务器,动态BGP最优骨干路由自动选择,持续稳定高效的网络助力业务部署。公司持有工信部办法的idc、isp许可证, 机房独有T级流量清洗系统配攻击溯源,准确进行流量调度,确保服务器高可用性。佳节活动现已开启,新人活动云服务器买多久送多久。


网站题目:struts2获取工程根目录-创新互联
本文URL:http://myzitong.com/article/dopgoo.html