Table of contents
2.1.application/x-www-form-urllencoded
3. Encoding supported by Spring MVC
1 Overview
HTTP (HyperText Transfer Protocol), hypertext transfer protocol. Hypertext (Hypertext) is a kind of structured text, which includes the ability of hyperlink (Hyperlink), through which you can create associations and jumps between different documents.
Traditional text is linear and arranged in a certain order, while hypertext breaks the linear structure and allows certain words, phrases or images in the text to be associated with other documents or resources. These associations are implemented through hyperlinks, and users can click on hyperlinks to jump to other related documents, web pages, pictures, videos or other media resources.
An important feature of hypertext is non-linearity, because users can freely jump and browse related content according to their interests and needs. This non-linear nature makes hypertext the foundation upon which the Internet and the World Wide Web (World Wide Web) are built, providing users with a rich browsing and navigation experience.
In the entire hypertext jump back and forth, the data to be transmitted is varied, such as text, pictures, video, audio, etc., so there must be a place in the message to declare the encoding format of the transmitted data. Properly parse the data after receiving it. In an HTTP message, this function is carried by the Content-Type attribute in the request header. Its structure is as follows:
content-type: theme type; character encoding
content-type:application/json; charset=UTF-8
The blogger explained the message structure of HTTP in detail in the previous article. Students who are not familiar with it can take a look, it is very clear and easy to understand:
HTTP, HTTPS__BugMan's Blog - CSDN Blog
Due to the variety of data types, each data type has its own corresponding content-type, so the types of content-type are also varied and numerous, with hundreds of types. Here are some examples:
-
text type:
text/plain
:Plain Texttext/html
: HTML documenttext/css
: CSS style sheettext/javascript
: JavaScript script
-
Application type:
application/json
: JSON dataapplication/xml
: XML dataapplication/pdf
: PDF documentapplication/octet-stream
: binary data streamapplication/x-www-form-urlencoded
: URL-encoded form dataapplication/zip
: ZIP archiveapplication/x-gzip
: GZIP compressed file
-
Image type:
image/jpeg
: JPEG imageimage/png
: PNG imageimage/gif
: GIF imageimage/svg+xml
: SVG image
-
Audio/Video Type:
audio/mpeg
: MP3 Audiovideo/mp4
: MP4 videovideo/mpeg
: MPEG Video
2. Common types
Due to the many types of content-type, this article only selects a few types that are often used in development to introduce.
2.1.application/x-www-form-urllencoded
application/x-www-form-urllencoded, the default encoding method for HTML forms, the reason why this method is used instead of json is because the data structure of json may be very complicated and requires additional parsing actions. Data in x-www-form-urllencoded is encoded in the form of key-value pairs, and is escaped and encoded using a specific character set. The specific coding rules are as follows:
- Use an equal sign ( ) to connect key-value pairs
=
, for example:key=value
- Use an ampersand ( ) to separate different key-value pairs
&
, for example:key1=value1&key2=value2
- Special characters are escape coded, and the escape code uses the percent sign (
%
) and the ASCII value of the two-digit hexadecimal character, for example: space is coded as%20
, plus sign is coded as%2B
Here is an example of data:
name=John%20Doe&age=25&city=New%2BYork
In the above example, there are three key-value pairs: name=John Doe
, age=25
,city=New+York
The HTTP message is as follows:
2.2.application/json
application/json, transfer data in json format.
HTML example:
The HTTP message is as follows:
3. Encoding supported by Spring MVC
3.1. Experiment
Build a controller:
Use form-data to pass:
Can receive data:
pass by
Also receive:
Use application/json to pass:
can not receive:
3.2. Adapter
The reason for the situation in the above experiment is that Spring MVC provides adapters ( HttpMessageConverter
) to handle different request body data encoding formats. These adapters automatically parse and convert request body data into method parameters or objects. When sending a POST request, no matter using form-data
or x-www-form-urlencoded
encoding format, Spring MVC can Content-Type
automatically , and pass the data to the corresponding Controller method.
However, if the data in json or xml format is passed, although spring mvc also prepares the corresponding adapter, it does not directly convert the data but needs to cooperate with the @RequestBody annotation to declare the binding of structured data with complex structures to the entity:
Many students will be confused here. Since the Content-Type in the message has declared the data type, why not directly convert complex structured data such as json? Also use it with @RequestBody.
This is actually just a choice in the design of Spring MVC. In fact, it is feasible to use COntent-Type to identify and convert. The annotations are specially introduced here because the annotations are used to clearly show that the data received is complex structured data. That's all. It can only be said that spring mvc chose this design. In fact, only using content-type to judge can take all situations.
3.3. Custom Adapter
There is a lot of content-type data, and the adapter that comes with Spring MVC must not be able to fully cover it. When there is no coverage, you can customize the parameter parsing logic by customizing the adapter to flexibly respond to all situations.
Custom adapter:
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
public class CustomMessageConverter extends AbstractHttpMessageConverter<CustomObject> {
public CustomMessageConverter() {
super(MediaType.APPLICATION_CUSTOM); // 自定义的 Content-Type
}
@Override
protected boolean supports(Class<?> clazz) {
return CustomObject.class.isAssignableFrom(clazz);
}
@Override
protected CustomObject readInternal(Class<? extends CustomObject> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
InputStreamReader reader = new InputStreamReader(inputMessage.getBody(), StandardCharsets.UTF_8);
// 手动解析请求主体内容并转换为 CustomObject 对象
// 这里假设请求主体内容是 JSON 格式
// 使用你喜欢的 JSON 解析库进行解析,比如 Jackson、Gson 等
CustomObject customObject = YourJsonParser.parse(reader, CustomObject.class);
return customObject;
}
@Override
protected void writeInternal(CustomObject customObject, HttpOutputMessage outputMessage) throws IOException {
// 实现将 CustomObject 对象转换为响应主体内容的逻辑
// 略
}
}
register:
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.util.List;
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
// 添加自定义的消息转换器
converters.add(new CustomMessageConverter());
}
}