版权声明:尊重博主原创文章,转载请注明出处哦~http://blog.csdn.net/eson_15/article/details/51248280

目录(?)[+]

Servlet的API有很多,这里只谈谈两个Servlet对象:ServletConfig对象和ServletContext对象。

1. ServletConfig对象

在Servlet的配置文件中,可以使用一个或多个<init-param>标签为servlet配置一些初始化参数,当Servlet配置了初始化参数后,web容器在创建servlet实例对象时,会自动将这些参数封装到ServletConfig对象中,并在调用Servlet的init方法时,将ServletConfig对象传递给Servlet。进而,程序员通过ServletConfig对象就可以得到当前Servlet的初始化参数信息。该对象的getInitParameter(String name)用来获得指定参数名的参数值,getInitParameterNames()用来获得所有参数名,我们测试一下:

在test工程的src下新建一个包servletConfig,然后新建一个ServletConfigDemo1类,在配置文件里进行如下配置:

[html] view plaincopy
  1. <servlet>
  2. <servlet-name>ServletConfigDemo1</servlet-name>
  3. <servlet-class>servletConfig.ServletConfigDemo1</servlet-class>
  4. <init-param>
  5. <param-name>category</param-name>
  6. <param-value>book</param-value>
  7. </init-param>
  8. <init-param>
  9. <param-name>school</param-name>
  10. <param-value>tongji</param-value>
  11. </init-param>
  12. <init-param>
  13. <param-name>name</param-name>
  14. <param-value>java</param-value>
  15. </init-param>
  16. </servlet>
  17. <servlet-mapping>
  18. <servlet-name>ServletConfigDemo1</servlet-name>
  19. <url-pattern>/ServletConfigDemo1</url-pattern>
  20. </servlet-mapping>

在ServletConfigDemo1.java中的代码如下:

[java] view plaincopy
  1. public class ServletConfigDemo1 extends HttpServlet {
  2. ServletConfig config = null;
  3. @Override
  4. protected void doGet(HttpServletRequest req, HttpServletResponse resp)
  5. throws ServletException, IOException {
  6. String value = config.getInitParameter("category");//获取指定的初始化参数
  7. resp.getOutputStream().write((value + "<br/>").getBytes());
  8. Enumeration e = config.getInitParameterNames();//获取所有参数名
  9. while(e.hasMoreElements()){
  10. String name = (String) e.nextElement();
  11. value = config.getInitParameter(name);
  12. resp.getOutputStream().write((name + "=" + value + "<br/>").getBytes());
  13. }
  14. }
  15. @Override
  16. protected void doPost(HttpServletRequest req, HttpServletResponse resp)
  17. throws ServletException, IOException {
  18. doGet(req, resp);
  19. }
  20. @Override
  21. public void init(ServletConfig config) throws ServletException {
  22. this.config = config; //初始化时会将ServletConfig对象传进来
  23. }
  24. }

在浏览器中输入:http://localhost:8080/test/ServletConfigDemo1,即可在浏览器中显示读取参数的结果。

注:实际开发中,并不需要重写init方法,以上代码中重写init方法是为了说明config对象的传递过程。其实在父类的init方法中已经实现了该config的传递了,我们只要直接调用getServletConfig()就可以得到config对象,即在doGet方法中直接通过下面的调用方式获得ServletConfig对象:

[java] view plaincopy
  1. ServletConfig config = this.getServletConfig();

那么ServletConfig对象有什么作用呢?一般主要用于以下情况:

1)获得字符集编码;

2)获得数据库连接信息;

3)获得配置文件,查看struts案例的web.xml文件等。

2. ServletContext对象

web容器在启动时,它会为每个web应用程序都创建一个对应的ServletContext对象,它代表当前web应用(web工程)。在ServletConfig接口中有个getServletContext方法用来获得ServletContext对象;ServletContext对象中维护了ServletContext对象的引用,也可以直接获得ServletContext对象。所以开发人员在编写Servlet时,可以通过下面两种方式获得ServletContext对象:

[java] view plaincopy
  1. this.getServletConfig().getServletContext();
  2. this.getServletContext();

