java Spring RestTemplate 不存在必需的字符串参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16238790/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 22:21:09  来源:igfitidea点击:

Required String parameter is not present with Spring RestTemplate

javaspringrestspring-mvcresttemplate

提问by TheEwook

I am having trouble to post 2 parameters with RestTemplate :

我无法使用 RestTemplate 发布 2 个参数:

  • a String
  • a MultipartFile
  • 一个字符串
  • 一个多部分文件

I don't think there is a problem in my controller because it's very basic. It seems that the controller doesn't received the name parameter. Could you tell me what's wrong in my code

我认为我的控制器没有问题,因为它非常基本。控制器似乎没有收到 name 参数。你能告诉我我的代码有什么问题吗

The controller(the receiver)

控制器(接收器)

@RequestMapping(value="/fileupload", method=RequestMethod.POST)
public void handleFileUpload(@RequestParam("name") String fileUploadHandlerName,
                             @RequestParam("file") MultipartFile file)
{
    [...]
}

The Rest client(the sender)

Rest客户端(发送方)

RestTemplate rest = new RestTemplate();
URI uri = new URI("http://127.0.0.1:7011/xxxxxxxx/admin/fileupload");

MultiValueMap<String, Object> parts = new LinkedMultiValueMap<String, Object>();
parts.add("name", "import_keys");
Resource file = new ClassPathResource("xmlFileImport/file.xml");
parts.add("file", file);

rest.postForLocation(uri, parts);

The controller stackTrace

控制器堆栈跟踪

org.springframework.web.bind.MissingServletRequestParameterException: Required String parameter 'name' is not present

org.springframework.web.bind.MissingServletRequestParameterException:所需的字符串参数“名称”不存在

回答by Sotirios Delimanolis

Handling multipart requests is a complex process. It's not as simple as reading request parameters. As such, Spring requires you to declare a MultipartResolverso that it can parse and handle such requests. You can do this in your applicationContext.xmlfile:

处理多部分请求是一个复杂的过程。它不像读取请求参数那么简单。因此,Spring 要求您声明 aMultipartResolver以便它可以解析和处理此类请求。您可以在applicationContext.xml文件中执行此操作:

<bean id="multipartResolver"  
    class="org.springframework.web.multipart.commons.CommonsMultipartResolver">  
    <property name="maxUploadSize">  
        <value> <YOUR_SIZE> </value>  
    </property>  
    <property name="maxInMemorySize">  
        <value> <YOUR_SIZE> </value>  
    </property>      
</bean>

Where CommonsMultipartResolveris the implementation that parse your request and split the parts so that your controller can find the plain request parameters and the file(s) uploaded.

CommonsMultipartResolver解析您的请求并拆分各个部分的实现在哪里,以便您的控制器可以找到普通的请求参数和上传的文件。