SpringMVC(十)獲取請求頭引數
阿新 • • 發佈:2018-11-30
SpringMVC(十)獲取請求頭引數
在HTTP請求中,有些網站會利用請求頭的資料進行身份驗證,所以有時在控制器中還需要拿到請求頭的資料。在spring mvc中可以通過註解@RequestHeader
進行獲取。
下面先編寫一個前臺頁面
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<meta charset="UTF-8">
<title>獲取請求頭引數</ title>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.2.0.js"></script>
<script type="text/javascript">
$.post({
url:"./person",
//設定請求頭引數
headers:{
id:"1"
},
//成功後的方法
success: function (person) {
if(person==null||person.id==null){
alert("獲取失敗");
return;
}
//彈出請求返回的使用者資訊
alert("id="+person.id+",person_name="+person.personName);
}
});
</script>
</head >
<body>
</body>
</html>
程式碼中使用指令碼對控制器發出了請求,同時設定了一個鍵為id
而值為1
的請求頭,這樣這個請求頭也會發送到控制器中了。
控制器
package com.lay.mvc.controller;
import com.lay.mvc.entity.Person;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* @Description:
* @Author: lay
* @Date: Created in 18:21 2018/11/15
* @Modified By:IntelliJ IDEA
*/
@Controller
public class HeaderController {
@GetMapping("/header/page")
public String headerPage(){
return "/header/testheader";
}
@PostMapping("/header/person")
@ResponseBody
public Person headerPerson(@RequestHeader("id") Long id){
Person person=new Person();
person.setId(id);
person.setPersonName("花花");
return person;
}
}
程式碼的/header/testheader
是對應的檢視。headerPerson
方法中的引數id則是使用註解RequestHHeader("id")
,它代表從請求頭中獲取鍵為id
的引數,這樣就能從請求頭中獲取引數。
測試
在瀏覽器中輸入http://localhost:8080/header/page
結果如圖