Servlet的API(一)

简介:

目录(?)[+]

        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 plain  copy
  在CODE上查看代码片 派生到我的代码片
  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 plain  copy
  在CODE上查看代码片 派生到我的代码片
  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.           
  9.         Enumeration e = config.getInitParameterNames();//获取所有参数名  
  10.         while(e.hasMoreElements()){  
  11.             String name = (String) e.nextElement();  
  12.             value = config.getInitParameter(name);  
  13.             resp.getOutputStream().write((name + "=" + value + "<br/>").getBytes());  
  14.         }  
  15.     }  
  16.     @Override  
  17.     protected void doPost(HttpServletRequest req, HttpServletResponse resp)  
  18.             throws ServletException, IOException {  
  19.         doGet(req, resp);  
  20.     }  
  21.     @Override  
  22.     public void init(ServletConfig config) throws ServletException {          
  23.         this.config = config; //初始化时会将ServletConfig对象传进来  
  24.     }  
  25. }  
        在浏览器中输入:http://localhost:8080/test/ServletConfigDemo1,即可在浏览器中显示读取参数的结果。

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

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  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 plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. this.getServletConfig().getServletContext();  
  2. this.getServletContext();  
        一般直接获得即可。
        由于一个web应用中的所有Servlet共享同一个ServletContext对象,因此Servlet对象之间可以通过ServletContext对象来实现通讯,ServletContext对象通常也被称为context域对象。有如下主要方法:
[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  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 plain  copy
  在CODE上查看代码片 派生到我的代码片
  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 plain  copy
  在CODE上查看代码片 派生到我的代码片
  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.           
  13.         doGet(req, resp);         
  14.     }     
  15. }  
Demo3:获取整个web应用的初始化参数

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. public class ServletContextDemo3 extends HttpServlet {  
  2.     @Override  
  3.     protected void doGet(HttpServletRequest req, HttpServletResponse resp)  
  4.             throws ServletException, IOException {  
  5.   
  6.         ServletContext context = this.getServletContext();  
  7.         String url = context.getInitParameter("url");//获取整个web应用的初始化参数,参数是在<context-param></context-param>中定义的  
  8.         resp.getOutputStream().write(url.getBytes());  
  9.     }  
  10.   
  11.     @Override  
  12.     protected void doPost(HttpServletRequest req, HttpServletResponse resp)  
  13.             throws ServletException, IOException {  
  14.   
  15.         doGet(req, resp);         
  16.     }         
  17. }  
Demo4:实现转发

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  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.   
  10.     @Override  
  11.     protected void doPost(HttpServletRequest req, HttpServletResponse resp)  
  12.             throws ServletException, IOException {  
  13.         doGet(req, resp);  
  14.     }     
  15. }  
Demo5:

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. public class ServletContextDemo5 extends HttpServlet {  
  2.   
  3.     @Override  
  4.     protected void doGet(HttpServletRequest req, HttpServletResponse resp)  
  5.             throws ServletException, IOException {  
  6.         resp.getOutputStream().write("ServletDemo5".getBytes());//处理ServletDemo4传过来的请求  
  7.     }  
  8.   
  9.     @Override  
  10.     protected void doPost(HttpServletRequest req, HttpServletResponse resp)  
  11.             throws ServletException, IOException {  
  12.         doGet(req, resp);  
  13.     }  
  14.       
  15. }  
Demo6:读取资源文件

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

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

_____________________________________________________________________________________________________________________________________________________

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

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


相关文章
|
6月前
|
API
05JavaWeb基础 - Servlet的相关API
05JavaWeb基础 - Servlet的相关API
20 0
|
3月前
|
JSON Java 应用服务中间件
|
8月前
|
JSON 应用服务中间件 API
【计算机网络】Servlet API重点知识汇总
【计算机网络】Servlet API重点知识汇总
|
9月前
|
网络协议 应用服务中间件 API
Servlet的常用Api—HttpServletResponse
Servlet的常用Api—HttpServletResponse
Servlet的常用Api—HttpServletResponse
|
10月前
|
JSON 编解码 前端开发
【JavaEE】Servlet的API详解
【JavaEE】Servlet的API详解
72 0
|
11月前
|
API
java202304java学习笔记第六十二天-ssm-获取servlet相关api
java202304java学习笔记第六十二天-ssm-获取servlet相关api
57 0
|
11月前
|
API
java202304java学习笔记第六十二天-ssm-获取servlet相关api
java202304java学习笔记第六十二天-ssm-获取servlet相关api
67 0
|
应用服务中间件 API
Servlet API 详解
Servlet API 详解
214 0
Servlet API 详解
|
应用服务中间件 API 容器
Servlet入门案例(三)Servlet的生命周期、api和请求方式、工作原理、注解开发
Servlet入门案例(三)Servlet的生命周期、api和请求方式、工作原理、注解开发
93 0
Servlet入门案例(三)Servlet的生命周期、api和请求方式、工作原理、注解开发
|
前端开发 Java API
Spring MVC框架:第二章:视图解析器和@RequestMapping注解使用在类级别及获取原生Servlet API对象
Spring MVC框架:第二章:视图解析器和@RequestMapping注解使用在类级别及获取原生Servlet API对象
239 0