首先我们要取得 HttpServletRequest (HttpServletResponse同理)
方式一:通过静态方法获取,也可以封装一个静态方法出来
1 2 3 4 5 6 7
| public class HttpContextUtils { public static HttpServletRequest getHttpServletRequest() { return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); } }
|
方式二:通过参数直接获取,只要在你的方法上加上参数,SpringBoot 就会帮你绑定,你可以直接使用。如果你的方法有其他参数,把 request 参数加到后面即可
1 2
| @GetMapping("/one") public void methodOne(@RequestParam String name, HttpServletRequest request) { }
|
方式三:注入到类,这样就不用每个方法都写了
1 2 3 4 5 6 7 8 9 10
| private final HttpServletRequest request;
public TestController(HttpServletRequest request) { this.request = request; }
@Log("执行方法一") @GetMapping("/one") public void methodOne(@RequestParam String name) { }
|
拿到 HttpServletRequest 后即可取得请求的 IP 地址
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
| public class IPUtils {
public static String getIpAddr(HttpServletRequest request) {
String ip = request.getHeader("x-forwarded-for"); if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("WL-Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getRemoteAddr(); } return "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : ip; } }
|