1.调用servlet的HTML
<a href="tmp.do">Test link to invoke cool servlet</a>
2.以DD格式映射servlet.
任何有.do扩展名(ex tmp.do)将调用servlet“重定向器”
<!-- SERVLET (centralized entry point) --> <servlet> <servlet-name>RedirectHandler</servlet-name> <servlet-class>com.masatosan.redirector.Redirector</servlet-class> </servlet> <servlet-mapping> <servlet-name>RedirectHandler</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping>
3.从* .do请求的servlet
public class Redirector extends HttpServlet { protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { //test - THIS RETURNS NULL!!!! System.out.println(request.getPathInfo()); Action action = ActionFactory.getAction(request); //return action object based on request URL path String view = action.execute(request, response); //action returns String (filename) if(view.equals(request.getPathInfo().substring(1))) { request.getRequestDispatcher("/WEB-INF/" + view + ".jsp").forward(request, response); } else { response.sendRedirect(view); } } catch(Exception e) { throw new ServletException("Failed in service layer (ActionFactory)", e); } } }//end class
问题是request.getPathInfo()返回null.根据第一本书,
The servlet life cycle moves from
"does not exist"
state to
"initialized"
state (meaning ready
to service client’s request) beginning
with its constructor. The init()
always completes before the first call
to service().
这告诉我,在构造函数和init()方法之间,servlet是不完全成长的servlet.
所以,这意味着,通过调用service()方法,servlet应该是完全生成的servlet,request方法应该能够调用getPathInfo(),并期望有效的值返回而不是null.
UDPATE
很有意思. (http://forums.sun.com/thread.jspa?threadID=657991)
(HttpServletRequest – getPathInfo())
如果网址如下所示:
http://www.myserver.com/mycontext/myservlet/hello/test?paramName=value.
如果您的web.xml将/ mycontext / * getPathInfo()返回到myservlet / hello / test,则getModletString()将返回paramName = value
(HttpServletRequest – getServletPath())
如果网址如下所示:
http://hostname.com:80/mywebapp/servlet/MyServlet/a/b;c=123?d=789
String servletPath = req.getServletPath();
它返回“/ servlet / MyServlet”
这个页面也很好:
http://www.exampledepot.com/egs/javax.servlet/GetReqUrl.html
HttpServletRequest#getServletPath()
(对不起,我忽略了这一点,而你写的
answer,你不知不觉中正在阅读,我更新了答案).
为了澄清:getPathInfo()不包含在web.xml中定义的servlet路径(仅此之后的路径),而getServletPath()基本上只返回web.xml中定义的servlet路径(因此不是之后的路径).如果url模式包含通配符,特别是包含该部分.