一般直接获得即可。
        由于一个web应用中的所有Servlet共享同一个ServletContext对象,因此Servlet对象之间可以通过ServletContext对象来实现通讯,ServletContext对象通常也被称为context域对象。有如下主要方法:

[java] view plaincopy
  1. getResource(String path); //方法获得工程里的某个资源
  2. getResourceAsStream(String path); //通过路径获得跟资源相关联的流
  3. setAttribute(Sring name, Object obj); //方法往ServletContext里存对象,通过MAP集合来保存。
  4. getAttribute(String name); //方法从MAP中取对象
  5. getInitParameter(String name); //获得整个web应用的初始化参数,
  6. //这个跟ServletConfig获取参数不同,这是在<context-param></context-param>中定义的,config对象里的getInitParameter方法获得的是具体某个servlet的初始化参数。
  7. getNamedeDispatcher(String name); //方法用于将请求转给另一个servlet处理,参数表示要转向的servlet。
  8. //调用该方法后,要紧接着调用forward(ServletRequest request, ServletResponse response)方法
  9. getServletContextName(); // 获得web应用的名称。

ServletContext应用有哪些呢?
         1)多个Servlet通过ServletContext对象实现数据共享(见下面的Demo1和Demo2)
         2)获取web应用的初始化参数(见Demo3)
         3)实现Servlet的转发(见Demo4和Demo5)
         4)利用ServletContext对象读取资源文件(xml或者properties)(见Demo6)

下面对ServletContext对象写几个Demo测试一下:

Demo1:往context域中存入数据

[java] view plaincopy
  1. public class ServletContextDemo1 extends HttpServlet {
  2. @Override
  3. protected void doGet(HttpServletRequest req, HttpServletResponse resp)
  4. throws ServletException, IOException {
  5. String data = "adddfdf";
  6. ServletContext context = this.getServletConfig().getServletContext();
  7. context.setAttribute("data", data);//将数据写到ServletContext
  8. }
  9. @Override
  10. protected void doPost(HttpServletRequest req, HttpServletResponse resp)
  11. throws ServletException, IOException {
  12. doGet(req, resp);
  13. }
  14. }

Demo2:从context域中读取数据

[java] view plaincopy
  1. public class ServletContextDemo2 extends HttpServlet {
  2. @Override
  3. protected void doGet(HttpServletRequest req, HttpServletResponse resp)
  4. throws ServletException, IOException {
  5. ServletContext context = this.getServletContext();
  6. String data = (String) context.getAttribute("data");//通过键值从ServletContext中获取刚才存入的数据
  7. resp.getOutputStream().write(data.getBytes());
  8. }
  9. @Override
  10. protected void doPost(HttpServletRequest req, HttpServletResponse resp)
  11. throws ServletException, IOException {
  12. doGet(req, resp);
  13. }
  14. }

Demo3:获取整个web应用的初始化参数

[java] view plaincopy
  1. public class ServletContextDemo3 extends HttpServlet {
  2. @Override
  3. protected void doGet(HttpServletRequest req, HttpServletResponse resp)
  4. throws ServletException, IOException {
  5. ServletContext context = this.getServletContext();
  6. String url = context.getInitParameter("url");//获取整个web应用的初始化参数,参数是在<context-param></context-param>中定义的
  7. resp.getOutputStream().write(url.getBytes());
  8. }
  9. @Override
  10. protected void doPost(HttpServletRequest req, HttpServletResponse resp)
  11. throws ServletException, IOException {
  12. doGet(req, resp);
  13. }
  14. }

Demo4:实现转发

[java] view plaincopy
  1. public class ServletContextDemo5 extends HttpServlet {
  2. @Override
  3. protected void doGet(HttpServletRequest req, HttpServletResponse resp)
  4. throws ServletException, IOException {
  5. ServletContext context = this.getServletContext();
  6. RequestDispatcher rd = context.getRequestDispatcher("/ServletContextDemo5");
  7. rd.forward(req, resp);//将请求转发给ServletContextDemo5.java处理
  8. }
  9. @Override
  10. protected void doPost(HttpServletRequest req, HttpServletResponse resp)
  11. throws ServletException, IOException {
  12. doGet(req, resp);
  13. }
  14. }

