Spring MVC-HttpMessageConverter

目录

概括

HttpMessageConverter,报文信息转换器,用于在HTTP请求和响应之间进行转换的策略接口,即将请求报文转换为Java对象,或将Java对象转换为响应报文。
HttpMessageConverter提供了两个注解和两个类型:@RequestBody,@ResponseBody,RequestEntity,ResponseEntity

环境

<dependencies>
        <!-- SpringMVC -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.3.1</version>
        </dependency>
        <!-- 日志 -->
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.2.3</version>
        </dependency>
        <!-- ServletAPI -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>
        <!-- Spring5和Thymeleaf整合包 -->
        <dependency>
            <groupId>org.thymeleaf</groupId>
            <artifactId>thymeleaf-spring5</artifactId>
            <version>3.0.12.RELEASE</version>
        </dependency>

    </dependencies>
  <!--自动扫描包-->
    <context:component-scan base-package="com.fly.controller"/>

    <!-- 配置Thymeleaf视图解析器 -->
    <bean id="viewResolver" class="org.thymeleaf.spring5.view.ThymeleafViewResolver">
        <property name="order" value="1"/>
        <property name="characterEncoding" value="UTF-8"/>
        <property name="templateEngine">
            <bean class="org.thymeleaf.spring5.SpringTemplateEngine">
                <property name="templateResolver">
                    <bean class="org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver">
                        <!-- 视图前缀 -->
                        <property name="prefix" value="/WEB-INF/templates/"/>
                        <!-- 视图后缀 -->
                        <property name="suffix" value=".html"/>
                        <property name="templateMode" value="HTML5"/>
                        <property name="characterEncoding" value="UTF-8" />
                    </bean>
                </property>
            </bean>
        </property>
    </bean>

    <!--  springMVC.xml  -->
    <mvc:view-controller path="/" view-name="index"/>

    <mvc:annotation-driven />
<filter>
        <filter-name>CharacterEncodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
        <init-param>
            <param-name>forceResponseEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>

    <filter-mapping>
        <filter-name>CharacterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <servlet>
        <servlet-name>DispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springMVC.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>DispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
  <meta charset="UTF-8">
  <title>首页</title>
</head>
<body>

</body>
</html>

@RequestBody

获取请求体,在控制器方法中用@RequestBody标识一个形参,前请求的请求体就会为当前注解所标识的形参赋值。

<!--index.html-->
<form th:action="@{/testRequestBody}" method="post" enctype="text/plain">
  用户名:
  <label>
    <input name="userName">
  </label><br>
  密码:
  <label>
    <input type="password" name="password">
  </label>
  <input type="submit">
</form>
package com.fly.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * @author 26414
 */
@Controller
public class HttpController {

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

}

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
  <meta charset="UTF-8">
  <title>success</title>
</head>
<body>
<!--success.html-->
<h2>success</h2>
</body>
</html>

Spring MVC-HttpMessageConverter

Spring MVC-HttpMessageConverter

Spring MVC-HttpMessageConverter

RequestEntity

RequestEntity是封装请求报文的一种类型,需要在控制器方法的形参中设置该类型的形参,当前请求的请求报文就会赋值给该形参

  /**
   *HttpController
   */
  @RequestMapping("/testRequestEntity")
  public String testRequestEntity(RequestEntity<String> requestEntity) {
    System.out.println("requestEntity.getHeaders() = " + requestEntity.getHeaders());
    System.out.println("requestEntity.getBody() = " + requestEntity.getBody());
    return "success";
  }
<!--index.html-->
<form th:action="@{/testRequestEntity}" method="post" enctype="text/plain">
  用户名:
  <label>
    <input name="userName">
  </label><br>
  密码:
  <label>
    <input type="password" name="password">
  </label>
  <input type="submit" value="RequestEntity">
</form>

Spring MVC-HttpMessageConverter

@ResponseBody

@ResponseBody用于标识一个控制器方法,可以将该方法的返回值直接作为响应报文的响应体响应到浏览器

返回普通类型

/**
   *HttpController
   */
  @RequestMapping("/testResponseBody")
  @ResponseBody
  public String testResponseBody() {
    return "hhh";
  }
<!--index.html-->
<a th:href="@{/testResponseBody}">testResponseBody</a>

Spring MVC-HttpMessageConverter

返回json

1:导入jackson的依赖

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.12.1</version>
</dependency>

2:在SpringMVC的核心配置文件中开启mvc的注解驱动
Spring MVC-HttpMessageConverter
3:使用@ResponseBody注解
4:将Java对象直接作为控制器方法的返回值返回

package com.fly.entity;

/**
 * @author 26414
 */
public class Person {
  
  private Integer id;

  public Person() {
  }

  public Person(Integer id, String name, Integer age) {
    this.id = id;
    this.name = name;
    this.age = age;
  }

  private String name;
  private Integer age;

  public Integer getId() {
    return id;
  }

  public void setId(Integer id) {
    this.id = id;
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public Integer getAge() {
    return age;
  }

  public void setAge(Integer age) {
    this.age = age;
  }
}

  /**
   *HttpController
   */
  @RequestMapping("/testResponseBodyJson")
  @ResponseBody
  public Person testResponseBodyJson() {
    return new Person(1, "张三", 12);
  }
<!--index.html-->
<a th:href="@{/testResponseBodyJson}">testResponseBodyJson</a>

Spring MVC-HttpMessageConverter

@RestController

一个方便的注释,它本身带有@Controller和@ResponseBody注释。 携带该注释的类型被视为控制器,其中@RequestMapping方法默认假设@ResponseBody语义。

ResponseEntity

ResponseEntity用于控制器方法的返回值类型,该控制器方法的返回值就是响应到浏览器的响应报文

上一篇:Elasticsearch 顶尖高手(6)--快速入门案例实战:group by + avg + sort等聚合分析(三)


下一篇:Impala笔记-保留小数位问题