Spring Boot 获取 HttpServletRequest 的几种方式

Spring Boot About 789 words

方法一

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";
    }

}
Views: 1,833 · Posted: 2022-10-14

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb/LiteNote

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

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


Today On History
Browsing Refresh