mas*_*san 16 service jsp tomcat servlets
我写了Front Controller Pattern并运行测试.不知何故,request.getPathInfo()在返回路径信息时返回null.
1.调用servlet的HTML
<a href="tmp.do">Test link to invoke cool servlet</a>
Run Code Online (Sandbox Code Playgroud)
2.在DD中映射servlet.
任何有.do扩展名(ex 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>
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
问题是request.getPathInfo()返回null.基于Head First的书,
servlet生命周期从其
"does not exist"状态开始"initialized"(意味着准备服务客户端的请求)从其构造函数开始.init()总是在第一次调用service()之前完成.
这告诉我,在构造函数和init()方法之间,servlet是未完全成长的servlet.
因此,这意味着,在调用service()方法时,servlet应该是完全成长的servlet,并且请求方法应该能够调用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
String servletPath = req.getServletPath();
它返回"/ servlet/MyServlet"
这个页面也非常好:http: //www.exampledepot.com/egs/javax.servlet/GetReqUrl.html
Bal*_*usC 19
@Vivien是对的.你想使用HttpServletRequest#getServletPath()(对不起,我在写下你无疑正在阅读的答案时忽略了那一点,我已经更新了答案).
澄清:getPathInfo()不不作为definied在包括servlet路径web.xml(仅在此后的路径)和getServletPath()基本上返回仅作为definied servlet路径web.xml(并因此不是路径之后).如果url模式包含通配符,则特别包含该部分.
| 归档时间: |
|
| 查看次数: |
26987 次 |
| 最近记录: |