本文共 3289 字,大约阅读时间需要 10 分钟。
最近对于request中的几种“路径”有点混淆,查找网上资源都没有很好的总结,希望此文章能够帮助我理解一下这几种“路径”。
+++++++++++++++++++++++++++++++++++++++++++++++++ 本文章主要讨论以下几种request获取路径的方法:
TestServlet.java文件:aab a.jsp test com.java.test.TestServlet test /*
package com.java.test;import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class TestServlet extends HttpServlet{ @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doPost(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("servletPath:"+req.getServletPath()); System.out.println("contextPath:"+req.getContextPath()); System.out.println("contextPath2:"+req.getServletContext().getContextPath()); System.out.println("pageInfo:"+req.getPathInfo()); System.out.println("uri:"+req.getRequestURI()); System.out.println("url:"+req.getRequestURL()); System.out.println("realPath:"+req.getServletContext().getRealPath("/")); }}此时请求http://localhost:8080/testweb (url-pattern=/*) 打印出来的值为:
servletPath:contextPath:/testwebcontextPath2:/testwebpageInfo:nulluri:/testweburl:http://localhost:8080/testwebrealPath:G:\java\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\testweb\请求http://localhost:8080/testweb/abc 打印的值为:
servletPath:contextPath:/testwebcontextPath2:/testwebpageInfo:/abcuri:/testweb/abcurl:http://localhost:8080/testweb/abcrealPath:G:\java\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\testweb\当我们修改web.xml为如下时(注意url-pattern的改变):
请求http://localhost:8080/testweb/abc/def/ghi/test.html (url-pattern=/abc/def/*) 打印的值为:aab a.jsp test com.java.test.TestServlet test /abc/def/*
servletPath:/abc/defcontextPath:/testwebcontextPath2:/testwebpageInfo:/ghi/test.htmluri:/testweb/abc/def/ghi/test.htmlurl:http://localhost:8080/testweb/abc/def/ghi/test.htmlrealPath:G:\java\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\testweb\