我写了前端控制器模式,并运行了测试。request.getPathInfo()在返回路径信息时会返回null。
1.调用servlet的
<a href="tmp.do">Test link to invoke cool servlet</a>
2.在DD.中映射servlet
任何具有.do扩展(例如tmp.do)的东西都将调用servlet "Redirector“。
<!-- 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。根据第一本书,
servlet生命周期从
"does not exist"
状态移动到"initialized"
状态(意思是准备为客户端的请求提供服务),从构造函数开始。init()总是在首次调用service()之前完成。
这告诉我,在构造函数和init()方法之间,servlet不是完全成熟的servlet。
因此,这意味着调用time service()方法时,servlet应该是完全增长的servlet,request方法应该能够调用getPathInfo()并期望有效值返回而不是null。
乌普特
非常有趣。(http://forums.sun.com/thread.jspa?threadID=657991)
(HttpServletRequest - getPathInfo() )
如果URL如下所示:
http://www.myserver.com/mycontext/myservlet/hello/test?paramName=value。
如果web.xml将servlet模式描述为/mycontext/* getPathInfo()将返回myservlet/hello/test,而getQueryString()将返回paramName=value
(HttpServletRequest - getServletPath() )
如果URL如下所示:
http://hostname.com:80/mywebapp/servlet/MyServlet/a/b;c=123?d=789
字符串servletPath = req.getServletPath();
它返回"/servlet/MyServlet“
发布于 2010-09-19 14:01:08
@Vivien是正确的。您希望使用HttpServletRequest#getServletPath()
(对不起,我在编写您无疑正在阅读的回答时忽略了这一点,我更新了答案)。
为了澄清:getPathInfo()
是否而不是包含在web.xml
中定义的servlet路径(只包括此后的路径),而getServletPath()
基本上只返回,这是在web.xml
中定义的servlet路径(因此之后不返回路径)。如果url模式包含通配符,特别是包含该部分。
https://stackoverflow.com/questions/3745275
复制相似问题