在spring中获得request

在spring中获得request,常用的有三种

一.Controller中加参数
1
2
3
4
5
6
7
8
@Controller
public class TestController {
@RequestMapping("/test")
public void test(HttpServletRequest request) throws InterruptedException {
// 模拟程序执行了一段时间
Thread.sleep(1000);
}
}

线程安全

二.自动注入

1
2
3
4
5
6
7
8
9
10
11
12
@Controller
public class TestController{

@Autowired
private HttpServletRequest request; //自动注入request

@RequestMapping("/test")
public void test() throws InterruptedException{
//模拟程序执行了一段时间
Thread.sleep(1000);
}
}

线程安全

在这里可能会有些疑问,spring注入的都是单例,会不会出现问题? 不会

@Autowired HttpServletRequest and passing as a parameter are the same things.

Before passing HttpServletRequest to invocation method responding to @RequestMapping function, Spring stores the HttpServletRequest into a ThreadLocal type variable.

That ThreadLocal variable is a thread-safe map that keeps HttpServletRequest in the current thread context. The @Autowired HttpServletRequest proxy bean gets the correct request from that ThreadLocal variable.

三.手动调用
1
2
3
4
5
6
7
8
9
@Controller
public class TestController {
@RequestMapping("/test")
public void test() throws InterruptedException {
HttpServletRequest request = ((ServletRequestAttributes)(RequestContextHolder.currentRequestAttributes())).getRequest();
// 模拟程序执行了一段时间
Thread.sleep(1000);
}
}

线程安全

参考:https://www.cnblogs.com/kismetv/p/8757260.html

https://stackoverflow.com/questions/48574780/autowired-httpservletrequest-vs-passing-as-parameter-best-practice

https://stackoverflow.com/questions/3320674/spring-how-do-i-inject-an-httpservletrequest-into-a-request-scoped-bean