第一种方式:非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";
}
}