获取用户的根路径
一、方法
✅
//这个方法用得比较多,动态获取应用的路径
`String contextPath = request.getContextPath();`
`System.out.println("应用的根路径" + contextPath);`
二、实现
public class RequestTestServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//这个方法用得比较多,动态获取应用的路径
String contextPath = request.getContextPath();
System.out.println("应用的根路径" + contextPath);
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.print(contextPath);
}
}
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<servlet>
<servlet-name>RequestTestServlet</servlet-name>
<servlet-class>servlet.RequestTestServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>RequestTestServlet</servlet-name>
<url-pattern>/testrequest</url-pattern>
</servlet-mapping>
</web-app>