Demo5:

[java] view plaincopy
  1. public class ServletContextDemo5 extends HttpServlet {
  2. @Override
  3. protected void doGet(HttpServletRequest req, HttpServletResponse resp)
  4. throws ServletException, IOException {
  5. resp.getOutputStream().write("ServletDemo5".getBytes());//处理ServletDemo4传过来的请求
  6. }
  7. @Override
  8. protected void doPost(HttpServletRequest req, HttpServletResponse resp)
  9. throws ServletException, IOException {
  10. doGet(req, resp);
  11. }
  12. }

Demo6:读取资源文件

[java] view plaincopy
  1. public class ServletContextDemo6 extends HttpServlet {
  2. @Override
  3. protected void doGet(HttpServletRequest req, HttpServletResponse resp)
  4. throws ServletException, IOException {
  5. //test1(resp);
  6. //test2(resp);
  7. //test3(resp);
  8. //test4();
  9. }
  10. //读取文件,并将文件拷贝到e:\根目录,如果文件太大,只能用servletContext,不能用类装载器
  11. private void test4() throws FileNotFoundException, IOException {
  12. String path = this.getServletContext().getRealPath("/WEB-INF/classes/db.properties");
  13. String filename = path.substring(path.lastIndexOf("\\")+1);
  14. InputStream in = this.getServletContext().getResourceAsStream("/WEB-INF/classes/db.properties");
  15. byte buffer[] = new byte[1024];
  16. int len = 0;
  17. FileOutputStream out = new FileOutputStream("e:\\" + filename);
  18. while((len = in.read(buffer)) > 0){
  19. out.write(buffer, 0, len);
  20. }
  21. }
  22. //使用类装载器读取源文件(不适合装载大文件)
  23. private void test3(HttpServletResponse resp) throws IOException {
  24. ClassLoader loader = ServletContextDemo6.class.getClassLoader();
  25. InputStream in = loader.getResourceAsStream("db.properties");
  26. Properties prop = new Properties();
  27. prop.load(in);
  28. String driver = prop.getProperty("driver");
  29. resp.getOutputStream().write(driver.getBytes());
  30. }
  31. private void test2(HttpServletResponse resp) throws FileNotFoundException,
  32. IOException {
  33. String path = this.getServletContext().getRealPath("/WEB-INF/classes/db.properties");//获取绝对路径
  34. FileInputStream in = new FileInputStream(path);//传统方法,参数为绝对路径
  35. Properties prop = new Properties();
  36. prop.load(in);
  37. String driver = prop.getProperty("driver");
  38. resp.getOutputStream().write(driver.getBytes());
  39. }
  40. //读取web工程中资源文件的模板代码(源文件在工程的src目录下)
  41. private void test1(HttpServletResponse resp) throws IOException {
  42. InputStream in = this.getServletContext().getResourceAsStream("/WEB-INF/classes/db.properties");
  43. 注:源文件若在工程的WebRoot目录下,则上面参数路径直接为"/db.properties",因为WebRoot即代表web应用
  44. Properties prop = new Properties();
  45. prop.load(in);//先装载流
  46. String driver = prop.getProperty("driver");
  47. String url = prop.getProperty("url");
  48. String username = prop.getProperty("username");
  49. String password = prop.getProperty("password");
  50. resp.getOutputStream().write(driver.getBytes());
  51. }
  52. @Override
  53. protected void doPost(HttpServletRequest req, HttpServletResponse resp)
  54. throws ServletException, IOException {
  55. doGet(req, resp);
  56. }
  57. }

ServletConfig对象和ServletContext对象就介绍这么多吧,如有错误之处,欢迎留言指正~

相关阅读:http://blog.csdn.net/column/details/servletandjsp.html

_____________________________________________________________________________________________________________________________________________________

-----乐于分享,共同进步!

-----更多文章请看:http://blog.csdn.net/eson_15

