一种在服务器内部的的资源的跳转方式
Aservlet ---->Bservlet分工合作
下列展示RequestDemo7 ---->RequestDemo8
RequestDemo7
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/RequestDemo7")
public class RequestDemo7 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//设置共享数据
req.setAttribute("msg","hello");
//转发到demo8资源
RequestDispatcher requestDispatcher = req.getRequestDispatcher("/RequestDemo8");
requestDispatcher.forward(req,resp);
}
}
RequestDemo8
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/RequestDemo8")
public class RequestDemo8 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Object msg = req.getAttribute("msg");
System.out.println(msg);
System.out.println("demo8被访问了");
}
}
ServletContext:
1.WEB容器在启动时,它会为每个WEB应用程序都创建一个对应的ServletContext对象,它代表当前web应用。
2.ServletConfig对象中维护了ServletContext对象的引用,开发人员在编写servlet时,可以通过ServletConfig.getServletContext方法获得ServletContext对象。
3.由于一个WEB应用中的所有Servlet共享同一个ServletContext对象,因此Servlet对象之间可以通过ServletContext对象来实现通讯。ServletContext对象通常也被称之为context域对象。
ServletContext应用:
1.多个Servlet通过ServletContext对象实现数据共享。
2.获取WEB应用的初始化参数。
3.实现Servlet的转发。
4.利用ServletContext对象读取资源文件。
(1).properties文件(属性文件)
(2)得到文件路径(ServletContext.getRealPath(),ServletContext.getReaourceAsStream())
ServletContext servletContext = req.getServletContext();
System.out.println(servletContext);
结果如下所示: