HttpMessageConverter
HttpMessageConverter
:报文信息转换器,将请求报文转换为Java对象,或将Java对象转换为响应报文。它提供了两个注解和两个类型:
@RequestBody, @ResponseBody, RequestEntity, ResponseEntity(响应用的较多)
准备
创建模块并完成配置文件编写
success.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" xmlns:th="http://www.thymeleaf.org">
<title>Title</title>
</head>
<body>
success
</body>
</html>
web.xml
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<!--配置编码过滤器-->
<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>
<!--配置请求方式put和delete的hiddenHttpMethodFilter-->
<filter>
<filter-name>HiddenHttpMethodFilter</filter-name>
<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>HiddenHttpMethodFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!--配置springMVC的前端控制器DispatcherServlet-->
<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>
</web-app>
SpringMVC.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--开启扫描组件-->
<context:component-scan base-package="com.louis"></context:component-scan>
<!--配值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>
</beans>
@RequestBody
@RequestBody
可以获取请求体,需要在控制方法设置一个形参,使用@RequestBody进行标识,当前请求的请求体就会为当前注解所标识的形参赋值(只求POST请求方式才会有请求体)
HttpController
@Controller
public class HttpController {
@RequestMapping("/testRequestBody")
public String testRequestBody(@RequestBody String requestBody){
System.out.println("requestBody = " + requestBody);
return "success";
}
}
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" xmlns:th="http://www.thymeleaf.org">
<title>首页</title>
</head>
<body>
<h3>首页</h3>
<form th:action="@{/testRequestBody}" method="post">
<input type="text" name="username">
<input type="text" name="password">
<input type="submit" value="测试@RequestBody">
</form>
</body>
</html>
测试
控制台
RequestEntity
RequestEntity
封装请求报文的一种类型,需要在控制器方法的形参中设置该类型的形参,当前请求的请求报文就会赋值给该形参,可以通过getHeaders()获取请求头信息,通过getBody()获取请求体信息。
index.html
<form th:action="@{/testRequestEntity}" method="post">
<input type="text" name="username">
<input type="text" name="password">
<input type="submit" value="测试RequestEntity">
</form>
HttpController
@RequestMapping("/testRequestEntity")
public String testRequestEntity(RequestEntity<String> requestEntity){
//当前的RequestEntity表示整个请求报文的信息
System.out.println("获取请求头:" + requestEntity.getHeaders());
System.out.println("获取请求体:" + requestEntity.getBody());
return "success";
}
测试
后端
@ResponseBody
@ResponseBody用于标识一个控制器方法,可以将该方法的返回值直接作为响应报文的响应体响应到浏览器。将数据响应到浏览器的方法有如下两种。
①直接使用ServletAPI
index.html
<a th:href="@{/testResponse}">通过servletAPI的response对象响应浏览器数据</a>
HttpController
@RequestMapping("/testResponse")
public void testResponse(HttpServletResponse response) throws IOException {
response.getWriter().write("hello response");
}
测试
②使用@ResponseBody
为了便于区分将success中的内容修改为如下
<h3>success</h3>
index.html
<a th:href="@{/testResponseBody}">通过@ResponseBody响应浏览器数据</a>
HttpController
@RequestMapping("/testResponseBody")
@ResponseBody
public String testResponseBody(){
/*加上@ResponseBody之后返回的就不再是视图名称,而是当前响应的响应体*/
return "success";
}
测试
不加@ResponseBody
SpringMVC处理json
创建User对象
public class User {
private Integer id;
private String username;
private String password;
private Integer age;
private String sex;
public User() {
}
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 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;
}
}
添加依赖
使用ResponseBody给浏览器响应对象数据,需要先导入jackson,因为浏览器不会识别对象类型。
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.15.2</version>
</dependency>
开启mvc的注解驱动
在SpringMVC的核心配置文件中开启mvc的注解驱动,此时在HandlerAdaptor中会自动装配一个消息转换器:MappingJackson2HttpMassageConvweter,可以将响应到浏览器的Java对象转换为Json格式的字符传输。
<mvc:annotation-driven></mvc:annotation-driven>
使用@ResponseBody标识
在控制器方法上使用@ResponseBody注解进行标识,这时将java对象直接作为控制器方法的返回值返回,就会自动转换为Json格式的字符串。
HttpController
@RequestMapping("/testResponseUser")
@ResponseBody
public User testResponseUser(){
/*加上@ResponseBody之后返回的就不再是视图名称,而是当前响应的响应体*/
return new User(1001, "khan", "1212", 22, "男");
}
index.html
<a th:href="@{/testResponseUser}">通过@ResponseBody响应浏览器User数据</a>
测试
SpringMVC处理ajax
导入静态资源axios.js
可以到进行下载
在springMVC.xml中配置
<!--开放对静态资源的访问-->
<mvc:default-servlet-handler/>
index.html
<div id="app">
<a @click="testAxios" th:href="@{/testAxios}">测试SpringMVC处理ajax</a>
</div>
<script th:src="@{/static/js/axios-0.18.0.js}"></script>
<script th:src="@{/static/js/vue.js}"></script>
<script>
new Vue({
el:"#app",
methods:{
testAxios(event){
axios({
method:"post",
url:event.target.href,
params:{
username:"louie",
password:"1212"
}
}).then(function (resp){
alert(resp.data);
});
/*取消超链接的默认行为*/
event.preventDefault();
}
}
})
</script>
HttpController
@RequestMapping("/testAxios")
@ResponseBody
public String testAxios(String username, String password){
System.out.println("username, = " + username + "password = " + password);
return "hello ajax";
}
测试
@RestController注解
@RestController注解是SpringMVC提供的一个复合注解,标识在控制器的类上,就相当于给类添加了@Controller注解,并且为其中的每个方法添加了@ResponseBody注解
RespondseEntity
用于控制器方法的返回值类型,该控制器方法的返回值就是响应到浏览器的响应报文。它可以用来实现文件下载功能。