1、@RequestHeader
- HTTP 请求报文中的首部(也可以称“头部”)中的有些信息,可能会在编程中起作用。Spring MVC 提供了
@RequestHeader
注解来便于方法参数接收首部的信息。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>MVC</title>
</head>
<body>
<form>
<input type="text" id="str1" autocomplete="off"/>
<input type="text" id="str2" autocomplete="off"/>
<input type="button" id="btn" value="提交"/>
</form>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.js"></script>
<script>
$("#btn").on("click", function() {
let myObj = {
str1: $("#str1").val(),
str2: $("#str2").val()
};
$.ajax({
contentType: "application/json;charset=utf-8",
type: "POST",
url: "http://localhost:8080/web4/data",
data: JSON.stringify(myObj),
success: function(result, status, xhr) {
console.log(status)
},
error: function(xhr, status, error) {
console.log(status)
}
});
});
</script>
</body>
</html>
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
@Controller
public class MyRequestController {
@PostMapping("/data")
public void myData(@RequestHeader("Content-Type") String contentType) {
System.out.println(contentType); // application/json;charset=UTF-8
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>MVC</title>
</head>
<body>
<form>
<input type="text" id="str1" autocomplete="off"/>
<input type="text" id="str2" autocomplete="off"/>
<input type="button" id="btn" value="提交"/>
</form>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.js"></script>
<script>
$("#btn").on("click", function() {
let myObj = {
str1: $("#str1").val(),
str2: $("#str2").val()
};
$.ajax({
contentType: "application/json;charset=utf-8",
type: "POST",
url: "http://localhost:8080/web4/data",
headers: {
Authorization: "c66fc7ed-a07d-400f-be85-c1f53cebe1e4"
},
data: JSON.stringify(myObj),
success: function(result, status, xhr) {
console.log(status)
},
error: function(xhr, status, error) {
console.log(status)
}
});
});
</script>
</body>
</html>
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
@Controller
public class MyRequestController {
@PostMapping("/data")
public void myData(@RequestHeader("Authorization") String token) {
System.out.println(token);
}
}
2、CookieValue
SpringMVC-6
SpringMVC-7
SpringMVC-8
<%@ page contentType="text/html;charset=UTF-8" pageEncoding="UTF-8" language="java" %>
<html>
<head>
<title>MVC</title>
</head>
<body>
<%
// 用于生成 Cookie 方便测试
Cookie cookie = new Cookie("uuid", "afac5117-39b5-4e2a-9a7b-82ed1227b801");
response.addCookie(cookie);
%>
<a href="/web4/data">后台打印 Cookie</a>
</body>
</html>
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
@Controller
public class MyRequestController {
@GetMapping("/data")
public void myData(@CookieValue("uuid") String uuid) {
System.out.println(uuid);
}
}
网友评论