ServletContext方法实例讲解
来源:互联网 发布:阿里巴巴标题优化技巧 编辑:程序博客网 时间:2024/06/05 14:45
1、多个servlet可以通过这个对象实现数据共享
在一个servlet中写
<span style="white-space:pre"></span>String date = "aaa";this.getServletContext().setAttribute("date", date);
另外一个中
<span style="white-space:pre"></span>protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {String value = (String) this.getServletContext().getAttribute("date");System.out.println(value);}先后运行控制台就能输出aaa
2、实现Servlet的转发
在servlet中
<span style="white-space:pre"></span>protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {String data = "money";//把数据带给jsp一般不通过context域,而是request域this.getServletContext().setAttribute("data", data);RequestDispatcher rd = this.getServletContext().getRequestDispatcher("/test.jsp");rd.forward(request, response);}
在jsp中
<body><font color="red"><%String data = (String)application.getAttribute("data");out.write(data);%></font></body>
在浏览器里访问servlet就能看见输出
3、读取资源文件
在db.properties下写上
url=jdbc:mysql://localhost:3306/test
username=root
password=root
如和servlet放在同一个包下
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {InputStream in = this.getServletContext().getResourceAsStream("/WEB-INF/classes/db.properties");Properties props = new Properties();//map保存props.load(in);String url = props.getProperty("url");String username = props.getProperty("username");String password = props.getProperty("password");System.out.println(url);System.out.println(username);System.out.println(password);}
运行即可输出
0 0
- ServletContext方法实例讲解
- ServletContext讲解
- ServletContext讲解
- ServletContext的讲解
- ServletContext方法
- Servletcontext 相关监听器实例
- 实例讲解面向对象的思维方法
- 实例讲解木马的分析方法
- 实例讲解木马的分析方法
- 实例讲解木马的分析方法
- 实例讲解电源高频变压器的设计方法
- 数据库性能测试方法实例讲解
- Jquery ajaxStart()与ajaxStop()方法(实例讲解)
- Java wait() notify()方法使用实例讲解
- 实例讲解GRE填空解题方法
- 工厂方法模式实例与讲解
- Java wait() notify()方法使用实例讲解
- Java wait() notify()方法使用实例讲解
- Reactor模式和NIO
- [leetcode] 3Sum
- codeforces-#465A. inc ARG(模拟)
- 【个人机房重构】——限制字符串输入(正则表达式)
- codeforces-#465B. Inbox (100500)(模拟)
- ServletContext方法实例讲解
- 我的linux内核学习之路(送新手)
- 查看linux服务器硬盘IO读写负载
- 开心的小明
- Android 中ScrollView的使用
- top命令分析
- Android 无标题 全屏设置
- 理解Load Average做好压力测试
- 60 多年前,一群小白程序员扒了一个俄罗斯的开源框架--小白都能看懂的操作系统Communix的历史(转)