[英]How to bypass struts2 interceptors on file upload
我写了一个简单的页面,其中包含一个用于上载文件的表单和一个用于处理该文件的jsp。
我的问题是,当文件上传时,请求对象由Struts拦截器处理,当它到达jsp页面时,它已经被“消耗”了,因此使用诸如“ ServletFileUpload.parseRequest()”之类的方法读取请求的调用”返回空列表。
我已经找到了一个可行的解决方案,但是这需要重新启动Tomcat,并且由于必须在生产服务器上添加该页面,因此,如果不重新启动它,那就更好了。
现在,我尝试和工作的是:
1)在struts.xml中我添加了
<include file="custom/struts-custom.xml"/>
2)在struts-custom.xml中,我写道:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<constant name="struts.action.excludePattern" value="/path_to_my_jsp/page.jsp"/>
</struts>
有了这个,我可以绕过Struts拦截器上传文件。
有更好/更清洁的解决方案吗? 如我所说,最好的解决方案是不需要重新启动应用程序服务器。
即使我不认为问题与代码有关,我也会将其发布。
page.html:
<form action="upload.jsp" method="post" enctype="multipart/form-data" TARGET="Report_Down"
onSubmit="if(document.getElementById('file1').value == '') return false;">
Input File <input type="file" name="file1" id="file1">
<input type="submit" value="Upload">
</form>
upload.jsp:
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (!isMultipart) {
return;
}
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(1024 * 1024 * 2);
factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
String uploadFolder = getServletContext().getRealPath("")
+ File.separator + DATA_DIRECTORY;
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setSizeMax(1024 * 1024);
try {
List items = upload.parseRequest(request);
Iterator iter = items.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
if (!item.isFormField()) {
try {
String fileName = new File(item.getName()).getName();
String filePath = uploadFolder + File.separator + fileName;
File uploadedFile = new File(filePath);
item.write(uploadedFile);
//do something...
}
catch(Exception e) {
//...
}
}
}
getServletContext().getRequestDispatcher(forwardUrl).forward(
request, response);
} catch (FileUploadException ex) {
throw new ServletException(ex);
} catch (Exception ex) {
throw new ServletException(ex);
}
先感谢您 :)
您的请求被消耗是什么意思? 该请求通过拦截器堆栈到达操作,并且仍然存在。
如果由于某种原因(在简单上传文件时没有原因),而您需要在框架机制(动作,拦截器等)之外运行代码,则可以使用Servlet。
顺便说一句, 这是在Struts2中上传文件的正确方法 ,而您的问题主要与
我敢打赌n.1,但是如果仍然不能解决您的问题,请发布有关struts.xml的更多详细信息。
还请记住避免使用scriptlet(如Boris所建议),并且永远不要直接调用JSP:始终通过Action。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.