SprintBoot任意处获取Request对象

老样子,直接上代码

方式一(粗暴,推荐)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package com.pibgstar.demo.utils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
* @author pibigstar
* @desc 获取request和response对象
**/
public class WebUtil {

/** 获取request对象 **/
public static HttpServletRequest getRequest(){
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
if (requestAttributes == null){
return null;
}
return ((ServletRequestAttributes)requestAttributes).getRequest();
}
/** 获取response对象 **/
public static HttpServletResponse getResponse(){
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
if (requestAttributes == null){
return null;
}
return ((ServletRequestAttributes)requestAttributes).getResponse();
}
}

方式二(简单)

在你需要的地方,注入即可

1
2
3
4
@Autowired
HttpServletRequest request;
@Autowired
HttpServletResponse response
-------------本文结束感谢您的阅读-------------