11.拦截器与文件上传,下载

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

猜你喜欢

转载自blog.csdn.net/qq_43051879/article/details/84875748
今日推荐