Handling both multi-page and non-multipart HTTP-POST in Spring MVC

I have a SpringMVC web service for uploading files that look like this:

@RequestMapping(value="/upload.json", method = RequestMethod.POST)
public @ResponseBody Map<String, Object> upload(MultipartHttpServletRequest request) {
    // upload the file
}

and all dandy. But if one of the consumers submits a non-multipart form, I get this exception

java.lang.IllegalStateException: Current request is not of type [org.springframework.web.multipart.MultipartHttpServletRequest]

Which makes sense. However, I do not want my end users to see 500 servlet exceptions. I want a welcome error message.

I just tried this (to be like other POSTs):

@RequestMapping(value="/upload.json", method = RequestMethod.POST)
public @ResponseBody Map<String, Object> upload2(){ 
// return friendly msg 
}

but I get this error:

java.lang.IllegalStateException: Ambiguous handler methods mapped for HTTP path '/upload.json'

Is there a way to safely handle both multiple and non-multipart POST requests? in one method or in two different methods that I do not need.

+5
source share
1 answer

, :

@RequestMapping(value="/upload.json", method = RequestMethod.POST) 
public @ResponseBody Map<String, Object> upload(HttpServletRequest request) {
    if (request instanceof MultipartHttpServletRequest) {
        // process the uploaded file
    }
    else {
        // other logic
    }
}
+14

All Articles