Search code examples
javarestspring-mvcputmodelattribute

Spring Mvc application PUT request with @ModelAttribute with multipart request form not binding


I have Spring application that handles REST APIs. All are working well until I converted the XML configuration to annotation configuration. At that time I have a problem in a few APIs. that APIs are PUT request With @ModelAttribute. that ajax requested data not binding in rest request.

@RequestMapping(method=RequestMethod.PUT,value="/user")
    public ResponseEntity<?> updatePlanSponsor(@ModelAttribute UserDTO user,BindingResult errors, @CookieValue(value="userID") Long userId){
------
}

All other requests like PUT with application/JSON, POST with multipart/form-data; In case of PUT with multipart/form-data; form not binding in dto class


Solution

  • I did to mistaken to add multi part resolver. PUT request with multipart only support with PutAwareCommonsMultipartResolver. CommonsMultipartResolver not support for PUT with Multipart .

     public class PutAwareCommonsMultipartResolver extends CommonsMultipartResolver {
    
        private static final String MULTIPART = "multipart/";
    
        @Override
        public boolean isMultipart(HttpServletRequest request) {
            return request != null && isMultipartContent(request);
        }
    
        /**
         * Utility method that determines whether the request contains multipart
         * content.
         * 
         * @param request The servlet request to be evaluated. Must be non-null.
         * 
         * @return <code>true</code> if the request is multipart; {@code false}
         * otherwise.
         * 
         * @see ServletFileUpload#isMultipartContent(HttpServletRequest)
         */
        public static final boolean isMultipartContent(HttpServletRequest request) {
            final String method = request.getMethod().toLowerCase();
            if (!method.equals("post") && !method.equals("put")) {
                return false;
            }
            String contentType = request.getContentType();
            if (contentType == null) {
                return false;
            }
            if (contentType.toLowerCase().startsWith(MULTIPART)) {
                return true;
            }
            return false;
        }
    
    }