最近复习Servlet一些相关知识,看到我们可以使用两种方式获取RequestDispatcher,即
//从ServletContext对象获取
getServletContext().getRequestDispatcher(String path).forward(req, resp);
//从Request对象获取
request.getRequestDispatcher(String path).forward(req, resp);
这两种方式都能具有forward方法,它们有什么区别呢?在网上查了查相关资料以供参考。
在stackoverflow上有人给出了这样的解释:
If you use absolute path ("/index.jsp"), there is no difference.
If you use relative path, you must use HttpServletRequest.getRequestDispatcher(). ServletContext.getRequestDispatcher() doesn't allow it.
For example, if you receive your request on http://example.com/myapp/subdir,
RequestDispatcher dispatcher =
request.getRequestDispatcher("index.jsp);
dispatcher.forward( request, response );
Will forward the request to the page http://example.com/myapp/subdir/index.jsp.
In any case, you can't forward request to a resource outside of the context.
简单的翻译下以上的答案:
1. 如果使用绝对地址,如 /index.jsp这种方式,二者无区别;
2. 如果使用相对地址,你只能使用request.getRequestDispatcher, ServletContext不允许使用相对路径;
3. 任何情况下你都不能将转发地址指向context之外的地方。
在实际使用过程中还有两点需要注意:
1. 在forward之前,不允许使用PrintWriter向页面输出内容(这里我自己测试了下,在forward之前向页面输出内容可能导致页面不会正确跳转)。
2. foward语句跳转后,可利用return或抛出异常的方式来结束当前servlet。
分享到:
相关推荐
小议职业高中数学教学.zip
小议生活中的茶文化.doc
小议量化宽松策略与影响.doc
小议建筑施工中的组织与管控.doc
小议外汇期权会计在新规则中应用.doc
小议高中教育中政治教学的审美性.docx
小议和谐高中思想政治课堂的构建.pdf
小议我国品牌并购与风险规避.doc
小议职业高中数学教学 (2).zip
小议全面收益观与传统收益综述.doc
小议物理教学中的探究与语言表达能力.doc
小议信息数据库管理与会计管理的结合.docx
小议最佳货币区与亚元的联想.doc
小议科学发展观与伦理思想的契合.doc
小议大中型超市的消防安全隐患及对策.doc
小议提升高中思想政治课堂教学质量的有效方案.docx
高职药学论文:小议高职药学创新与实践.doc
小议幼儿教育中的语言艺术
小议高中语文文言文教育.doc
小议无线平台中手机搜索.doc