ServletContext是一个接口,但是服务器会传递一个已经实例化的对象过来。
对比与ServletConfig:
ServletConfig是传送servlet的参数
ServletContext是传送整个web应用的上下文参数
由于在web应用中多个servlet共享一个contex对象,所以多个servlet可以通过SverletContext对象实现数据共享。
其实对于数据库的配置不应该在ServletConfig中,而是应该在ServletContext中,因为如果有100个servlet,不可能配置100次ServletConfig。
举例:
web.xml:
class ServletDemo03:(将web.xml文件中的配置读出,同时将其存到ServletContext中)
class ServletDemo04:(将请求转发给1.jsp)
1.jsp:(得到demo04的转发内容,同时从context中取得数据进行显示)
服务器中有多个web应用,那么就有多个Context对象;
对于重定向和转发:
重定向就是你找我借钱,我没有,你去找老王借;
转发就是你找我借钱,我没有,我帮你找老王借;
重定向用户发两次请求,转发用户只需要一次请求。
对比与ServletConfig:
ServletConfig是传送servlet的参数
ServletContext是传送整个web应用的上下文参数
由于在web应用中多个servlet共享一个contex对象,所以多个servlet可以通过SverletContext对象实现数据共享。
其实对于数据库的配置不应该在ServletConfig中,而是应该在ServletContext中,因为如果有100个servlet,不可能配置100次ServletConfig。
举例:
web.xml:
<context-param>
<param-name>context_data1</param-name>
<param-value>context_value1</param-value>
</context-param>
class ServletDemo03:(将web.xml文件中的配置读出,同时将其存到ServletContext中)
//得到ServletContext方法1
ServletContext ctx = this.getServletConfig().getServletContext();
//得到ServletContext方法2
ctx = this.getServletContext();
String str = ctx.getInitParameter("context_data1");
ctx.setAttribute("data", str);
class ServletDemo04:(将请求转发给1.jsp)
ServletContext ctx = this.getServletContext();
//String str = (String) ctx.getAttribute("data");
//OutputStream out= response.getOutputStream();
//out.write(str.getBytes());
RequestDispatcher rd = ctx.getRequestDispatcher("/1.jsp");
rd.forward(request, response);
1.jsp:(得到demo04的转发内容,同时从context中取得数据进行显示)
<body>
<%
String str = (String)application.getAttribute("data");
out.write(str);
%>
</body>
服务器中有多个web应用,那么就有多个Context对象;
对于重定向和转发:
重定向就是你找我借钱,我没有,你去找老王借;
转发就是你找我借钱,我没有,我帮你找老王借;
重定向用户发两次请求,转发用户只需要一次请求。