欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

struts2拦截器与文件上传、下载

程序员文章站 2022-05-28 15:57:47
...

1、拦截器

定义一个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>

在上面第二段代码块TestInterceptor.java中,destroy方法为拦截器被销毁时调用的方法、init方法为拦截器初始化时调用的方法,前面两个方法都没什么好说的,最后一个方法以及它的参数才是重点。

 intercept(ActionInvocation arg0)  ,在这里就不多解释了: https://blog.csdn.net/beliefyou8/article/details/51956279

 

 

2、文件上传、下载
 

在下面的demo中是用到了一个jar包的 commons-io-2.5.jar,使用前需要先将jar包导入进去,不导jar也行,需自己写文件操作的代码。

<!-- struts中的s标签 -->
<s:form action="fileAction_upload" namespace="/sy" method="post" enctype="multipart/form-data">
	<input type="file" name="file">
	<input type="submit">
</s:form>

定义上传、下载、打开文件的类

package com.zking.study.five;
 
import java.io.File;
import java.io.IOException;
 
import org.apache.commons.io.FileUtils;
 
import com.zking.study.four.base.BaseAction;
 
/**
 *  文件上传下载
 */
public class FileAction extends BaseAction{
//这是jsp页面传递过来的具体文件
	private File file;
	//文件名
	private String fileFileName;
	//文件类型
	private String fileContentType;
	//虚拟路径
	private String serverDir="/upload";
	
	public File getFile() {
		return file;
	}
 
	public void setFile(File file) {
		this.file = file;
	}
 
	public String getFileFileName() {
		return fileFileName;
	}
 
	public void setFileFileName(String fileFileName) {
		this.fileFileName = fileFileName;
	}
 
	public String getFileContentType() {
		return fileContentType;
	}
 
	public void setFileContentType(String fileContentType) {
		this.fileContentType = fileContentType;
	}
 
	//上传图片到tomcat
	public String upload() {
		String realPath = getRealPath(serverDir+"/"+fileFileName);
		try {
			FileUtils.copyFile(file, new File(realPath));
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "success";
	}
	//得到服务器中的真实路径
	private String getRealPath(String path) {
		return this.request.getServletContext().getRealPath(path);
	}
	
	//保存图片
	public String saveAs() {
		String fileName="stationmaster_img.png";
		String fileType="image/png";
		this.response.setContentType(fileType);
		this.response.setHeader("Content-Disposition","attachment;filename=" + fileName);
		String realPath=getRealPath(serverDir+"/"+fileName);
		try {
            //commons-io-2.5.jar 中的方法,不使用该方法则需自己写文件操作的方法。
			FileUtils.copyFile(new File(realPath), response.getOutputStream());
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	//打开图片
	public String openAs() {
		String fileName="stationmaster_img.png";
		String fileType="image/png";
		this.response.setContentType(fileType);
		this.response.setHeader("Content-Disposition","filename=" + fileName);
		String realPath=getRealPath(serverDir+"/"+fileName);
		try {
			FileUtils.copyFile(new File(realPath), response.getOutputStream());
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
}

BaseAction.java

package com.zking.study.four.base;
 
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
 
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
 
public class BaseAction implements ServletRequestAware, ServletResponseAware{
 
	/**
	 * 为了传值使用
	 */
	protected HttpServletRequest request;
	protected HttpServletResponse response;
	protected HttpSession session;
	protected ServletContext application;
	
	/**
	 * 为了配置跳转页面所用
	 */
	protected final static String SUCCESS="success";
	protected final static String FAIL="fail";
	protected final static String LIST="list";
	protected final static String ADD="add";
	protected final static String PROADD="proAdd";
	protected final static String EDIT="edit";
	protected final static String PROEDIT="proEdit";
	protected final static String DEL="del";
	protected final static String TOLIST="tolist";
	protected final static String DETAIL="detail";
	
	/**
	 * 具体传值字段		后端向jsp页面传值所用字段
	 */
	protected Object result;
	protected Object msg;
	protected int code;
	
	
	public Object getResult() {
		return result;
	}
	public Object getMsg() {
		return msg;
	}
	public int getCode() {
		return code;
	}
	@Override
	public void setServletResponse(HttpServletResponse response) {
		// TODO Auto-generated method stub
		this.response=response;
	}
	@Override
	public void setServletRequest(HttpServletRequest request) {
		// TODO Auto-generated method stub
		this.request=request;
	}
}

点击上传后跳转的页面 


<body>
<img src="${pageContext.request.contextPath}/sy/fileAction_openAs.action">
 
<a href="${pageContext.request.contextPath}/sy/fileAction_saveAs.action">点击下载</a>
</body>

struts2配置文件


<?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">
		<action name="fileAction_*" class="com.zking.study.five.FileAction" method="{1}">
			<result name="success">/success.jsp</result>
		</action>
	</package>
</struts>

上传文件是有两个概念需要理解的,虚拟路径与真实路径的概念?

相对于你所在的开发电脑而言,你自己电脑上有的就是真实路径,你电脑上没有的路径就是虚拟的。

相关标签: struts2