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:
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方法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
- 03.ServletContext
- ServletContext
- ServletContext
- servletcontext
- servletContext
- servletContext
- servletcontext
- ServletContext
- ServletContext
- servletContext
- ServletContext
- ServletContext
- servletContext
- ServletContext
- servletContext
- ServletContext
- servletContext
- ServletContext
- Android Camera 通过V4L2与kernel driver的完整交互过程
- IOS--MKNetworkKit的使用方法
- 关于jquery中ajax
- easyui dialog 标题栏 不显示
- LeetCode:Path Sum I &&II
- 03.ServletContext
- Ubuntu下Firefox的安装和Personal Package Archives
- 推荐个可以和《魔戒》争雄的美剧:《权力的游戏》。
- hbase region分配,RS下线处理
- 解决MYSQL访问时无法切换数据库的问题.Reading table information for completion of table and column names
- Java 判断操作系统类型(适用于各种操作系统)
- insmod时“invalid module format”及“unknown symbol”
- CentOS中文乱码问题的解决方法
- 多线程 gcd