Java OpenResty Spring Spring Boot MySQL Redis MongoDB PostgreSQL Linux Android Nginx 面试 小程序 Arthas JVM AQS juc Kubernetes Docker DevOps


Spring Boot 获取 HttpServletRequest 的几种方式

Spring Boot 大约 789 字

方法一

SpringMVC会隐式注入HttpRequest

@RestController
public class TestController {

    @GetMapping("/hello")
    public String helloGetPathVariable(HttpServletRequest request) {
        return "OK";
    }

}

方法二

通过依赖注入。

@RestController
public class TestController {

    @Autowired
    private HttpServletRequest request;

    @GetMapping("/hello")
    public String helloGetPathVariable() {
        return "OK";
    }

}

方法三

RequestContextHolderSpring封装的ThreadLocal

@RestController
public class TestController {

    @GetMapping("/hello")
    public String helloGetPathVariable() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        return "OK";
    }

}
阅读 168 · 发布于 2022-10-14

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb

扫描下方二维码关注公众号和小程序↓↓↓

扫描二维码关注我
昵称:
随便看看 换一批