Spring MVC中如何处理既包含多部分数据又包含非多部分数据的HTTP POST请求。

5

我有一个SpringMVC Web服务,用于上传文件,它的代码类似这样:

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

一切都很好。但是,如果其中一个使用者发布了非多部分表单,则会出现此异常。

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

这是有道理的.. 但我不希望我的终端用户看到500个servlet异常。我想要一个友好的错误信息。

我刚试了一下这个(作为其他POST的catchall):

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

但是我遇到了这个错误:
java.lang.IllegalStateException: Ambiguous handler methods mapped for HTTP path '/upload.json'

有没有一种安全的方式可以在一个方法中处理多部分和非多部分POST请求,或者使用2种不同的方法都可以。
1个回答

14

自行检查请求是否为多部分:

@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
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接