1. 程式人生 > >Struts2 的開發應用

Struts2 的開發應用

實現 輸出流 myeclips bsp struts2 cnblogs 地址 -- 模式

理解MVC設計模式的基本概念和Java Web開發的兩種模式Model1和Model2,以及Struts開發工作流程和基本應用。

使用myeclipse的struts2開發時

要在軟件中添加struts2

技術分享

案例使用strust2開發實現網頁的文件上傳

建立java類

代碼如下

package po;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

public class UploadAction extends ActionSupport
{
private String title;
private File upload;
private String uploadContentType;
private String uploadFileName;

//接受依賴註入的屬性
private String savePath;
//接受依賴註入的方法
public void setSavePath(String value)
{
this.savePath = value;
}

private String getSavePath() throws Exception
{
return ServletActionContext.getRequest().getRealPath(savePath);
}

public void setTitle(String title) {
this.title = title;
}

public void setUpload(File upload) {
this.upload = upload;
}

public void setUploadContentType(String uploadContentType) {
this.uploadContentType = uploadContentType;
}

public void setUploadFileName(String uploadFileName) {
this.uploadFileName = uploadFileName;
}

public String getTitle() {
return (this.title);
}

public File getUpload() {
return (this.upload);
}

public String getUploadContentType() {
return (this.uploadContentType);
}

public String getUploadFileName() {
return (this.uploadFileName);
}
@Override
public String execute() throws Exception
{
System.out.println("開始上傳單個文件-----------------------");
System.out.println(getSavePath());
System.out.println("==========" + getUploadFileName());
System.out.println("==========" + getUploadContentType());
System.out.println("==========" + getUpload());
//以服務器的文件保存地址和原文件名建立上傳文件輸出流
FileOutputStream fos = new FileOutputStream(getSavePath() + "\\" + getUploadFileName());
FileInputStream fis = new FileInputStream(getUpload());
byte[] buffer = new byte[1024];
int len = 0;
while ((len = fis.read(buffer)) > 0)
{
fos.write(buffer , 0 , len);
}
return SUCCESS;
}
}然後在struts.xml中配置

技術分享

html代碼如下

技術分享

網頁實現

技術分享

Struts2 的開發應用