Java获取各种路径
本文由 小茗同学 发表于 2016-07-28 浏览(1543)
最后修改 2017-03-20 标签:java jsp 路径

JavaWeb中获取各种路径

假设有如下结构项目:

/test/index.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%
	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());
%>