11.攔截器與檔案上傳,下載
阿新 • • 發佈:2019-01-14
Struts 2 攔截器
interceptor(攔截器)是一種可以在請求處理之前或者之後執行的Struts 2元件。攔截器是Struts 2的重要特性,Struts 2框架絕大多數功能都是通過攔截器來完成的。
1.攔截器類:
public class MyTimerInterceptor extends AbstractInterceptor {
@Override
public String intercept(ActionInvocation invocation) throws Exception {
// 1。執行Action之前的工作:獲取開始執行時間
long startTime = System.currentTimeMillis();
System.out.println("執行Action之前的工作,開始時間:" + startTime);
// 執行後續攔截器或Action
String result = invocation.invoke();
// 3.執行Action之後的工作,計算並輸出執行時間
long endTime = System.currentTimeMillis();
long execTime = endTime - startTime;
System.out.println("ִ執行Action後的工作,結束時間" + endTime) ;
System.out.println("總共時間:" + execTime);
return result;
}
}
攔截器的配置
通過<interceptor/》元素定義攔截器
通過<interceptot-ref/》元素使用攔截器
<package name="default" namespace="/" extends="struts-default">
<!-- 攔截器 -->
<interceptors>
<!-- action的執行用時 -->
<interceptor name= "myTimer" class="util.MyTimerInterceptor" />
</interceptors>
<action name="login" class="userAction" method="login">
<result name="success">main.jsp</result>
<result name="error">login.jsp</result>
<result name="input">login.jsp</result>
<interceptor-ref name="myTimer"></interceptor-ref>
<interceptor-ref name="defaultStack"></interceptor-ref>
</action>
定義攔截器棧
<interceptors>
<!-- action的執行用時 -->
<interceptor name="myTimer" class="util.MyTimerInterceptor" />
<interceptor name="myAuthorization" class="util.AuthorizationInterceptot" />
<interceptor-stack name="myStack">
<interceptor-ref name="myAuthorization" />
<interceptor-ref name="defaultStack" />
</interceptor-stack>
</interceptors>
自定義攔截器
許可權驗證檢查攔截器
public class AuthorizationInterceptot extends AbstractInterceptor {
public String intercept(ActionInvocation invocation) {
Map session = invocation.getInvocationContext().getSession();
User user = (User) session.get("USER");
if (user == null) {
return Action.SUCCESS;
} else {
return Action.ERROR;
}
}
}
配置檔案
<package name="default" namespace="/" extends="struts-default">
<!-- 攔截器 -->
<interceptors>
<!-- action的執行用時 -->
<!-- 定義許可權驗證攔截器 -->
<interceptor name="myAuthorization" class="util.AuthorizationInterceptot" />
<interceptor-stack name="myStack">
<interceptor-ref name="myAuthorization" />
<interceptor-ref name="defaultStack" />
</interceptor-stack>
</interceptors>
<!-- 定義預設攔截器 -->
<default-interceptor-ref name="myStack" />
<default-action-ref name="defaultAction" />
<!-- 定義全域性結果 -->
<global-results>
<result name="login" type="redirect">
/login.jsp
</result>
</global-results>
</package>
注意:指定預設攔截器後,action中可省略攔截器的引用
檔案上傳
準備commons-fileupload-x.x.x.jar和commons-io-x.x.x.jar
1.jsp中
<s:form action="upload.action" enctype="multipart/form-data"
method="post">
<s:textfield name="title" lable="標題" />
<br />
<s:file name="upload" lable="選擇檔案" />
<br />
<s:submit name="submit" value="上傳檔案" />
</s:form>
2.檔案上傳的action
public class UploadAction extends ActionSupport {
private File upload; // 獲取提交的檔案
private String uploadContentType; // 封裝上傳檔案的型別
private String uploadFileName; // 服裝上傳檔名稱
private String savePath; // 獲取檔案的路徑
public String execute() throws Exception {
byte[] buffer = new byte[1024];
//讀取檔案
FileInputStream fis = new FileInputStream(getUpload());
//儲存問津
FileOutputStream fos = new FileOutputStream(getSavePath() + "\\"+ this.getUploadFileName());
int length = fis.read(buffer);
while (length > 0) {
fos.write(buffer, 0, length);
length = fis.read(buffer);
}
fis.close();
fos.flush();
fos.close();
}
return SUCCESS;
}
public String getSavePath() {
return ServletActionContext.getServletContext().getRealPath(savePath);
}
}
3.Strut.xml
<action name="upload" class="action.UploadAction">
<param name="savePath">/upload</param>
<result name="success">/upload_success.jsp</result>
</action>
4.success.jsp
你所上傳的檔案是:
<s:property value="uploadFileName" />
檔案型別:
<s:property value="uploadContentType" />
多檔案上傳
action
private File[] upload; // 獲取提交的檔案
private String[] uploadContentType; // 封裝上傳檔案的型別
private String[] uploadFileName; // 服裝上傳檔名稱
private String savePath; // 獲取檔案的路徑
public String execute() throws Exception {
byte[] buffer = new byte[1024];
for (int i = 0; i < upload.length; i++) {
FileInputStream fis = new FileInputStream(getUpload()[i]);
FileOutputStream fos = new FileOutputStream(getSavePath() + "\\"
+ this.getUploadFileName()[i]);
int length = fis.read(buffer);
while (length > 0) {
fos.write(buffer, 0, length);
length = fis.read(buffer);
}
fis.close();
fos.flush();
fos.close();
}
return SUCCESS;
}
public String getSavePath() {
return ServletActionContext.getServletContext().getRealPath(savePath);
}
檔案下載
1.jsp
<a href="download.action?fileName=334.jpg">點選下載</a>
2.struts.xml
<action name="download" class="action.FileDownAction">
<param name="inputPath">/upload</param>
<!-- <result name="success">/upload_success.jsp</result> -->
<result name="success" type="stream">
<param name="contentType">application/octet-stream</param>
<param name="inputName">inputStream</param>
<param name="contentDisposition">
attachment;filename="${fileName}"
</param>
<param name="bufferSize">4096</param>
</result>
</action>
3.action
private String inputPath; // 讀取下載檔案的目錄
private String fileName; // 下載檔案的檔名
@SuppressWarnings("unused")
private InputStream inputStream; // 讀取下載檔案的輸入流
private String conetntType; // 下載檔案的型別
public InputStream getInputStream() throws FileNotFoundException {
String path = ServletActionContext.getServletContext().getRealPath(
inputPath);
return new BufferedInputStream(new FileInputStream(path + "\\"
+ fileName));
}
public String execute() throws Exception {
return SUCCESS;
}
stream結果型別的配置引數
名稱 | 作用 |
---|---|
contentType | 設定傳送到瀏覽器的MIME型別 |
cpntentLengh | 設定檔案的大小 |
content | 設定響應的HTTP頭資訊中的Content-Disposition引數的值 |
inputName | 指定Action中提供inputStream型別的屬性名稱 |
bufferSize | 設定讀取下載檔案時的緩衝區大小 |
contentType檔案型別
檔案型別 | contentType設定 |
---|---|
Word | application/msword |
Excel | application/vnd.ms-excel |
PPT | application/vnd.ms-powerpoint |
圖片 | image/gif,image/bmp,image/jpeg |
文字檔案 | text/plain |
HTML網頁 | text/HTML |
任意的二進位制資料 | application/octet-stream |