JavaWeb中获取各种路径
假设有如下结构项目:
/test/index.jsp:
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
// basePath:http://localhost:8088/12306/
System.out.println("basePath:" + basePath);
// getContextPath:/12306
System.out.println("getContextPath:" + request.getContextPath());
// getServletPath:/test/index.jsp
System.out.println("getServletPath:" + request.getServletPath());
// /12306/test/index.jsp
System.out.println("getRequestURI:" + request.getRequestURI());
// http://localhost:8088/12306/test/index.jsp
System.out.println("getRequestURL:" + request.getRequestURL());
// getQueryString:?a=1&b=2
System.out.println("getQueryString:" + request.getQueryString());
// getRealPath:F:\Workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp12\wtpwebapps\12306
System.out.println("getRealPath:" + getServletContext().getRealPath(""));
// getRealPath:F:\Workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp12\wtpwebapps\12306\
System.out.println("getRealPath:" + getServletContext().getRealPath("/"));
// getRealPath:F:\Workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp12\wtpwebapps\12306\home.jsp
System.out.println("getRealPath:" + getServletContext().getRealPath("home"));
// getRealPath:F:\Workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp12\wtpwebapps\12306\test\index.jsp
// 此地址即使不存在也能返回正确的拼接地址
System.out.println("getRealPath:" + getServletContext().getRealPath("/test/index.jsp"));
// /F:/Workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp12/wtpwebapps/12306/WEB-INF/classes/
System.out.println(this.getClass().getClassLoader().getResource("/").getPath());
// /F:/Workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp12/wtpwebapps/12306/WEB-INF/classes/test.txt
// 注意,此地址如果不存在则报错
System.out.println(this.getClass().getClassLoader().getResource("/test.txt").getPath());
%>