简体   繁体   中英

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. We try to implement CSRF security, and therefor we added the _csrf token to all our forms. For file uploads we added the org.springframework.web.multipart.support.MultipartFilter to our web.xml , and also fixed the commons-fileupload dependency.

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? I tried casting the request object to MultipartHttpServletRequest but it failed. All examples on the internet show how to access the file item in a Spring MVC controller. I'm a bit lost here.包装纸相互缠绕

All those wrappers extend from the standard ServletRequestWrapper interface. Just cast to it, obtain the wrapped request via getRequest() method and test it instead.

You can even do it in a loop if it actually returned another ServletRequestWrapper implementation.

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. 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. Folders covered by the webapp's runtime classpath are ao WAR's /WEB-INF/lib , server's /lib and JRE's /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

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 :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM