struts2 Action中获取request, response session对象的方法

第一种方式:非Ioc(Spring中的控制反转)方式

ActionContext ctx = ServletActionContext.getContext();
HttpServletRequest req = (HttpServletRequest)ctx.get(ServletActionContext.HTTP_REQUEST);
HttpServletResponse response = (HttpServletResponse)ctx.get(ServletActionContext.HTTP_RESPONSE);
Map session = ctx.getSession();


ServletActionContext.getRequest().setAttribute("msg",obj);

第二种方式:Ioc方式

public class UploadImageAction3 extends ActionSupport implements RequestAware,
SessionAware, ApplicationAware {

private final static String UPLOAD = "/attached";

private Map<String, Object> request;
private Map<String, Object> session;
private Map<String, Object> application;

private File imgFile;

private String imgFileFileName;

private String imgFileContentType;

public String getImgFileFileName() {
return imgFileFileName;
}

public void setImgFileFileName(String imgFileFileName) {
this.imgFileFileName = imgFileFileName;
}

public String getImgFileContentType() {
return imgFileContentType;
}

public void setImgFileContentType(String imgFileContentType) {
this.imgFileContentType = imgFileContentType;
}

public File getImgFile() {
return imgFile;
}

public void setImgFile(File imgFile) {
this.imgFile = imgFile;
}

public void setRequest(Map<String, Object> request) {
this.request = request;
}

public void setSession(Map<String, Object> session) {
this.session = session;
}

public void setApplication(Map<String, Object> application) {
this.application = application;
}

@Override
public String execute() throws Exception {

InputStream in = new FileInputStream(imgFile);
String dir = ServletActionContext.getRequest().getRealPath(UPLOAD);
OutputStream fos = new FileOutputStream(dir + "\\"
+ this.getImgFileFileName());

byte[] buffer = new byte[1024 * 1024];

int length = 0;

while (-1 != (length = in.read(buffer))) {
fos.write(buffer, 0, length);

}
fos.close();
in.close();

request.put("msg", "Great!");

return "success2";
}

}



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值