JavaWeb 获取请求网络协议、IP、端口号、项目根路径(根目录)

1.需求

  在项目中,需要使用Java向本程序发送request请求,由于项目的发布名称、部署IP和端口不固定,

  如何才能动态获取这些信息呢?

2.代码实现

import javax.servlet.http.HttpServletRequest;
/**
 * 获取url请求前缀
 * @explain http://localhost:8080/test
 * @param request request对象
 * @return
 */
public static String getRequestPrefix (HttpServletRequest request) {
    // 网络协议
    String networkProtocol = request.getScheme();
    // 网络ip
    String ip = request.getServerName(); 
    // 端口号
    int port = request.getServerPort();
    // 项目发布名称
    String webApp = request.getContextPath();
    return networkProtocol + "://" + ip + ":" + port + webApp;
}

2021年11月4日10:43:15

SpringMvc,SpringBoot控制层获取请求地址

第一步:注入对象HttpServletRequest

注意:在代码的编译期和运行期,上述的request对象都是NULL,因为此时此刻,并没有请求到达这个控制器,所以该注入的对象为空。

第二步:在请求入口里调用请求对象。

2023年4月14日17:07:25

在Controller层或Servlet类当中,获取项目绝对路径

String projectAbsolutePath = request.getServletContext().RealPath("/");

2023年9月8日17:12:41

在Servlet当中的init()方法当中,获取项目绝对路径

config.getServletContext().getRealPath("/");

获取的项目绝对路径,比如:

D:\workspace-eclipse2021\TWRS2.1\web\

通过Struts2获取项目根路径

import org.apache.struts2.ServletActionContext;
/**
 * 获取制定路径的实际路径
 * @param servletContext
 * @param path
 * @return
 * @throws FileNotFoundException
 */
public static String getRealPath(String path) throws FileNotFoundException {
    if (!path.startsWith("/")) {
        path = "/" + path;
    }
    String realPath = ServletActionContext.getServletContext().getRealPath(path);
    if (realPath == null) {
        throw new FileNotFoundException("未找到文件夹:" + path);
    }
    return realPath;
}

 

posted @ 2018-06-01 16:44  Marydon  阅读(13078)  评论(3编辑  收藏  举报