This article has participated in the activity of “New person creation Ceremony”, and started the road of digging gold creation together.

This article focuses on the Content-Type explanation of Http requests and its application in Spring MVC

Quote: In Http requests, we use the Content-type every day to specify different formats of request information, but few people fully understand how many values are allowed in the content-type. Here are the available values for the content-type. And how they can be used to map request information in Spring MVC.

1.  Content-Type

MediaType stands for Internet MediaType. Also known as MIME Type, content-Type is used in Http headers to indicate the media Type in a specific request.

Type format: type/subtype(; parameter)? Type Specifies the main type. Any string, such as text, is an asterisk. Subtype, an arbitrary string, such as HTML, if the asterisk represents all; Parameter Specifies some optional parameters, such as the Q parameter of the Accept request header and the Charset parameter of the Content-type.Copy the code

For example, content-type: text/ HTML; charset:utf-8;

Common media format types are as follows:

  1. Text/HTML: HTML format
  2. Text /plain: plain text format
  3. Text/XML: indicates the XML format
  4. Image/GIF: indicates the GIF image format
  5. Image/JPEG: JPG format
  6. Image/PNG: indicates the PNG image format

Media format types beginning with Application:

  1. Application/XHTML + XML: XHTML format
  2. Application/XML: XML data format
  3. Application/Atom + XML: Atom XML aggregation format
  4. Application /json: Json data format
  5. Application/PDF: in PDF format
  6. Application/MSWORD: Word document format
  7. Application /octet-stream: binary stream data (e.g. common file downloads)
  8. Application/X-www-form-urlencoded: default encType, form form data is coded as key/value format and sent to the server (form default submit data format)

Another common media format is used when uploading files:

Multipart /form-data: This format is used when files need to be uploaded in the form

These are some of the content-Type formats we often use in our daily development.

2. Use of content-type information in Spring MVC

First let’s look at the Class definition in RequestMapping:

@Target({ElementType.METHOD, ElementType.TYPE}) 
@Retention(RetentionPolicy.RUNTIME) 
@Documented 
@Mapping 
public @interface RequestMapping { 
   String[] value() default {}; 
   RequestMethod[] method() default {}; 
   String[] params() default {}; 
   String[] headers() default {}; 
   String[] consumes() default {}; 
   String[] produces() default {}; 
} 

Copy the code

Value: Specifies the actual address of the request, such as /action/info. Method: specifies the method Type of the requests. GET, POST, PUT and DELETE are the consumes, which are the content-types that handle the requests, for example, application/ JSON and Text/HTML. produces: Params: Specifies that the request must contain some parameter values before this method can handle headers: params: Specifies that the request must contain some parameter values before this method can handle headers: Consumes, Produces uses content-Typ to filter information. As consumes, the method consumes, produces. Content-type can be used to filter and determine headers.

3. Example

  3.1 headers

@RequestMapping(value = "/test", method = RequestMethod.GET, headers="Referer=http://www.ifeng.com/")  
public void testHeaders(@PathVariable String ownerId, @PathVariable String petId) {    
 // implementation omitted  
}  
Copy the code

Headers matches all Headers, not just the Referer. \

Example 2

@RequestMapping(value = "/response/ContentType", headers = "Accept=application/json")  
public void response2(HttpServletResponse response) throws IOException {  
  // The media type of the content area data representing the response is JSON and encoded in UTF-8 (the client should decode in UTF-8).
  response.setContentType("application/json; charset=utf-8");  
  // Write out the response body
  String jsonData = "{\"username\":\"zhang\", \"password\":\"123\"}";  
  response.getWriter().write(jsonData);  
}  
Copy the code

The server produces JSON data based on the request header “Accept=application/ JSON”.

When you have the following Accept header, the following rules apply:

