03.ServletContext

来源:互联网 发布:网络摄像机拍照 编辑:程序博客网 时间:2024/05/21 21:45
ServletContext是一个接口,但是服务器会传递一个已经实例化的对象过来。

对比与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方法1ServletContext ctx = this.getServletConfig().getServletContext();//得到ServletContext方法2ctx = 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对象;
对于重定向和转发:
重定向就是你找我借钱,我没有,你去找老王借;
转发就是你找我借钱,我没有,我帮你找老王借;
重定向用户发两次请求,转发用户只需要一次请求。
0 0
原创粉丝点击