最近在学习javaweb的过程中,遇到了一些相对路径和绝对路径的问题,对于几种request获取路径方法了解的不是很清楚,在网上发现了这篇文章,通俗易懂,希望可以帮助到大家。
本文章主要讨论以下几种request获取路径的方法:
request.getServletPath()
request.getPathInfo()
request.getContextPath()
request.getRequestURI()
request.getRequestURL()
request.getServletContext().getRealPath()
以一个简单的例子说明:
web.xml配置(注意此处的url-pattern项)
test
/*
TestServlet.java文件:
package com.java.test;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class TestServlet extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println(“servletPath:”+req.getServletPath());
System.out.println(“contextPath:”+req.getContextPath());
System.out.println(“contextPath2:”+req.getServletContext().getContextPath());
System.out.println(“pageInfo:”+req.getPathInfo());
System.out.println(“uri:”+req.getRequestURI());
System.out.println(“url:”+req.getRequestURL());
System.out.println(“realPath:”+req.getServletContext().getRealPath("/"));
}
}
此时请求http://localhost:8080/testweb (url-pattern=/*)
打印出来的值为:
servletPath:
contextPath:/testweb
contextPath2:/testweb
pageInfo:null
uri:/testweb
url:http://localhost:8080/testweb
realPath:G:\java.metadata.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\testweb
请求http://localhost:8080/testweb/abc 打印的值为:
servletPath:
contextPath:/testweb
contextPath2:/testweb
pageInfo:/abc
uri:/testweb/abc
url:http://localhost:8080/testweb/abc
realPath:G:\java.metadata.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\testweb
当我们修改web.xml为如下时(注意url-pattern的改变):
test
com.java.test.TestServlet
test
/abc/def/*
请求http://localhost:8080/testweb/abc/def/ghi/test.html (url-pattern=/abc/def/*) 打印的值为:
servletPath:/abc/def
contextPath:/testweb
contextPath2:/testweb
pageInfo:/ghi/test.html
uri:/testweb/abc/def/ghi/test.html
url:http://localhost:8080/testweb/abc/def/ghi/test.html
realPath:G:\java.metadata.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\testweb
通过观察打印结果,我们可以总结: