MultipartFilter in a non-Spring MVC application

606 views Asked by At

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. Wrappers wrapping each other

2

There are 2 answers

2
BalusC On BEST ANSWER

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 a.o. WAR's /WEB-INF/lib, server's /lib and JRE's /lib.

0
cloudnaut On

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