Spring RestTemplate 不存在必需的字符串参数 [英] Required String parameter is not present with Spring RestTemplate

查看:115
本文介绍了Spring RestTemplate 不存在必需的字符串参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am having trouble to post 2 parameters with RestTemplate :

  • 一个字符串
  • 一个多部分文件

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

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

控制器(接收器)

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

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

控制器堆栈跟踪

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

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

推荐答案

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

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

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

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

Where CommonsMultipartResolver is 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.

这篇关于Spring RestTemplate 不存在必需的字符串参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