在项目中我们经常会遇到需要向请求头中添加消息的场景,然后后端通过request.getRequest()或者@RequestHeader获取请求头中的消息。
下面提供几种前端向请求头添加消息的方式
spring-webmvc:springmvc的包
jackson:将结果转化成json字符串的包
4.0.0
com.txc
springmvcdemo1
0.0.1-SNAPSHOT
war
org.springframework
spring-webmvc
5.3.28
com.fasterxml.jackson.core
jackson-databind
2.11.4
com.fasterxml.jackson.core
jackson-core
2.11.4
com.fasterxml.jackson.core
jackson-annotations
2.11.4
commons-fileupload
commons-fileupload
1.4
@ResponseBody:表示是一个异步请求,且返回json类型的数据
@RequesetHeader:表示从请求中获取参数username,如果请求中不包括username参数程序会报错。
@Controller
public class HeadersController {
@GetMapping("/testHeaders")
@ResponseBody
public String testHeaders(@RequestHeader String username){
System.out.println("======username====="+username);
return username;
}
}
在工程中需要引入jQuery的包信息,如果没有jQuery包,下面提供了源码下载
头消息在jQuery中可以通过headers参数和beforeSend函数发送
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
Insert title here
下载地址:https://github.com/axios/axios#example
在axios的dist目录中找到axios.js文件,引入到工程中
通过axios.create设置公共参数,在headers中设置请求头消息
如果不会使用axios.create可以参照如下博客:
https://blog.csdn.net/tangshiyilang/article/details/134678945
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
Insert title here
https://download.csdn.net/download/tangshiyilang/88620005