关于JavaWeb中的路径问题
在浏览器中
/开头为相对路径表示当前主机地址==>http://localhost:8080,也就是服务器目录,而不是web应用
<a href="/xxx">、<form action="/xxx">==>http://localhost:8080/xxx这显然是不对劲的我们还需要在/xxx前面加上我们的项目名也就是这样http://localhost:8080/project/xxx
获取项目名的方式
jsp表达式:
<%= request.getContextPath() %>
El表达式:
${pageContext.request.contextPath }
Thymeleaf:
th:href="@{/}"
在服务器中
/开头为相对路径表示当前web应用地址也就是http://localhost:8080/project
request.getContextPath() // 获取项目根路径
request.getServletPath() // 获取servlet路径
request.getRequestURI() // 获取服务器请求路径,也就是端口号后面的全部路径
request.getRealPath("/") // 获取web应用的绝对路径
补充:ServletContext对象获得几种方式:
javax.servlet.http.HttpSession.getServletContext()
javax.servlet.jsp.PageContext.getServletContext()
javax.servlet.ServletConfig.getServletContext()
System.getProperty("user.dir") // 获取当前项目的工作目录

浙公网安备 33010602011771号