signed

QiShunwang

“诚信为本、客户至上”

ServletConfig讲解

2021/5/14 23:13:19   来源:

一、ServletConfig讲解

1.1、配置Servlet初始化参数

  在Servlet的配置文件web.xml中,可以使用一个或多个<init-param>标签为servlet配置一些初始化参数。

例如:

<servlet>
   <servlet-name>ServletConfigDemo1</servlet-name>
      <servlet-class>com.servlet.test.ServletConfigDemo1</servlet-class>
      <!--配置ServletConfigDemo1的初始化参数 -->
      <init-param>
          <param-name>name</param-name>
         <param-value>abc</param-value>
     </init-param>
       <init-param>
         <param-name>password</param-name>
         <param-value>123</param-value>
     </init-param>
     <init-param>
         <param-name>charset</param-name>
         <param-value>UTF-8</param-value>
     </init-param> 
</servlet>
<servlet-mapping>
	<servlet-name>ServletConfigDemo1</servlet-name>
	<url-pattern>/ServletConfigDemo1</url-pattern>
</servlet-mapping>

1.2、通过ServletConfig获取Servlet的初始化参数

  当servlet配置了初始化参数后,web容器在创建servlet实例对象时,会自动将这些初始化参数封装到ServletConfig对象中,并在调用servlet的init方法时,将ServletConfig对象传递给servlet。进而,我们通过ServletConfig对象就可以得到当前servlet的初始化参数信息。

例子代码如下:

package com.servlet.test;

import java.io.IOException;
import java.util.Enumeration;

import javax.servlet.ServletContext;
import javax.servlet.ServletConfig;


import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ServletConfigDemo1 extends HttpServlet {
	
	//定义ServletConfig对象来接收配置的初始化参数
	private ServletConfig config;
	
	@Override
	public void init(ServletConfig config) throws ServletException {
         this.config = config;
    }
	
	
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
//		super.doGet(request, response);
		System.out.println("this.config.getServletName()="+this.config.getServletName() );//这行代码输出的是  this.config.getServletName()=ServletConfigDemo1
		//获取在web.xml中配置的初始化参数
		String paramVal = this.config.getInitParameter("name");//获取指定的初始化参数
		response.getWriter().print(paramVal);
		response.getWriter().print("<br/>");
//		response.getWriter().print(this.config.getServletContext());
		response.getWriter().print("<hr/>");
		//获取所有的初始化参数
		Enumeration<String> e = config.getInitParameterNames();
		while(e.hasMoreElements()){
		    String name = e.nextElement();
		    String value = config.getInitParameter(name);
		    response.getWriter().print(name + "=" + value + "<br/>");
        }
	}
	 
     public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
         this.doGet(request, response);
     }
	 
	
}

运行结果如下:

 

二、ServletContext对象

  WEB容器在启动时,它会为每个WEB应用程序都创建一个对应的ServletContext对象,它代表当前web应用。
  ServletConfig对象中维护了ServletContext对象的引用,开发人员在编写servlet时,可以通过ServletConfig.getServletContext方法获得ServletContext对象。
  由于一个WEB应用中的所有Servlet共享同一个ServletContext对象,因此Servlet对象之间可以通过ServletContext对象来实现通讯。ServletContext对象通常也被称之为context域对象。

三、ServletContext的应用

  3.1、多个Servlet通过ServletContext对象实现数据共享

  范例:ServletContextDemo1和ServletContextDemo2通过ServletContext对象实现数据共享

下面是例子:

继续在web.xml配置:

<servlet>
    <servlet-name>ServletConfigDemo2</servlet-name>
    <servlet-class>com.servlet.test.ServletConfigDemo2</servlet-class>
</servlet>
<servlet-mapping>
	<servlet-name>ServletConfigDemo2</servlet-name>
	<url-pattern>/ServletConfigDemo2</url-pattern>
</servlet-mapping>
	
	
<servlet>
	<servlet-name>ServletConfigDemo3</servlet-name>
    <servlet-class>com.servlet.test.ServletConfigDemo3</servlet-class>
</servlet>
<servlet-mapping>
	<servlet-name>ServletConfigDemo3</servlet-name>
	<url-pattern>/ServletConfigDemo3</url-pattern>
</servlet-mapping>

下面是ServletConfigDemo2代码:

package com.servlet.test;

import java.io.IOException;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ServletConfigDemo2 extends HttpServlet{
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
         String data = "xdp_gacl";
         /**
          * ServletConfig对象中维护了ServletContext对象的引用,开发人员在编写servlet时,
          * 可以通过ServletConfig.getServletContext方法获得ServletContext对象。
          */
         ServletContext context = this.getServletConfig().getServletContext();//获得ServletContext对象
         context.setAttribute("data", data);  //将data存储到ServletContext对象中
     }
	 
     
	public void doPost(HttpServletRequest request, HttpServletResponse response)
             throws ServletException, IOException {
         doGet(request, response);
     }

}

