1. 首页
  2. 软件开发
  3. SpringMVC—— RequestParam注解、RequestHeader注解、CookieValue注解的作用及用法

SpringMVC—— RequestParam注解、RequestHeader注解、CookieValue注解的作用及用法

  • 发布于 2024-08-17
  • 0 次阅读

RequestParam注解、RequestHeader注解和CookieValue注解在Spring MVC中用于获取不同类型的请求信息。

  1. @RequestParam注解 :
    用于从请求中获取参数的值。可以用在方法的参数上,指定要映射的请求参数的名称。

代码如下:

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MyController {
   

    @GetMapping("/hello")
    public String hello(@RequestParam("name") String name) {
   
        return "Hello, " + name;
    }
}
  1. @RequestHeader注解 :
    用于从请求头中获取特定的信息,比如User-Agent、Accept-Language等。

代码如下:

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MyController {
   

    @GetMapping("/user-agent")
    public String getUserAgent(@RequestHeader("User-Agent") String userAgent) {
   
        return "User Agent: " + userAgent;
    }
}
  1. @CookieValue注解 :
    用于从请求的Cookie中获取特定的值。

代码如下:

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MyController {
   

    @GetMapping("/cookie")
    public String getCookieValue(@CookieValue("myCookie") String cookieValue) {
   
        return "Cookie Value: " + cookieValue;
    }
}

原文链接: https://blog.csdn.net/2401_82884096/article/details/137960899