HttpMessageConverter is a packet information converter. It serves two functions:

  • Convert the request message into a Java object: the request message is sent from the browser to the server, which is the Request object.
  • Convert a Java object into a response message: The server sends a response message to the browser. The browser cannot parse Java used by the server, so it converts a response message to the browser.

HttpMessageConverter provides two annotations: @requestBody and @responseBody. There are two more types: RequestEntity and ResponseEntity.

The two most commonly used to convert Java objects into response messages are @responseBody and ResponseEntity.

There are already several ways to get request parameters, or request headers, so there is no need to use @requestBody and RequestEntity here.

A, @ RequestBody

@requestbody can get the RequestBody. You need to set a parameter in the controller method. Using @requestbody to identify the parameter, the RequestBody of the current request will assign a value to the parameter identified by the current annotation.

For example, there is a page form for sending requests.

<form th:action="@{/testRequestBody}" method="post"> username: <input type="text" name="username"> <input type="password" name="password"><br> <input type="submit"> </form>Copy the code

The corresponding controller handles the request:

@RequestMapping("/testRequestBody")
public String testRequestBody(@RequestBody String requestBody){
    System.out.println("requestBody:"+requestBody);
    return "success";
}
Copy the code

A success.html is added here to jump to.

Then enter username=admin, password=123456 in the form. After submitting, check the console output:

requestBody:username=admin&password=123456
Copy the code

Username = admin&Password =123456 This is the request body content.

Second, the RequestEntity

RequestEntity is a type that encapsulates a request packet and contains the request header and request body.

When used, you need to set the parameter of this type in the parameter of the controller method. The request message of the current request is assigned to this parameter.

You can then get the request headers from getHeaders() and the request body from getBody().

Copy the form above and request a change of address:

<form th:action="@{/testRequestEntity}" method="post"> username: <input type="text" name="username"> <input type="password" name="password"><br> <input type="submit"> </form>Copy the code

Then add a controller method:

@RequestMapping("/testRequestEntity") public String testRequestEntity(RequestEntity<String> requestEntity){ System.out.println(" header :"+ requestEntity.getheaders ()); System.out.println(" body :"+requestEntity.getBody()); return "success"; }Copy the code

Enter the form and submit it to test:

Third, @ ResponseBody

1. Not using @responseBody

Using the Servlet API HttpServletResponse can also respond to the browser without using the @responseBody annotation.

Such as:

    @RequestMapping("/testResponse")
    public void testResponse(HttpServletResponse response) throws IOException {
        response.getWriter().print("hello, response");
    }
Copy the code

Write a hyperlink to test the front-end:

<a th:href="@{/testResponse}"> Use HttpServletResponse </a>Copy the code

Click on the hyperlink.

2. Using the @ ResponseBody

Using @responseBody identifies a controller method whose return value can be sent directly to the browser as the body of the response message.

    @RequestMapping("/testResponseBody")
    @ResponseBody
    public String testResponseBody(){
        return "success";
    }
Copy the code

The controller method here adds @responseBody:

  • If there is no annotation, return"success", matches the page to jump to.
  • Plus,"success"Instead of representing the view name, the response body is returned directly to the browser.

Continue adding hyperlinks to test:

<a th:href="@{/testResponseBody}">Copy the code

Note that in order to distinguish the effects, I have modified the contents of success.html:

<! DOCTYPE HTML > < HTML lang="en"> <head> <meta charset="UTF-8"> <title> title </title> </head> <body> <h1 Page </h1> </body> </ HTML >Copy the code

OK, now click the hyperlink and the page displays Success.

And then I’m going to get rid of @responseBody in my controller, and redeploy it and click on the hyperlink.

Jump to the success.html page.

So, it’s pretty convenient to use @responseBody, whatever data we need to return to the browser, just return it in our controller method.

3. SpringMVC handles JSON

The response in the example above is a string, which is displayed directly to the browser. What if I want to respond to an object?

For example, create a new User class and set the constructors, set and get:

public class User { private Integer id; private String username; private String password; private Integer age; private String sex; . .Copy the code

Writing controller:

@requestMapping ("/testResponseUser") @responseBody public User testResponseUser() {return new User(1001, "一 次 ", "123456", 11, "male "); }Copy the code

Return a User object directly.

To test this, continue adding a hyperlink to the front page:

<a th:href="@{/testResponseUser}">Copy the code

Redeploy, click Test, error reported.

There is also the conversion step, which converts the User object into a JSON-formatted string.

Add dependency Jackson to POM.xml:

<! - object into json response to the browser - > < the dependency > < groupId > com. Fasterxml. Jackson. Core < / groupId > < artifactId > Jackson - databind < / artifactId > < version > 2.12.1 < / version > < / dependency >Copy the code

Also, check whether the annotation driver is enabled in the springmVC.xml configuration file:

<! < MVC :annotation-driven />Copy the code

To redeploy, click the hyperlink.

The response is normal.

4. SpringMVC handles Ajax

Using Ajax to send a request is not the same as clicking the hyperlink above to send a request, but it is the same for the server.

The advantage of Ajax is that you can interact with the server without refreshing the page.

Continue adding content to the front page, add a hyperlink, bind a click event @click:

< div id = "app" > < a th: href = "@ {/ testAjax}" @ click = "testAjax" > for springMVC handle ajax < / a > < br > < / div >Copy the code

Here you need to use the static resources vue.min.js and axios.min.js, download it and put it under webApp \static\js.

Handle click events via Vue and AXIos:

<! Th: SRC ="@{/static/js/vue.min.js}"></script> <script type="text/javascript" th:src="@{/static/js/axios.min.js}"></script> <script> new Vue({ el: "#app", methods: { testAjax: function (event) { axios({ method: "post", url: event.target.href, params: { username: "admin", password: "123456"}}). Then (function (response) {alert(response.data) {response.data); event.preventDefault(); // Remove the default behavior of hyperlinks}}}); </script>Copy the code

Add the request controller for:

    @RequestMapping("/testAjax")
    @ResponseBody
    public String testAjax(String username, String password) {
        System.out.println("username:" + username + ",password:" + password);
        return "hello, Ajax";
    }
Copy the code

Before redeploying, remember to repackage Maven.

Also, remember to allow access to static resources in the springMVC configuration file:

<! < MVC :default-servlet-handler />Copy the code

To redeploy, click the hyperlink.

The @restController annotation

This is a note that will be used a lot.

The @RestController annotation is a composite annotation provided by springMVC.

The identification on the Controller’s class is equivalent to adding the @Controller annotation to the class and the @responseBody annotation to each of its methods.

Fifth, ResponseEntity

ResponseEntity Return value type for the controller method.

The return value of this controller method is the response message sent to the browser, which will be used in the download and upload file example below.