[英]MultipartFilter in a non-Spring MVC application
In our Java servlet (2.5) in Tomcat 6, we use Spring and Spring security 3 but no Spring MVC.在 Tomcat 6 的 Java servlet (2.5) 中,我们使用 Spring 和 Spring security 3,但没有使用 Spring MVC。 We try to implement CSRF security, and therefor we added the
_csrf
token to all our forms.我们尝试实现 CSRF 安全性,因此我们在所有表单中添加了
_csrf
令牌。 For file uploads we added the org.springframework.web.multipart.support.MultipartFilter
to our web.xml
, and also fixed the commons-fileupload dependency.对于文件上传,我们将
org.springframework.web.multipart.support.MultipartFilter
添加到我们的web.xml
,并修复了 commons-fileupload 依赖项。
We can see that the request is parsed and wrapped, but spring security is also wrapping the request again, so we can't access the multipart data anymore, can we?我们可以看到请求被解析和包装了,但是spring security也在再次包装请求,所以我们不能再访问multipart数据了,是吗? I tried casting the request object to
MultipartHttpServletRequest
but it failed.我尝试将请求对象转换为
MultipartHttpServletRequest
但失败了。 All examples on the internet show how to access the file item in a Spring MVC controller.互联网上的所有示例都展示了如何访问 Spring MVC 控制器中的文件项。 I'm a bit lost here.
我有点迷失在这里。
All those wrappers extend from the standard ServletRequestWrapper
interface.所有这些包装器都从标准的
ServletRequestWrapper
接口扩展而来。 Just cast to it, obtain the wrapped request via getRequest()
method and test it instead.只需投射到它,通过
getRequest()
方法获取包装的请求并对其进行测试。
You can even do it in a loop if it actually returned another ServletRequestWrapper
implementation.如果它实际上返回了另一个
ServletRequestWrapper
实现,您甚至可以在循环中进行。
public static <R extends ServletRequest> R unwrap(ServletRequest request, Class<R> type) {
ServletRequest current = request;
while (!type.isInstance(current) && current instanceof ServletRequestWrapper) {
current = ((ServletRequestWrapper) current).getRequest();
}
return type.isInstance(current) ? type.cast(current) : null;
}
Usage:用法:
MultipartHttpServletRequest multipartRequest = unwrap(request, MultipartHttpServletRequest.class);
// ...
As to the bonus question: your webapp's runtime classpath contains somewhere Servlet 3.0+ API.至于额外的问题:您的 webapp 的运行时类路径包含 Servlet 3.0+ API 的某个地方。 If that's not the intent, then it's likely simply a dirty runtime classpath.
如果这不是本意,那么它可能只是一个肮脏的运行时类路径。 Just cleanup it to get rid of Servlet 3.0+ libraries.
只需清理它即可摆脱 Servlet 3.0+ 库。 Folders covered by the webapp's runtime classpath are ao WAR's
/WEB-INF/lib
, server's /lib
and JRE's /lib
. webapp 的运行时类路径所覆盖的文件夹是 ao WAR 的
/WEB-INF/lib
、服务器的/lib
和 JRE 的/lib
。
although I like the way of how BalusC solved it better (with a while loop vs. recursion), I think it's worth mentioning that尽管我喜欢 BalusC 如何更好地解决它的方式(使用 while 循环与递归),但我认为值得一提的是
import org.springframework.web.util.WebUtils;
...
WebUtils.getNativeRequest(request, MultipartHttpServletRequest.class);
does the same but just with a recursion, but in a well supported Lib-Class :)做同样的事情,但只是递归,但在一个支持良好的 Lib-Class 中:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.