下面是ServletConfigDemo3代码:

package com.servlet.test;

import java.io.IOException;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ServletConfigDemo3 extends HttpServlet{
	
	 public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
	          ServletContext context = this.getServletContext();
	          String data = (String) context.getAttribute("data");//从ServletContext对象中取出数据
	          response.getWriter().print("data="+data);
	          System.out.println("data="+data);
     }
	  
     public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
          doGet(request, response);
     }
}

我们先运行ServletConfigDemo2代码,然后运行ServletConfigDemo3代码,看看能不能成功取出data的数据:

运行结果如下:

 

3.2、获取WEB应用的初始化参数

  在web.xml文件中使用<context-param>标签配置WEB应用的初始化参数,如下所示:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	version="2.5">

<display-name>Spring MVC Application</display-name>
     <!--监听器
     <listener>
		<listener-class>com.listener.TestListener</listener-class>
	</listener>
	-->
     
      <context-param>
          <param-name>url</param-name>
          <param-value>jdbc:mysql://localhost:3306/database</param-value>
      </context-param>

     <context-param>
    	<!-- 这个contextConfigLocation参数是用来加载spring相关配置的标签 -->
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:com/config/spring/applicationContext.xml</param-value>
    </context-param>
</web-app>

现在我们要获取<context-param>标签里面的值:,下面是代码:

package com.servlet.test;

import java.io.IOException;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/*
 * 用ServletContext读取整个web站点的初始化参数
 * */

public class ServletContextDemo1 extends HttpServlet{
	
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
	 
	     ServletContext context = this.getServletContext();
	     //获取整个web站点的初始化参数
	     String contextInitParam1 = context.getInitParameter("url");
	     response.getWriter().println(contextInitParam1);
	     
	     String contextInitParam2 = context.getInitParameter("contextConfigLocation");
	     response.getWriter().println(contextInitParam2);
         //System.out.println("contextInitParam="+contextInitParam);
     }
 
     public void doPost(HttpServletRequest request, HttpServletResponse response)
             throws ServletException, IOException {
         doGet(request, response);
     }
}

运行代码,效果如下:

 

3.3、用servletContext实现请求转发

编写ServletContextDemo2程序,然后跳转到ServletContextDemo3页面

先配置web.xml文件,在web.xml文件添加以下代码
 

<servlet>
    <servlet-name>ServletConfigDemo2</servlet-name>
    <servlet-class>com.servlet.test.ServletConfigDemo2</servlet-class>
</servlet>
<servlet-mapping>
	<servlet-name>ServletConfigDemo2</servlet-name>
	<url-pattern>/ServletConfigDemo2</url-pattern>
</servlet-mapping>
	
<servlet>
    <servlet-name>ServletConfigDemo3</servlet-name>
    <servlet-class>com.servlet.test.ServletConfigDemo3</servlet-class>
</servlet>
<servlet-mapping>
	<servlet-name>ServletConfigDemo3</servlet-name>
	<url-pattern>/ServletConfigDemo3</url-pattern>
</servlet-mapping>

下面是ServletContextDemo2代码

package com.servlet.test;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ServletContextDemo2 extends HttpServlet{
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
         String data = "<h1><font color='red'>abcdefghjkl</font></h1>";
         response.getOutputStream().write(data.getBytes());
         ServletContext context = this.getServletContext();//获取ServletContext对象
         RequestDispatcher rd = context.getRequestDispatcher("/ServletContextDemo3");//获取请求转发对象(RequestDispatcher)
         rd.forward(request, response);//调用forward方法实现请求转发
     }
	 
     public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
    	 doGet(request,response);
     }
}

下面是ServletContextDemo3代码

package com.servlet.test;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ServletContextDemo3 extends HttpServlet{
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
		response.getOutputStream().write("ServletContextDemo3".getBytes());
    }
 
     public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
         this.doGet(request, response);
     }
}

效果如下:

成功跳转

3.4、利用ServletContext对象读取资源文件

代码范例:使用servletContext读取资源文件

先配置web.xml文件,在web.xml文件添加以下代码:

	<servlet>
		<servlet-name>ServletContextDemo4</servlet-name>
    	<servlet-class>com.servlet.test.ServletContextDemo4</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>ServletContextDemo4</servlet-name>
		<url-pattern>/ServletContextDemo4</url-pattern>
	</servlet-mapping>

以下是要读取的文件的位置

以下是要读取的文件的内容:

#mysql jdbc
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/library?useUnicode=true&characterEncoding=UTF-8
username=root
password=123

以下是代码:

