SpringMVC-HttpMessageConverter

九、HttpMessageConverter

HttpMessageConverter:报文信息转换器。将请求报文(浏览器发送给服务器)转换为Java对象,或将Java对象转换为响应报文(服务器发送给浏览器)。

HttpMessageConverter提供了两个注解和两个类型:@RequestBody、@ResponseBody、RequestEntity、ResponseEntity

其中@ResponseBody和ResponseEntity用的较多。

1、@RequestBody

@RequestBody的作用:将请求报文的请求体转换为Java对象。

@RequestBody可以获取请求体,需要在控制器方法设置一个形参,使用@RequestBody进行标识,当前请求的请求体就会为当前注解所标识的形参赋值。

html中的设置

index.html中:

<h1>首页</h1>
<!--此时的请求体为:username=xxx&password=xxx-->
<form th:action="@{/testRequestBody}" method="post">
    <input type="text" name="username">
    <input type="text" name="password">
    <input type="submit" value="测试@RequestBody">
</form>

success.html中:

<h1>success</h1>

控制器中的设置

//测试请求体
@RequestMapping("/testRequestBody")
public String testRequestBody(@RequestBody String requestBody){
    System.out.println("requestBody:"+requestBody);
    return "success";
}

输出结果:requestBody:username=admin&password=123

2、RequestEntity

RequestEntity封装请求报文的一种类型,需要在控制器方法的形参中设置该类型的形参,当前请求的请求报文就会赋值给该形参,可以通过getHeaders()获取请求头信息,通过getBody()获取请求体信息。

RequestEntity不是专门封装请求头,也不是专门封装请求体的,而是封装整个请求报文。

html中的设置

index.html中:

<form th:action="@{/testRequestEntity}" method="post">
    <input type="text" name="username">
    <input type="text" name="password">
    <input type="submit" value="测试RequestEntity">
</form>

控制器中的设置

//测试RequestEntity获取的请求报文
@RequestMapping("/testRequestEntity")
public String testRequestEntity(RequestEntity<String> requestEntity){
    //当前requestEntity表示整个请求报文的信息
    //getHeaders()表示获取请求报文的请求头信息
    System.out.println("请求头:"+requestEntity.getHeaders());
    //getBody()表示获取请求报文的请求体信息
    System.out.println("请求体:"+requestEntity.getBody());
    return "success";
}

输出结果:

请求头:[host:"localhost:8080", connection:"keep-alive", content-length:"27", cache-control:"max-age=0", sec-ch-ua:"" Not A;Brand";v="99", "Chromium";v="99", "Microsoft Edge";v="99"", sec-ch-ua-mobile:"?0", sec-ch-ua-platform:""Windows"", upgrade-insecure-requests:"1", origin:"http://localhost:8080", user-agent:"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.74 Safari/537.36 Edg/99.0.1150.55", accept:"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,/;q=0.8,application/signed-exchange;v=b3;q=0.9", sec-fetch-site:"same-origin", sec-fetch-mode:"navigate", sec-fetch-user:"?1", sec-fetch-dest:"document", referer:"http://localhost:8080/SpringMVC/", accept-encoding:"gzip, deflate, br", accept-language:"zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6", Content-Type:"application/x-www-form-urlencoded;charset=UTF-8"]

请求体:username=admin&password=123

3、@ResponseBody

@ResponseBody的作用:将Java对象转换为响应报文的响应体。

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

注:没有加@ResponseBody时,return返回的sucess是视图的名称。加上@ResponseBody后,return返回的success作为响应报文的响应体,即直接在浏览器页面显示的文本。

向浏览器响应数据的方法:

1)通过servletAPI的response对象响应浏览器数据

html中的设置

index.html中:

<a th:href="@{/testResponse}">通过servletAPI的response对象响应浏览器数据</a>

控制器中的设置

//通过servletAPI的response对象响应浏览器数据
@RequestMapping("/testResponse")
public void testResponse(HttpServletResponse response) throws IOException {
    //将"hello,response"直接作为响应报文的响应体,响应给浏览器
    response.getWriter().print("hello,response");
}

2)通过@ResponseBody注解响应浏览器数据

index.html中:

<a th:href="@{/testResponseBody}">通过@ResponseBody注解响应浏览器String数据</a>

控制器中的设置

//通过@ResponseBody注解响应浏览器数据。返回String类型字符串
/**
 * 没有加@ResponseBody时,return返回的sucess是视图的名称。加
 * 上@ResponseBody后,return返回的success作为响应报文的响应体,
 * 即直接在浏览器页面显示的文本。
 */
@RequestMapping("/testResponseBody")
@ResponseBody
public String testResponseBody(){
    return "success";
}

4、SpringMVC中@ResponseBody处理json

直接将实体类对象响应给浏览器的设置:

在mvc包下创建bean包,用于存放实体类,然后新建User实体类并定义

