HttpServletRequest request相关问题

416 阅读2分钟

问题描述

在实际情况中使用HttpServletRequest的API,调用需要传递HttpServletRequest参数,但是又不想把HttpServletRequest对象当作这个Service方法的参数传过来,原因是这个方法被N多Controller调用,加一个参数就得改一堆代码,例如,我需要获取项目项目的IP地址和端口号等。

参考文档

  1. java获取项目所在服务器的ip地址和端口号(获取当前ip地址)
  2. HttpServletRequest详解

思路整理

只需要在获取项目地址的方法中,初始化HttpServletRequest即可。

具体实现

1.接口直接调用

    @RequestMapping("getUrl1")
    public String getUrl1(){
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        assert requestAttributes != null;
        HttpServletRequest request = requestAttributes.getRequest();
        String localAddr = request.getLocalAddr();
        int serverPort = request.getServerPort();
        return "http://"+localAddr +":"+ serverPort;
    }

2.接口间接调用

   @RequestMapping("getUrl1")
    public String  getUrl1(){
        return testRequest.getUrl1();
    }

3.主方法调用

  public static void main(String[] args) {
        TestRequest testRequest = new TestRequest();
        String url1 = testRequest.getUrl1();
    }

最终效果

1.接口直接调用结果

接口直接调用结果

2.接口间接调用

3.主方法调用

ServletRequestAttributes对象为空

思考

为什么接口方法和主方法调用同一个方法会产生不一样的效果呢?

公共接口类HttpServletRequest继承自ServletRequest。客户端浏览器发出的请求被封装成为一个HttpServletRequest对象。对象包含了客户端请求信息包括请求的地址,请求的参数,提交的数据,上传的文件客户端的ip甚至客户端操作系统都包含在其内。HttpServletResponse继承了ServletResponse接口,并提供了与Http协议有关的方法,这些方法的主要功能是设置HTTP状态码和管理Cookie。

简答来说就是,当网页发送了一个接口请求到服务器端时,服务器端就会产生一个HttpServletRequest对象,这个对象随着请求的诞生而诞生,消亡而消亡。因为主方法中没有涉及到客户端浏览器对服务器的接口调用所以就没有HttpServletRequest对象产生。

总结

  1. 明白HttpServletRequest的概念即可