SpringBoot获取Request请求的三种方式

文章目录

Request对象包含了请求的各种信息,比如请求方法、请求URL、请求参数、请求内容等等,这些信息可以供服务器进行处理和响应。那么在SpringBoot中,怎么才能获取到Request对象?

本文将介绍三种方法,并提示例参考。

一、直接在Controller方法参数上注入HttpServletRequest

这是最常用的一种方法。在Controller的方法参数上直接注入HttpServletRequest对象,Spring会自动将请求对象赋值到该参数中。

原理讲解:当Spring接收到HTTP请求时,会寻找一个合适的方法来处理该请求。如果该方法参数上标注了@RequestMapping或@Get、@Post等注解,Spring就会将HttpServletRequest对象注入到该参数中。

示例代码:

java 复制代码
@RestController
public class MyController {
    @RequestMapping("/test")
    public String test(HttpServletRequest request) {
        String ip = request.getRemoteAddr();
        String method = request.getMethod();
        String uri = request.getRequestURI();
        return "ip:" + ip + ", method:" + method + ", uri:" + uri;
    }
}

二、通过RequestContextHolder获取

在非Controller方法中,可以使用RequestContextHolder来获取ServletRequestAttributes对象,再从该对象中获取HttpServletRequest和HttpServletResponse。

原理讲解:Spring会将所有的请求参数、头部信息等封装到ServletRequestAttributes对象中。通过调用RequestContextHolder的getRequestAttributes()方法可以获取到该对象,再通过ServletRequestAttributes对象可以获取到HttpServletRequest对象。

示例代码:

java 复制代码
@Service
public class MyService {
    public String test() {
        ServletRequestAttributes sra = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = sra.getRequest();
        String ip = request.getRemoteAddr();
        String method = request.getMethod();
        String uri = request.getRequestURI();
        return "ip:" + ip + ", method:" + method + ", uri:" + uri;
    }
}

三、通过@Autowired注解注入HttpServletRequest对象

如果需要在非Controller方法中获取HttpServletRequest对象,可以使用@Autowired注解将该对象注入到对应的变量中。

原理讲解:在初始化一个Bean时,如果发现该Bean中有一个@Autowired注解标注的属性,Spring就会自动寻找一个合适的Bean来注入到该属性中。如果该属性是HttpServletRequest对象,Spring就会将当前的请求对象注入到该属性中。

示例代码:

java 复制代码
@Component
public class MyComponent {
    @Autowired
    private HttpServletRequest request;
    public String test() {
        String ip = request.getRemoteAddr();
        String method = request.getMethod();
        String uri = request.getRequestURI();
        return "ip:" + ip + ", method:" + method + ", uri:" + uri;
    }
}
复制代码
	以上是SpringBoot获取Request的三种方法,分别是直接在Controller方法参数上注入HttpServletRequest、通过RequestContextHolder获取、以及通过@Autowired注解注入HttpServletRequest对象。
相关推荐
阿里巴巴P8资深技术专家1 天前
基于 Spring Boot + JODConverter 实现文档在线转换为 PDF 功能
java
寻星探路1 天前
【算法专题】哈希表:从“两数之和”到“最长连续序列”的深度解析
java·数据结构·人工智能·python·算法·ai·散列表
q***44151 天前
SpringSecurity踢出指定用户
java
SHolmes18541 天前
Python all函数 判断是否同时满足多个条件
java·服务器·python
shejizuopin1 天前
基于JavaSSM+MySQL的实验室考勤管理系统设计与实现
java·mysql·vue·毕业设计·论文·springboot·实验室考勤管理系统设计与实现
J***51681 天前
SpringSecurity的配置
java
面汤放盐1 天前
软件架构指南 Software Architecture Guide
java·微服务·devops
tkevinjd1 天前
JUC5(线程池)
java·线程池·多线程·juc
武子康1 天前
大数据-210 如何在Scikit-Learn中实现逻辑回归及正则化详解(L1与L2)
大数据·后端·机器学习
Tao____1 天前
如何对接Modbus-tcp协议(使用Thinlinks物联网平台)
java·物联网·网络协议·tcp/ip·modbus