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

来源:互联网 发布:sql cast和convert 编辑:程序博客网 时间:2024/06/11 09:53

区别:

  • 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......../testpathRequestURI......../testpath/Test/TestServletRequestURL........http://localhost:8080/testpath/Test/TestServletServletPath......../Test/TestServlet
0 0
原创粉丝点击