springboot中如何获取request呢?
下文笔者讲述SpringBoot中获取request的方法分享,如下所示
SpringBoot获取request的方法
实现思路: 方式1: controller中直接定义HttpServletRequest数据类型,则会自动接收request 方式2: Autowired方式注入request 方式3: 所有Controller的基类中注入,其方式2相同 方式4: 手动调用获取例
方法一:Controller中加入参数
@Controller public class TestController { @RequestMapping("/test") public void test(HttpServletRequest request) throws InterruptedException { // 模拟程序执行了一段时间* Thread.sleep(1000); } }
方法二:Autowired自动注入
@Controller public class TestController{ @Autowired private HttpServletRequest request; //自动注入request* @RequestMapping("/test") public void test() throws InterruptedException{ //模拟程序执行了一段时间* Thread.sleep(1000); } }
方法三:基类中自动注入
public class BaseController { @Autowired protected HttpServletRequest request; } 其他Controller继承她即可
方法四:手动调用
@Controller public class TestController { @RequestMapping("/test") public void test() throws InterruptedException { HttpServletRequest request = ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest(); // 模拟程序执行了一段时间 Thread.sleep(1000); } }
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。