package com.servlet.test;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.MessageFormat;
import java.util.Properties;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ServletContextDemo4 extends HttpServlet{
	
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
	         /**
	           * response.setContentType("text/html;charset=UTF-8");目的是控制浏览器用UTF-8进行解码;
	           * 这样就不会出现中文乱码了
	           */
	        response.setHeader("content-type","text/html;charset=UTF-8");
	        test1(response);
	        response.getWriter().println("<hr/>");
	        test2(response);
	        response.getWriter().println("<hr/>");
	          try {
			//	test3();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	         test4();
	         

	 }
	      
	      /**
	       * 读取类路径下的资源文件
	       * @param response
	       * @throws IOException
	       */
      private void test1(HttpServletResponse response) throws IOException {
          //获取到装载当前类的类装载器
          ClassLoader loader = ServletContextDemo4.class.getClassLoader();
          //用类装载器读取src目录下的db1.properties配置文件
          InputStream in = loader.getResourceAsStream("db.properties");
          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");
          response.getWriter().println("用类装载器读取src目录下的db1.properties配置文件:");
          response.getWriter().println(MessageFormat.format(
                          "driver={0},url={1},username={2},password={3}", 
                          driver,url, username, password));
      }
  
	      /**
	       * 读取类路径下面、包下面的资源文件
	       * @param response
	       * @throws IOException
	       */
	      private void test2(HttpServletResponse response) throws IOException {
	          //获取到装载当前类的类装载器
	          ClassLoader loader = ServletContextDemo4.class.getClassLoader();
	          //用类装载器读取src目录下的gacl.servlet.study包中的db4.properties配置文件
	          InputStream in = loader.getResourceAsStream("com/servlet/test/db.properties");
	          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");
	          response.getWriter().println("用类装载器读取src目录下的gacl.servlet.study包中的db4.properties配置文件:");
	          response.getWriter().println(
	                  MessageFormat.format(
	                          "driver={0},url={1},username={2},password={3}", 
	                          driver,url, username, password));
	      }
	      
	      /**
	       * 通过类装载器读取资源文件的注意事项:不适合装载大文件,否则会导致jvm内存溢出
	     * @throws IOException 
	       */
	      public void test3() throws Exception {
	          /**114115116117118
	           * 01.mp4是一个1.74G的文件,按道理使用类加载器去读取这个大文件时会导致内存溢出:
	           * java.lang.OutOfMemoryError: Java heap space
	           *
          */
	    	  try{
	    		  byte buffer[] = new byte[1024];
	  		      int len = 0;
	  	    	  String filename = "01.mp4";//获取文件名
	  	    	  InputStream in = ServletContextDemo4.class.getClassLoader().getResourceAsStream("01.mp4");
	  	    	  System.out.println("test3="+in);
	  	    	  OutputStream out = new FileOutputStream("D:\\" + filename);
	  	    	  while ((len = in.read(buffer)) > 0) {
	  	    		  out.write(buffer, 0, len);
	  	    	  }
	  	    	  out.close();
	  	    	  in.close();
	    	  }catch(Exception e){
	    		  e.printStackTrace();
	    	  }
	    	
	      }
	      
	      /**
	       * 读取01.avi,并拷贝到D:\根目录下
	       * 01.avi文件太大,只能用servletContext去读取
	      * @throws IOException
	      */
	     public void test4() throws IOException {
	         // path=G:\Java学习视频\JavaWeb学习视频\JavaWeb\day05视频\01.avi
	         // path=01.avi
	         String path = this.getServletContext().getRealPath("/WEB-INF/classes/01.mp4");
	         /**
	          * path.lastIndexOf("\\") + 1是一个非常绝妙的写法
	          */
	         String filename = path.substring(path.lastIndexOf("\\") + 1);//获取文件名
	         InputStream in = this.getServletContext().getResourceAsStream("/WEB-INF/classes/01.mp4");
	         byte buffer[] = new byte[1024];
	         int len = 0;
	         OutputStream out = new FileOutputStream("D:\\" + filename);
	         while ((len = in.read(buffer)) > 0) {
	             out.write(buffer, 0, len);
	         }
	         out.close();
	         in.close();
	     }
	 
	     public void doPost(HttpServletRequest request, HttpServletResponse response)
	             throws ServletException, IOException {
	 
	         this.doGet(request, response);
	     }
	 
	 }

运行,效果如下

四、在客户端缓存Servlet的输出

  对于不经常变化的数据,在servlet中可以为其设置合理的缓存时间值,以避免浏览器频繁向服务器发送请求,提升服务器的性能。

在web.xml添加配置:

	<servlet>
		<servlet-name>ServletContextDemo5</servlet-name>
    	<servlet-class>com.servlet.test.ServletContextDemo5</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>ServletContextDemo5</servlet-name>
		<url-pattern>/ServletContextDemo5</url-pattern>
	</servlet-mapping>

代码如下:

package com.servlet.test;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ServletContextDemo5 extends HttpServlet {
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String data = "mytest";
        resp.setDateHeader("expires",System.currentTimeMillis() + 48 * 3600 * 1000);
        /**
         * 设置数据合理的缓存时间值,以避免浏览器频繁向服务器发送请求,提升服务器的性能
         * 这里是将数据的缓存时间设置为2天
         */
        resp.getWriter().println(data);
    }

	@Override
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        this.doGet(request, response);
    }
}