Skip to content

Commit 2d07054

Browse files
committed
Added Form converter
1 parent e35201f commit 2d07054

File tree

3 files changed

+199
-0
lines changed

3 files changed

+199
-0
lines changed

org.springframework.core/src/main/java/org/springframework/util/LinkedMultiValueMap.java

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,14 @@ public LinkedMultiValueMap() {
4444
this.targetMap = new LinkedHashMap<K, List<V>>();
4545
}
4646

47+
/**
48+
* Create a new SimpleMultiValueMap that wraps a newly created {@link LinkedHashMap} with the given initial capacity.
49+
* @param initialCapacity the initial capacity
50+
*/
51+
public LinkedMultiValueMap(int initialCapacity) {
52+
this.targetMap = new LinkedHashMap<K, List<V>>(initialCapacity);
53+
}
54+
4755
/**
4856
* Create a new SimpleMultiValueMap that wraps the given target Map.
4957
* <p>Note: The given Map will be used as active underlying Map.
Lines changed: 113 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,113 @@
1+
/*
2+
* Copyright 2002-2009 the original author or authors.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package org.springframework.http.converter;
18+
19+
import java.io.IOException;
20+
import java.io.InputStreamReader;
21+
import java.io.OutputStreamWriter;
22+
import java.net.URLDecoder;
23+
import java.net.URLEncoder;
24+
import java.nio.charset.Charset;
25+
import java.util.Iterator;
26+
import java.util.List;
27+
import java.util.Map;
28+
29+
import org.springframework.http.HttpInputMessage;
30+
import org.springframework.http.HttpOutputMessage;
31+
import org.springframework.http.MediaType;
32+
import org.springframework.util.FileCopyUtils;
33+
import org.springframework.util.LinkedMultiValueMap;
34+
import org.springframework.util.MultiValueMap;
35+
import org.springframework.util.StringUtils;
36+
37+
/**
38+
* Implementation of {@link HttpMessageConverter} that can read and write form data.
39+
*
40+
* <p>By default, this converter reads and writes the media type ({@code application/x-www-form-urlencoded}). This
41+
* can be overridden by setting the {@link #setSupportedMediaTypes(java.util.List) supportedMediaTypes} property. Form
42+
* data is read from and written into a {@link MultiValueMap MultiValueMap&lt;String, String&gt;}.
43+
* @author Arjen Poutsma
44+
* @see MultiValueMap
45+
* @since 3.0
46+
*/
47+
public class FormHttpMessageConverter extends AbstractHttpMessageConverter<MultiValueMap<String, String>> {
48+
49+
public static final Charset DEFAULT_CHARSET = Charset.forName("ISO-8859-1");
50+
51+
/**
52+
* Creates a new instance of the {@code FormHttpMessageConverter}.
53+
*/
54+
public FormHttpMessageConverter() {
55+
super(new MediaType("application", "x-www-form-urlencoded"));
56+
}
57+
58+
public boolean supports(Class<? extends MultiValueMap<String, String>> clazz) {
59+
return MultiValueMap.class.isAssignableFrom(clazz);
60+
}
61+
62+
public MultiValueMap<String, String> read(Class<MultiValueMap<String, String>> clazz, HttpInputMessage inputMessage)
63+
throws IOException {
64+
MediaType contentType = inputMessage.getHeaders().getContentType();
65+
Charset charset = contentType.getCharSet() != null ? contentType.getCharSet() : DEFAULT_CHARSET;
66+
String body = FileCopyUtils.copyToString(new InputStreamReader(inputMessage.getBody(), charset));
67+
68+
String[] pairs = StringUtils.tokenizeToStringArray(body, "&");
69+
70+
MultiValueMap<String, String> result = new LinkedMultiValueMap<String, String>(pairs.length);
71+
72+
for (String pair : pairs) {
73+
int idx = pair.indexOf('=');
74+
if (idx == -1) {
75+
result.add(URLDecoder.decode(pair, charset.name()), null);
76+
}
77+
else {
78+
String name = URLDecoder.decode(pair.substring(0, idx), charset.name());
79+
String value = URLDecoder.decode(pair.substring(idx + 1), charset.name());
80+
result.add(name, value);
81+
}
82+
}
83+
return result;
84+
}
85+
86+
@Override
87+
protected void writeToInternal(MultiValueMap<String, String> form, HttpOutputMessage outputMessage)
88+
throws IOException {
89+
MediaType contentType = getContentType(form);
90+
Charset charset = contentType.getCharSet() != null ? contentType.getCharSet() : DEFAULT_CHARSET;
91+
StringBuilder builder = new StringBuilder();
92+
for (Iterator<Map.Entry<String, List<String>>> entryIterator = form.entrySet().iterator();
93+
entryIterator.hasNext();) {
94+
Map.Entry<String, List<String>> entry = entryIterator.next();
95+
String name = entry.getKey();
96+
for (Iterator<String> valueIterator = entry.getValue().iterator(); valueIterator.hasNext();) {
97+
String value = valueIterator.next();
98+
builder.append(URLEncoder.encode(name, charset.name()));
99+
if (value != null) {
100+
builder.append('=');
101+
builder.append(URLEncoder.encode(value, charset.name()));
102+
if (valueIterator.hasNext()) {
103+
builder.append('&');
104+
}
105+
}
106+
}
107+
if (entryIterator.hasNext()) {
108+
builder.append('&');
109+
}
110+
}
111+
FileCopyUtils.copy(builder.toString(), new OutputStreamWriter(outputMessage.getBody(), charset));
112+
}
113+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
/*
2+
* Copyright 2002-2009 the original author or authors.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package org.springframework.http.converter;
18+
19+
import java.io.IOException;
20+
import java.nio.charset.Charset;
21+
import java.util.List;
22+
23+
import static org.junit.Assert.*;
24+
import org.junit.Before;
25+
import org.junit.Test;
26+
27+
import org.springframework.http.MediaType;
28+
import org.springframework.http.MockHttpInputMessage;
29+
import org.springframework.http.MockHttpOutputMessage;
30+
import org.springframework.util.LinkedMultiValueMap;
31+
import org.springframework.util.MultiValueMap;
32+
33+
/**
34+
* @author Arjen Poutsma
35+
*/
36+
public class FormHttpMessageConverterTests {
37+
38+
private FormHttpMessageConverter converter;
39+
40+
@Before
41+
public void setUp() {
42+
converter = new FormHttpMessageConverter();
43+
}
44+
45+
@SuppressWarnings("unchecked")
46+
@Test
47+
public void read() throws Exception {
48+
String body = "name+1=value+1&name+2=value+2%2B1&name+2=value+2%2B2&name+3";
49+
Charset iso88591 = Charset.forName("ISO-8859-1");
50+
MockHttpInputMessage inputMessage = new MockHttpInputMessage(body.getBytes(iso88591));
51+
inputMessage.getHeaders().setContentType(new MediaType("application", "x-www-form-urlencoded", iso88591));
52+
MultiValueMap result = converter.read(null, inputMessage);
53+
assertEquals("Invalid result", 3, result.size());
54+
assertEquals("Invalid result", "value 1", result.getFirst("name 1"));
55+
List<String> values = (List<String>) result.get("name 2");
56+
assertEquals("Invalid result", 2, values.size());
57+
assertEquals("Invalid result", "value 2+1", values.get(0));
58+
assertEquals("Invalid result", "value 2+2", values.get(1));
59+
assertNull("Invalid result", result.getFirst("name 3"));
60+
}
61+
62+
@Test
63+
public void write() throws IOException {
64+
MultiValueMap<String, String> body = new LinkedMultiValueMap<String, String>();
65+
body.set("name 1", "value 1");
66+
body.add("name 2", "value 2+1");
67+
body.add("name 2", "value 2+2");
68+
body.add("name 3", null);
69+
MockHttpOutputMessage outputMessage = new MockHttpOutputMessage();
70+
converter.write(body, outputMessage);
71+
Charset iso88591 = Charset.forName("ISO-8859-1");
72+
assertEquals("Invalid result", "name+1=value+1&name+2=value+2%2B1&name+2=value+2%2B2&name+3",
73+
outputMessage.getBodyAsString(iso88591));
74+
assertEquals("Invalid content-type", new MediaType("application", "x-www-form-urlencoded"),
75+
outputMessage.getHeaders().getContentType());
76+
}
77+
78+
}

0 commit comments

Comments
 (0)