当前位置: 代码迷 >> 综合 >> request.getContextPath()、request.getRequestURI()、request.getRequestURI()、getServletPath()
  详细解决方案

request.getContextPath()、request.getRequestURI()、request.getRequestURI()、getServletPath()

热度:74   发布时间:2023-12-14 05:31:05.0

区别:

  • request.getContextPath():得到项目的名字,即当前应用的根目录。
  • request.getRequestURI():返回相对路径
  • request.getRequestURL():返回绝对路径
  • request.getServletPath():返回Servlet所对应的url-pattern

写一个最简单的Servlet:TestServlet.java

    public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {String ContextPath = request.getContextPath();System.out.println("ContextPath........"+ContextPath);String RequestURI = request.getRequestURI();System.out.println("RequestURI........"+RequestURI);StringBuffer RequestURL = request.getRequestURL();System.out.println("RequestURL........"+RequestURL);String ServletPath = request.getServletPath();System.out.println("ServletPath........"+ServletPath);}

web.xml中的配置如下;

  <servlet><servlet-name>TestServlet</servlet-name><servlet-class>test.TestServlet</servlet-class></servlet><servlet-mapping><servlet-name>TestServlet</servlet-name><url-pattern>/Test/TestServlet</url-pattern></servlet-mapping>

在地址栏里输入URL为:

http://localhost:8080/testpath/Test/TestServlet

输出结果为:

其中,testpath为项目名。
ContextPath......../testpath
RequestURI......../testpath/Test/TestServlet
RequestURL........http://localhost:8080/testpath/Test/TestServlet
ServletPath......../Test/TestServlet
  相关解决方案