从Java中的相对URL构建绝对URL
我无法从相对URL构建绝对URL而无需诉诸String hackery …
特定
http://localhost:8080/myWebApp/someServlet
方法内部:
public void handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { }
什么是最“正确”的建设方式:
http://localhost:8080/myWebApp/someImage.jpg
(注意,必须是绝对的,而不是相对的)
目前,我是通过构建字符串来实现的,但必须有更好的方法。
我查看了新URI / URL的各种组合,我最终得到了
http://localhost:8080/someImage.jpg
非常感谢
使用java.net.URL
URL baseUrl = new URL("http://www.google.com/someFolder/"); URL url = new URL(baseUrl, "../test.html");
怎么样:
String s = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/someImage.jpg";
看起来你已经找到了困难的部分,这是你正在运行的主机。 其余的很简单,
String url = host + request.getContextPath() + "/someImage.jpg";
应该给你你需要的东西。