1) Accept: Text/HTML, application/XML, application/json will produces the matching in the following order (1) (2) (3) application/application/XML text/HTML json (2) the Accept: application/xml; Q = 0.5, application/json; If q=0.9,text/ HTML will match produces in the following order ①text/ HTML ② Application /json ③ Application/XML is a quality factor of media type, the larger the application, the higher the priority (from 0 to 1) ③Accept: /,text/,text/ HTML will match in the following order ①text/ HTML ②text/ ③*/*

That is, the matching rule is: the most explicit match is preferred.

Part Requests

Header explain The sample
Accept Specifies the type of content that the client can receive Accept: text/plain, text/html
Accept-Charset A set of character encodings acceptable to the browser. Accept-Charset: iso-8859-5
Accept-Encoding Specifies the type of web server content compression encoding that the browser can support. Accept-Encoding: compress, gzip
Accept-Language Browser acceptable language Accept-Language: en,zh
Accept-Ranges You can request one or more subscope fields of a web page entity Accept-Ranges: bytes
Authorization HTTP authorization certificate Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==
Cache-Control Specify the caching mechanism that requests and responses follow Cache-Control: no-cache
Connection Indicates whether a persistent connection is required. (HTTP 1.1 makes persistent connections by default) Connection: close
Cookie When an HTTP request is sent, all cookie values stored under the domain name of the request are sent to the Web server. Cookie: $Version=1; Skin=new;
Content-Length The content length of the request Content-Length: 348
Content-Type MIME information that corresponds to the entity being requested Content-Type: application/x-www-form-urlencoded
Date The date and time the request was sent Date: Tue, 15 Nov 2010 08:12:31 GMT
Expect The specific server behavior requested Expect: 100-continue
From Email address of the user who made the request From: [email protected]
Host Specifies the domain name and port number of the requested server Host:localhost
If-Match This is valid only if the request content matches the entity If – the Match: “737060 cd8c284d8af7ad3082f209582d”
If-Modified-Since If the part of the request is modified after the specified time, the request succeeds; if it is not modified, the 304 code is returned If-Modified-Since: Sat, 29 Oct 2010 19:43:31 GMT
If-None-Match If the content has not changed, the 304 code is returned with the Etag sent by the server. The Etag is compared with the Etag returned by the server to determine whether it has changed If None – Match: “737060 cd8c284d8af7ad3082f209582d”
If-Range If the entity has not changed, the server sends the missing part of the client, otherwise sends the whole entity. The parameter is also Etag If – Range: “737060 cd8c284d8af7ad3082f209582d”
If-Unmodified-Since The request succeeds only if the entity has not been modified after the specified time If-Unmodified-Since: Sat, 29 Oct 2010 19:43:31 GMT
Max-Forwards Limit the amount of time messages can be sent through proxies and gateways Max-Forwards: 10
Pragma Used to contain implementation-specific instructions Pragma: no-cache
Proxy-Authorization Certificate of authorization to connect to the agent Proxy-Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==
Range Only a portion of the entity is requested, specifying scope Range: bytes=500-999
Referer The address of the previous web page, followed by the current requested web page, is the incoming path Referer: http://localhost:port
TE The client is willing to accept the transmission code and notifies the server to accept the end plus header message TE: trailers,deflate; Q = 0.5
Upgrade Specify some transport protocol to the server for the server to convert (if supported) Upgrade: HTTP/2.0, SHTTP/1.3, IRC/6.9, RTA/ X11
User-Agent User-agent contains the information about the User that sends the request The user-agent: Mozilla / 5.0 (Linux; X11)
Via Notification intermediate gateway or proxy server address, communication protocol Via: 1.0 fred, 1.1 nowhere.com (Apache/1.1)
Warning Warning information about message entities Warn: 199 Miscellaneous warning

Responses of

Header explain The sample
Accept-Ranges Indicates whether the server supports scoped requests and what type of segmented requests Accept-Ranges: bytes
Age Estimated time from the original server to proxy cache formation (in seconds, non-negative) Age: 12
Allow A valid request for a network resource. If not allowed, 405 is returned Allow: GET, HEAD
Cache-Control Tell all caching mechanisms whether they can cache and what type Cache-Control: no-cache
Content-Encoding The type of returned content compression encoding supported by the Web server. Content-Encoding: gzip
Content-Language The language of the response body Content-Language: en,zh
Content-Length The length of the response body Content-Length: 348
Content-Location Request an alternate address for alternate resources Content-Location: /index.htm
Content-MD5 Returns the MD5 check value of the resource Content-MD5: Q2hlY2sgSW50ZWdyaXR5IQ==
Content-Range The byte position of this part in the entire return body Content-Range: bytes 21010-47021/47022
Content-Type Returns the MIME type of the content Content-Type: text/html; charset=utf-8
Date The time when the original server message was sent Date: Tue, 15 Nov 2010 08:12:31 GMT
ETag The current value of the entity label of the request variable ETag: “737060 cd8c284d8af7ad3082f209582d”
Expires The expiration date and time of the response Expires: Thu, 01 Dec 2010 16:00:00 GMT
Last-Modified The last modification time of the requested resource Last-Modified: Tue, 15 Nov 2010 12:45:26 GMT
Location Used to redirect the recipient to the location of the non-requested URL to complete the request or to identify a new resource Location:l=http://localhost:port
Pragma This includes implementing specific instructions that can be applied to any recipient on the response chain Pragma: no-cache
Proxy-Authenticate It indicates the authentication scheme and the parameters that can be applied to the URL of the broker Proxy-Authenticate: Basic
refresh Applied to redirects or a new resource is created, redirects after 5 seconds (proposed by Netscape and supported by most browsers)   Refresh: 5; url=http://localhost:port
Retry-After If the entity is temporarily unavailable, notify the client to try again after the specified time Retry-After: 120
Server Name of the Web server software Server: Apache / 1.3.27 (Unix) (Red Hat/Linux)
Set-Cookie Set the Http cookies Set-Cookie: UserID=JohnDoe; Max-Age=3600; Version=1
Trailer Indicates that the header field exists at the end of the block transfer code Trailer: Max-Forwards
Transfer-Encoding File transfer coding Transfer-Encoding:chunked
vary Tell the downstream proxy whether to use a cached response or request from the original server Vary: *
Via Tell the proxy client where the response is sent Via: 1.0 fred, 1.1 nowhere.com (Apache/1.1)
Warning Alerts entities to possible problems Warning: 199 Miscellaneous warning
WWW-Authenticate Indicates the authorization scheme that the client requesting entity should use WWW-Authenticate: Basic

3.2 Examples of Params

@RequestMapping(value = "/test/{userId}", method = RequestMethod.GET, params="myParam=myValue")  
public void findUser(@PathVariable String userId) {    
 // implementation omitted  
}  
Copy the code

Only requests containing the name “myParam” and the value “myValue” act as a filter.

Consumes 3.3 / produces

@Controller  
@RequestMapping(value = "/users", method = RequestMethod.POST, consumes="application/json", produces="application/json")  
@ResponseBody 
public List<User> addUser(@RequestBody User userl) {    
  // implementation omitted  
  return List<User> users; 
}  

Copy the code

Produces ==> Handles requests whose Request Content-type is “application/json”. Produces specifies that the Accept header contains “application/json”. It also implies that the content type returned is application/json;

4. To summarize

In this article, we first introduce the main formats supported by content-Type, and then introduce the main usage methods based on the Content of @RequestMapping. Headers, Consumes, and Produces use the various media formats used in the Content-Type. You control access and filter it.

Thank you for reading, I hope I can help you, thank you for your support!