一、拦截器介绍
Interceptor是Struts2框架中定义的拦截器对象,它是一个接口,无论是Struts2内置的拦截器对象,还是自定义的拦截器,都需要直接或间接的实现此接口。AbstractInterceptor对象是一个抽象类,它对Interceptor接口进行了实现。在创建拦截器时,可以通过继承AbstractInterceptor进行创建。
1 import com.opensymphony.xwork2.ActionInvocation; 2 3 public interface Interceptor extends Serializable 4 { 5 void destroy() ; 6 void init() ; 7 String intercept(ActionInvocation invocation) throws Exception ; 8 }
拦截器(Interceptor)
• 拦截器的配置
1)编写实现Interceptor 接口的类。
2)在struts.xml 文件中定义拦截器。
3)在action中使用拦截器
4)一旦定义了自己的拦截器,将其配置到 action上后,我们需要在action的最后加上默认的拦截器栈:defaultStack。
二、文件上传fileupload
进行表单文件上传时,必须将表单的method属性设置为post,将enctype属性设置为multipart/form-data。
Struts2在进行文件上传操作时,实际上是通过两个步骤实现的:
1) 首先将客户端上传的文件保存到struts.multipart.saveDir键所指定的目录中,如果该键所对应的目录不存在,那么就保存到javax.servlet.context.tempdir 环境变量所指定的目录中。
2) Action中所定义的File类型的成员变量file实际上指向的是临时目录中的临时文件,然后在服务器端通过 IO的方式将临时文件写入到指定的服务器端目录中。
public class UploadServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
DiskFileItemFactory factory = new DiskFileItemFactory();
String path = req.getRealPath("/upload");
factory.setRepository(new File(path));
factory.setSizeThreshold(1024 * 1024);
ServletFileUpload upload = new ServletFileUpload(factory);
try {
List<FileItem> list = (List<FileItem>)upload.parseRequest(req);
for (FileItem fileItem : list)
{
String name = fileItem.getFieldName();
if (fileItem.isFormField())
{
String value = fileItem.getString();
System.out.println(name + "=" + value);
req.setAttribute(name, value);
}
else
{
String value = fileItem.getName();
int start = value.lastIndexOf("\\");
String fileName = value.substring(start + 1);
req.setAttribute(name, fileName);
fileItem.write(new File(path,fileName));
}
}
} catch (Exception e) {
e.printStackTrace();
}
req.getRequestDispatcher("fileUploadResult.jsp").forward(req, resp);
}
}