我编写了一个简单的页面,其中包含一个上传文件的表单和一个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);
}(预先谢谢:)
发布于 2016-02-04 11:15:00
请求被消耗是什么意思?请求通过Interceptor堆栈到达Action,并且仍然在那里。
如果由于某些原因(在简单上传文件时不应该有),需要在框架机制(操作、拦截器等)之外运行代码,则可以使用Servlet。
顺便说一句,this is the correct way of uploading a file in Struts2,您的问题主要是与
我打赌1号,但如果这还没有解决你的问题,张贴更多关于你的struts.xml的细节。
另外,请记住避免使用scriptlet(就像Boris已经建议的那样),并避免,而不是直接调用JSP:始终通过一个操作。
https://stackoverflow.com/questions/35198474
复制相似问题