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类,在配置文件里进行如下配置:

<servlet>
    <servlet-name>ServletConfigDemo1</servlet-name>
    <servlet-class>servletConfig.ServletConfigDemo1</servlet-class>
    <init-param>
	<param-name>category</param-name>
	<param-value>book</param-value>
    </init-param> 	
    <init-param>
	<param-name>school</param-name>
	<param-value>tongji</param-value>
    </init-param> 	
    <init-param>
	<param-name>name</param-name>
	<param-value>java</param-value>
    </init-param>    	
</servlet>
<servlet-mapping>
    <servlet-name>ServletConfigDemo1</servlet-name>
    <url-pattern>/ServletConfigDemo1</url-pattern>
</servlet-mapping>
        在ServletConfigDemo1.java中的代码如下:

public class ServletConfigDemo1 extends HttpServlet {
	ServletConfig config = null;	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String value = config.getInitParameter("category");//获取指定的初始化参数
		resp.getOutputStream().write((value + "<br/>").getBytes());
		
		Enumeration e = config.getInitParameterNames();//获取所有参数名
		while(e.hasMoreElements()){
			String name = (String) e.nextElement();
			value = config.getInitParameter(name);
			resp.getOutputStream().write((name + "=" + value + "<br/>").getBytes());
		}
	}
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doGet(req, resp);
	}
	@Override
	public void init(ServletConfig config) throws ServletException {		
		this.config = config; //初始化时会将ServletConfig对象传进来
	}
}
        在浏览器中输入:http://localhost:8080/test/ServletConfigDemo1,即可在浏览器中显示读取参数的结果。

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

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对象:

this.getServletConfig().getServletContext();
this.getServletContext();
        一般直接获得即可。
        由于一个web应用中的所有Servlet共享同一个ServletContext对象,因此Servlet对象之间可以通过ServletContext对象来实现通讯,ServletContext对象通常也被称为context域对象。有如下主要方法:
getResource(String path); //方法获得工程里的某个资源
getResourceAsStream(String path); //通过路径获得跟资源相关联的流
setAttribute(Sring name, Object obj); //方法往ServletContext里存对象,通过MAP集合来保存。
getAttribute(String name); //方法从MAP中取对象
getInitParameter(String name); //获得整个web应用的初始化参数,
//这个跟ServletConfig获取参数不同,这是在<context-param></context-param>中定义的,config对象里的getInitParameter方法获得的是具体某个servlet的初始化参数。
getNamedeDispatcher(String name); //方法用于将请求转给另一个servlet处理,参数表示要转向的servlet。
//调用该方法后,要紧接着调用forward(ServletRequest request, ServletResponse response)方法
getServletContextName(); // 获得web应用的名称。
        ServletContext应用有哪些呢?
         1)多个Servlet通过ServletContext对象实现数据共享(见下面的Demo1和Demo2)
         2)获取web应用的初始化参数(见Demo3)
         3)实现Servlet的转发(见Demo4和Demo5)
         4)利用ServletContext对象读取资源文件(xml或者properties)(见Demo6)

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

Demo1:往context域中存入数据

public class ServletContextDemo1 extends HttpServlet {
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {		
		String data = "adddfdf";
		ServletContext context = this.getServletConfig().getServletContext();
		context.setAttribute("data", data);//将数据写到ServletContext
	}
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doGet(req, resp);
	}	
}
Demo2:从context域中读取数据

public class ServletContextDemo2 extends HttpServlet {
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {		
		ServletContext context = this.getServletContext();
		String data = (String) context.getAttribute("data");//通过键值从ServletContext中获取刚才存入的数据
		resp.getOutputStream().write(data.getBytes());
	}
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		doGet(req, resp);		
	}	
}
Demo3:获取整个web应用的初始化参数

public class ServletContextDemo3 extends HttpServlet {
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		ServletContext context = this.getServletContext();
		String url = context.getInitParameter("url");//获取整个web应用的初始化参数,参数是在<context-param></context-param>中定义的
		resp.getOutputStream().write(url.getBytes());
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		doGet(req, resp);		
	}		
}
Demo4:实现转发

public class ServletContextDemo5 extends HttpServlet {
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		ServletContext context = this.getServletContext();
		RequestDispatcher rd = context.getRequestDispatcher("/ServletContextDemo5");
		rd.forward(req, resp);//将请求转发给ServletContextDemo5.java处理
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doGet(req, resp);
	}	
}
Demo5:

public class ServletContextDemo5 extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		resp.getOutputStream().write("ServletDemo5".getBytes());//处理ServletDemo4传过来的请求
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doGet(req, resp);
	}
	
}
Demo6:读取资源文件

public class ServletContextDemo6 extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		//test1(resp);
		//test2(resp);
		//test3(resp);
		//test4();
	}
	
	//读取文件,并将文件拷贝到e:\根目录,如果文件太大,只能用servletContext,不能用类装载器
	private void test4() throws FileNotFoundException, IOException {
		String path = this.getServletContext().getRealPath("/WEB-INF/classes/db.properties");
		String filename = path.substring(path.lastIndexOf("\\")+1);
		
		InputStream in = this.getServletContext().getResourceAsStream("/WEB-INF/classes/db.properties");
		byte buffer[] = new byte[1024];
		int len = 0;
		
		FileOutputStream out = new FileOutputStream("e:\\" + filename);
		while((len = in.read(buffer)) > 0){
			out.write(buffer, 0, len);
		}
	}

	//使用类装载器读取源文件(不适合装载大文件)
	private void test3(HttpServletResponse resp) throws IOException {
		ClassLoader loader = ServletContextDemo6.class.getClassLoader();
		InputStream in = loader.getResourceAsStream("db.properties");
		Properties prop = new Properties();
		prop.load(in);
		String driver = prop.getProperty("driver");
		resp.getOutputStream().write(driver.getBytes());
	}

	private void test2(HttpServletResponse resp) throws FileNotFoundException,
					IOException {
		String path = this.getServletContext().getRealPath("/WEB-INF/classes/db.properties");//获取绝对路径
		FileInputStream in = new FileInputStream(path);//传统方法,参数为绝对路径
		
		Properties prop = new Properties();
		prop.load(in);
		String driver = prop.getProperty("driver");
		resp.getOutputStream().write(driver.getBytes());
	}

	//读取web工程中资源文件的模板代码(源文件在工程的src目录下)
	private void test1(HttpServletResponse resp) throws IOException {
		InputStream in = this.getServletContext().getResourceAsStream("/WEB-INF/classes/db.properties");
		////注:源文件若在工程的WebRoot目录下,则上面参数路径直接为"/db.properties",因为WebRoot即代表web应用
		Properties prop = new Properties();
		prop.load(in);//先装载流
		String driver = prop.getProperty("driver");
		String url = prop.getProperty("url");
		String username = prop.getProperty("username");
		String password = prop.getProperty("password");
		resp.getOutputStream().write(driver.getBytes());
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doGet(req, resp);
	}	
}
        ServletConfig对象和ServletContext对象就介绍这么多吧,如有错误之处,欢迎留言指正~

_____________________________________________________________________________________________________________________________________________________

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

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

你可能感兴趣的:(servlet,api,servletContext,servletconfig)