Servlet的API(一)相关推荐

  1. spring mvc-使用Servlet原生API作为参数

    https://www.cnblogs.com/caoyc/p/5635701.html 具体看代码: @RequestMapping("/testServletAPI")publ ...

  2. struts2:在Action中使用Servlet的API,设置、读取各种内置对象的属性

    有两种方式可以实现在Action中使用Servlet的API.一种是使用org.apache.struts2.ServletActionContext类,另一种是使用com.opensymphony. ...

  3. Servlet编程API

    一.基本的servlet APIJavaEE关于Servlet的API主要有两个包:javax.servlet和javax.servlet.http.前者主要提供了Web容器能够使用的servlet基 ...

  4. (转)Struts2访问Servlet的API及......

    http://blog.csdn.net/yerenyuan_pku/article/details/67315598 Struts2访问Servlet的API 前面已经对Struts2的流程已经执行 ...

  5. Cris 学 SpringMVC(二):使用 servlet 原生 api 作为方法入参

    代码测试 /** 可以使用原生的 servlet 的api 作为目标方法的参数,具体支持以下类型* * HttpServletRequst* HttpServletResponse* HttpSess ...

  6. ssh备考-05Struts2 Action类下的重要API(原生Servlet的API、跳转配置、框架自身的数据封装、自定义拦截器)

    目录 一.Struts框架中如何使用原生Servlet的API 方法一.使用ActionContext类(完全解耦合的方式)(不好用,了解) demo1.jsp demo1Action.java    ...

  7. Servlet中文API文档-个人整理版

    Servlet中文API文档-个人整理版 一.Servlet 说明:servlet抽象集是javax.servlet.Servlet接口,它规定了必须由Servlet类实现由servlet引擎识别和管 ...

  8. JavaEE基础(02):Servlet核心API用法详解

    本文源码:GitHub·点这里 || GitEE·点这里 一.核心API简介 1.Servlet执行流程 Servlet是JavaWeb的三大组件之一(Servlet.Filter.Listener) ...

  9. Struts07---访问servlet的API

    01.创建登录界面 <%@ page language="java" import="java.util.*" pageEncoding="UT ...

最新文章

  1. 《机器学习》 周志华学习笔记第七章 贝叶斯分类器(课后习题)python 实现
  2. 信息学奥赛C++语言:格莱尔的香蕉
  3. centos7 如何重启web服务_如何重启web服务器
  4. 准备创建一个自己的校验提示Extender
  5. 第三章:3.9 引用Django 认证登陆
  6. machine learning之PCA、ICA
  7. 「实战篇」开源项目docker化运维部署-搭建mysql集群(四)
  8. 快手极速版自动评论脚本
  9. 软件架构之“道”和“术”哲学思考
  10. Jupyterhub batchspawner on PBS
  11. 百度相关搜索是怎么出现的如何利用
  12. spotlight ios_如何禁用iOS 10的Spotlight搜索历史记录
  13. 【软件测试】——软件测试经验总结
  14. java密码框转字符串_实现汉字的凯撒密码(内容包括:去掉字符串中的转义字符、汉字的unicode转换)...
  15. 用Python解决一个简单的数论问题——x分解为a^2+b^2
  16. Word制作生成html模板替换动态值为占位符使用Java转为pdf文件
  17. Dota2电竞数据API接口 - 【战队基本信息】API调用代码
  18. java中如何删除文件或清除文件夹下的所有文件
  19. 100集华为HCIE安全培训视频教材整理 | 防火墙互联技术(二)
  20. 阿里国际站详情页上装修轮播功能代码怎么做动画gif图片步骤教程方法技巧

热门文章

  1. 波士顿动力机器狗解锁“自动驾驶”,会跑步的Atlas真的很稳
  2. 奥巴马吐槽川普“笨蛋”的视频火了,这又得“归功”于AI
  3. AI在中国,还没到抢切蛋糕的时候
  4. 寒假作业3:抓老鼠啊~亏了还是赚了?
  5. Quick Switch Virtual Desktop[AutoHotkey]
  6. 11.06T1 DLZ常数剪枝+DP
  7. mysql与oracle语法对比(实用)
  8. WAF和IPS的区别
  9. vue.js的学习中的简单案例
  10. Android 连接SQLite