1. 程式人生 > >struts攔截器與檔案上傳、下載

struts攔截器與檔案上傳、下載

定義一個action。.

TestAction.java


package com.zking.study.five;
 
/**
 *  用於測試的action,與普通action沒啥區別
 */
public class TestAction{
 
	public String execute() {
		System.out.println("進入了InterceptorAction的execute方法。");
		return null;
	}


定義一個攔截器,實現Interceptor介面,( com.opensymphony.xwork2.interceptor.Interceptor )

TestInterceptor.java

package com.zking.study.five;
 
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;
/**
 *  用於測試的攔截器,實現Interceptor介面
 */
public class TestInterceptor implements Interceptor{
 
	@Override
	public void destroy() {
		System.out.println("TestInterceptor is destroying.");
	}
	@Override
	public void init() {
		System.out.println("TestInterceptor is initing.");
	}
	@Override
	public String intercept(ActionInvocation arg0) throws Exception {
		System.out.println("攔截的類:"+arg0.getAction().getClass().getName());
		System.out.println("呼叫的Action是:"+arg0.getProxy().getActionName());
		System.out.println("呼叫的方法是:"+arg0.getProxy().getMethod());
		arg0.invoke();
		return null;
	}
}
 

struts中的配置檔案 struts-sy.xml


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
	"-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
	"http://struts.apache.org/dtds/struts-2.5.dtd">
<struts>
	<package name="sy" extends="base" namespace="/sy">
    <!-- 攔截器定義在package標籤下,於action同級 -->
	<interceptors>
		<interceptor name="testInterceptor" class="com.zking.study.five.TestInterceptor"></interceptor>
	</interceptors>
    <!-- 配置我們之前寫的那個測試action -->
		<action name="testAction" class="com.zking.study.five.TestAction">
            <!-- 將之前定義好的攔截器配置到action裡,(可配置多個) -->
			<interceptor-ref name="testInterceptor"></interceptor-ref>
		</action>
	</package>
</struts>

Interceptor
implements Interceptor
extends AbstractInterceptor
與filter的區別:先過filter再過interceptor

org.apache.struts2.interceptor.FileUploadInterceptor
檔案上傳:
三種上傳方案
虛擬路徑與真實路徑 /upload
copyFile與copydirectory

0. 檔案下載

另存為
直接開啟

  1. 內容型別
    response.setContentType(d.getMime());

  2. 設定響應頭
    response.setHeader(“Content-Disposition”,“attachment;filename=” + fileName);//檔名

  3. 處理檔名的中文亂碼
    String fileName = d.getFileName();
    fileName = new String(fileName.getBytes(“utf-8”), “iso8859-1”);

  4. struts2檔案上傳大小設定

  5. struts2檔案上傳型別設定
    根據struts2自帶的fileupload攔截器中提供的allowedTypes來進行限制

    image/png,image/gif,image/jpeg
  6. 其它
    enctype=“multipart/form-data” method=“post”
    private File file;
    private String fileContentType;
    private String fileFileName;