ServletContext提供了一个方法getContext(uri)
如果有两个application,它们部署在同一个server下,那么它们之间可以通过这种方式进行相互通信。
ServletContext aContext = ....
ServletContext anotherContext = aContext.getContext("the uri")
但是tomcat默认不允许跨应用的访问,可以在context.xml中配置一下。
找到Context节点,添加属性 crossContext="true"
ServletContext有一个方法getRequestDispatcher
HttpServletRequest也有一个方法getRequestDispatcher
前者是必须以"/"开头,相对于当前ServletContext的根目录(http:localhost:8080/springmvc)。
后者不必以"/"开头,如果以"/"开头那么就是项目于当前ServletContext的根目录(http:localhost:8080/springmvc)。
如果不以"/"开头,那么就是相对于当前请求的路径。
下面是RequestDispatcher include方法的使用:
原文地址:http://hi.baidu.com/jlhaoran/item/b89bff0e5fcd0c2fa0312d1c
一:RequestDispatcher.include方法可以将RequestDispatcher封装的资源信息当作当前响应的一部分包含进来从而实现可编程的服务器端包含功能。
二:被包含的Servlet程序不能改变响应信息的状态码和响应头 如果它里面存在这些语句,这些语句的执行结果将被忽略。
下面是一个例子。有三个servlet 其中一个包含另外两个的内容。
//head.java
package cn.nyist.servlet;
public class ServletDemo9 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String data="head 你好";
response.getWriter().write(data);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request,response);
}
}
//foot.java
package cn.nyist.servlet;
public class ServletDemo10 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String data="foot 你好";
response.getWriter().write(data);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request,response);
}
}
//ServletDemo12包含了前面两个servlet的内容
package cn.nyist.servlet;
public class ServletDemo12 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
response.setCharacterEncoding("UTF-8");
request.getRequestDispatcher("/servlet/ServletDemo9").include(request, response);
response.getWriter().write("</br>");
response.getWriter().write("hello");
response.getWriter().write("</br>");
request.getRequestDispatcher("/servlet/ServletDemo10").include(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request,response);
}
}