获取用户的根路径

一、方法

  • //这个方法用得比较多,动态获取应用的路径

    1. `String contextPath = request.getContextPath();`
    2. `System.out.println("应用的根路径" + contextPath);`

二、实现

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

6、获取用户的根路径 - 图1