private Integer id;
private String username;
private String password;
private Integer age;
private String sex;
​
public User(Integer id, String username, String password, Integer age, String sex) {
    this.id = id;
    this.username = username;
    this.password = password;
    this.age = age;
    this.sex = sex;
}
​
public User() {
}
​
public Integer getId() {
    return id;
}
​
public void setId(Integer id) {
    this.id = id;
}
​
public String getUsername() {
    return username;
}
​
public void setUsername(String username) {
    this.username = username;
}
​
public String getPassword() {
    return password;
}
​
public void setPassword(String password) {
    this.password = password;
}
​
public Integer getAge() {
    return age;
}
​
public void setAge(Integer age) {
    this.age = age;
}
​
public String getSex() {
    return sex;
}
​
public void setSex(String sex) {
    this.sex = sex;
}

html中的设置

index.html中:

<a th:href="@{/testResponseUser}">通过@ResponseBody注解响应浏览器User对象</a><br>

控制器中的设置

//通过@ResponseBody注解响应浏览器数据。返回User类型实体类
@RequestMapping("/testResponseUser")
@ResponseBody
//返回User类型
public User testResponseUser(){
    return new User(1001, "admin", "123456", 23, "男");
}

但是浏览器报错:HTTP状态 500 - 内部服务器错误,No converter found for return value of type: class com.atguigu.mvc.bean.User

这是因为浏览器无法直接处理响应的实体类对象,可以将其转换为json再响应给浏览器。

@ResponseBody处理json的步骤:

a>导入jackson的依赖

<!--jackson依赖-->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.11.4</version>
</dependency>

b>在SpringMVC的核心配置文件中开启mvc的注解驱动

此时在HandlerAdaptor中会自动装配一个消息转换器:MappingJackson2HttpMessageConverter,可以将响应到浏览器的Java对象转换为列Json格式的字符串(不是直接转化为json对象)。

<mvc:annotation-driven />

c>在处理器方法上使用@ResponseBody注解进行标识

d>将Java对象直接作为控制器方法的返回值返回,就会自动转换为Json格式的字符串

html中的设置

index.html中:

<a th:href="@{/testResponseUser}">通过@ResponseBody注解响应浏览器User对象</a><br>

控制器中的设置

//通过@ResponseBody注解响应浏览器数据。返回User类型实体类
@RequestMapping("/testResponseUser")
@ResponseBody
//返回User类型
public User testResponseUser(){
    return new User(1001, "admin", "123456", 23, "男");
}

浏览器页面中展示的结果为:{"id":1001,"username":"admin","password":"123456","age":23,"sex":"男"}

5、SpringMVC中处理ajax

ajax:在页面不跳转的情况下,与服务器进行交互。

a>请求超链接:

html中的设置

<div id="app">
    <a href="@{/testAxios}">SpringMVC处理ajax</a>
</div>

b>通过vue和axios处理点击事件:

1)在webapp目录下新建static.js目录,用来存放vue.js和axios.min.js文件。然后在html中引入vue.js和axios.min.js:

<!--引入vue.js和axios.min.js-->
<script type="text/javascript" th:src="@{/static/js/vue.js}"></script>
<script type="text/javascript" th:src="@{/static/js/axios.min.js}"></script>

2)绑定点击事件

<div id="app">
    <!--用@click绑定点击事件testAxios-->
    <a @click="testAxios" th:href="@{/testAxios}">SpringMVC处理ajax</a>
</div>

3)编写点击事件函数

<!--JavaScript代码-->
<script type="text/javascript">
    new Vue({
        //容器id为#app
        el:"#app",
        method:{
            testAxios:function (event) {
                axios({
                    //请求方式
                    method: "post",
                    //请求地址,即为此处超链接的触发地址
                    url:event.target.href,
                    //传输到服务器中的数据
                    params:{
                        username:"admin",
                        password:"123456"
                    }
                   //编写ajax处理请求成功之后的函数
                }).then(function (response) {
                    //response.data表示响应的数据
                    alert(response.data);
                });
​
                //取消当前超链接的默认行为
                event.preventDefault();
            }
        }
    });
</script>

则完整的html文件设置为

<div id="app">
    <!--用@click绑定点击事件testAxios-->
    <a @click="testAxios" th:href="@{/testAxios}">SpringMVC处理ajax</a>
</div>
<!--引入vue.js和axios.min.js-->
<script type="text/javascript" th:src="@{/static/js/vue.js}"></script>
<script type="text/javascript" th:src="@{/static/js/axios.min.js}"></script>
<!--JavaScript代码-->
<script type="text/javascript">
    new Vue({
        //容器id为#app
        el:"#app",
        method:{
            testAxios:function (event) {
                axios({
                    //请求方式
                    method: "post",
                    //请求地址,即为此处超链接的触发地址
                    url:event.target.href,
                    //传输到服务器中的数据
                    params:{
                        username:"admin",
                        password:"123456"
                    }
                   //编写ajax处理请求成功之后的函数
                }).then(function (response) {
                    //response.data表示响应的数据
                    alert(response.data);
                });
​
                //取消当前超链接的默认行为
                event.preventDefault();
            }
        }
    });
</script>

4)控制器设置

//SpringMVC处理ajax
@RequestMapping("/testAxios")
@ResponseBody
public String testAxios(String username, String password){
    System.out.println(username+","+password);
    return "hello,axios";
}

6、@RestController注解

@RestController注解是SpringMVC提供的一个复合注解,标识在控制器的类上,就相当于为类添加了@Controller注解,并且为其中的每个方法添加了@ResponseBody注解。

@RestController使用频繁。

7、ResponseEntity

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值