springboot中如何获取request呢?

乔欣 SpringBoot 发布时间:2023-02-23 22:39:01 阅读数:4320 1
下文笔者讲述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);
    }
}
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/JavaFramework/SpringBoot/202302/5898.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者