美文网首页
Spring 获取 Request 对象

Spring 获取 Request 对象

作者: Tinyspot | 来源:发表于2023-12-26 19:54 被阅读0次

1. 获取 Request 对象

1.1 属性注入

@RestController
@RequestMapping("/web")
public class ConcreteController {

    @Resource
    private HttpServletRequest request;

    @RequestMapping("/request")
    public String request() {
        return JSON.toJSONString(request.getClass());
    }
}

1.2 方法参数注入

@RestController
@RequestMapping("/web")
public class ConcreteController {

    @RequestMapping("/request2")
    public String request2(HttpServletRequest request) {
        return JSON.toJSONString(request.getClass());
    }
}

1.3 从请求上下文获取 Request 对象

@RestController
@RequestMapping("/web")
public class ConcreteController {

    @RequestMapping("/request3")
    public String servletRequest() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        return JSON.toJSONString(request.getClass());
    }
}

2. @PostConstruct 注解

  • JDK 提供的注解
@Component
public class ConcreteConfig {

    @Resource
    private GreetService greetService;

    @PostConstruct
    public void init() {
        System.out.println("ConcreteConfig init: " + greetService.greet());
    }
}

Spring 启动时会执行init()

3. 获取IP

@RequestMapping("/ip/address")
public String ipAddress() {
    String hostAddress = null;
    try {
        InetAddress localHost = InetAddress.getLocalHost();
        hostAddress = localHost.getHostAddress();
    } catch (UnknownHostException e) {
        e.printStackTrace();
    }
    return hostAddress;
}

相关文章

网友评论

      本文标题:Spring 获取 Request 对象

      本文链接:https://www.haomeiwen.com/subject/nanlndtx.html