SpringMVC(十)获取请求头参数

版权声明:From Lay https://blog.csdn.net/Sadlay/article/details/84109081

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

结果如图

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/Sadlay/article/details/84109081