java action 获取项目路径_struts2获取工程根目录

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值