httpreservlet中和路径相关的方法
request.getContextPath();
返回请求使用的实际上下文路径
request.getServletPath();
request.getRequestURL();
request.getRequestURI();
ServletContext中和路径相关的方法
servletContext servletContext = getServletContext();
servletContext.getContextPath();
servletContext.getRealPath("/");
servletContext.getREsourcePaths("/");
补充1:测试代码
package GQ.work;
import java.io.IOException;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class TestServletPath extends HttpServlet {
private static final long serialVersionUID = 1L;
public TestServletPath() {
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
System.out.println("request.getContextPath()"+request.getContextPath());
System.out.println("request.getServletPath()"+request.getServletPath());
System.out.println("request.getRequestURL()"+request.getRequestURL());
System.out.println("request.getRequestURI()"+request.getRequestURI());
ServletContext context = getServletContext();
System.out.println("getServletContext()"+context);
System.out.println("context.getContextPath()"+context.getContextPath());
System.out.println("context.getRealPath('/')"+context.getRealPath("/"));
System.out.println("context.getResourcePaths('/')"+context.getResourcePaths("/"));
}
}
补充2: 测试结果及说明
①request.getContextPath()
/JD1706_Servlet
获得上下文路径
②request.getServletPath()
/TestServletPath
返回该请求使用的实际上下文路径
③request.getRequestURL()
http://localhost:8088/JD1706_Servlet/TestServletPath
获得浏览器地址
④request.getRequestURI()
/JD1706_Servlet/TestServletPath
项目中的路径
⑤getServletContext()
org.apache.catalina.core.ApplicationContextFacade@608061bd
上下文对象
⑥context.getContextPath()
/JD1706_Servlet
上下文路径
⑦context.getRealPath(‘/’)
E:\Study\javaee\apache-tomcat-6.0.18\webapps\JD1706_Servlet\
获得一个绝对路径/代表项目名后的/
⑧context.getResourcePaths(‘/’)
[/META-INF/, /download/, /WEB-INF/, /dabang.jpg, /zhaohongli.jpg, /form/, /upload/]
获得一个路径下的所有资源