欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

javaweb Servlet开发总结(二)

程序员文章站 2024-03-11 20:57:37
一、servletconfig讲解 1.1、配置servlet初始化参数   在servlet的配置文件web.xml中,可以使用一个或多个

一、servletconfig讲解

1.1、配置servlet初始化参数

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

例如:

<servlet>
 <servlet-name>servletconfigdemo1</servlet-name>
 <servlet-class>gacl.servlet.study.servletconfigdemo1</servlet-class>
 <!--配置servletconfigdemo1的初始化参数 -->
 <init-param>
  <param-name>name</param-name>
  <param-value>gacl</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>

1.2、通过servletconfig获取servlet的初始化参数

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

例如:

package gacl.servlet.study;

import java.io.ioexception;
import java.util.enumeration;
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;
 
 /**
  * 当servlet配置了初始化参数后,web容器在创建servlet实例对象时,
  * 会自动将这些初始化参数封装到servletconfig对象中,并在调用servlet的init方法时,
  * 将servletconfig对象传递给servlet。进而,程序员通过servletconfig对象就可以
  * 得到当前servlet的初始化参数信息。
  */
 @override
 public void init(servletconfig config) throws servletexception {
  this.config = config;
 }

 public void doget(httpservletrequest request, httpservletresponse response)
   throws servletexception, ioexception {
  //获取在web.xml中配置的初始化参数
  string paramval = this.config.getinitparameter("name");//获取指定的初始化参数
  response.getwriter().print(paramval);
  
  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);
 }

}

运行结果如下:

javaweb Servlet开发总结(二)

二、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对象实现数据共享

package gacl.servlet.study;

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 servletcontextdemo1 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);
 }
}

package gacl.servlet.study;

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 servletcontextdemo2 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);
 }

 public void dopost(httpservletrequest request, httpservletresponse response)
   throws servletexception, ioexception {
  doget(request, response);
 }
}

  先运行servletcontextdemo1,将数据data存储到servletcontext对象中,然后运行servletcontextdemo2就可以从servletcontext对象中取出数据了,这样就实现了数据共享,如下图所示:

javaweb Servlet开发总结(二)

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

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

<?xml version="1.0" encoding="utf-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xsi:schemalocation="http://java.sun.com/xml/ns/javaee 
 http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
 <display-name></display-name>
 <!-- 配置web应用的初始化参数 -->
 <context-param>
  <param-name>url</param-name>
  <param-value>jdbc:mysql://localhost:3306/test</param-value>
 </context-param>

 <welcome-file-list>
  <welcome-file>index.jsp</welcome-file>
 </welcome-file-list>
</web-app>

获取web应用的初始化参数,代码如下:

package gacl.servlet.study;

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 servletcontextdemo3 extends httpservlet {

 public void doget(httpservletrequest request, httpservletresponse response)
   throws servletexception, ioexception {

  servletcontext context = this.getservletcontext();
  //获取整个web站点的初始化参数
  string contextinitparam = context.getinitparameter("url");
  response.getwriter().print(contextinitparam);
 }

 public void dopost(httpservletrequest request, httpservletresponse response)
   throws servletexception, ioexception {
  doget(request, response);
 }

}

运行结果:

javaweb Servlet开发总结(二)

3.3、用servletcontext实现请求转发

servletcontextdemo4

package gacl.servlet.study;

import java.io.ioexception;
import java.io.printwriter;
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 servletcontextdemo4 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("/servlet/servletcontextdemo5");//获取请求转发对象(requestdispatcher)
  rd.forward(request, response);//调用forward方法实现请求转发
 }

 public void dopost(httpservletrequest request, httpservletresponse response)
   throws servletexception, ioexception {
 }
}

servletcontextdemo5

package gacl.servlet.study;

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 {

 public void doget(httpservletrequest request, httpservletresponse response)
   throws servletexception, ioexception {
  response.getoutputstream().write("servletdemo5".getbytes());
 }

 public void dopost(httpservletrequest request, httpservletresponse response)
   throws servletexception, ioexception {
  this.doget(request, response);
 }

}

运行结果:

javaweb Servlet开发总结(二)

访问的是servletcontextdemo4,浏览器显示的却是servletcontextdemo5的内容,这就是使用servletcontext实现了请求转发

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

项目目录结构如下:

   javaweb Servlet开发总结(二)

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

package gacl.servlet.study;

import java.io.fileinputstream;
import java.io.filenotfoundexception;
import java.io.ioexception;
import java.io.inputstream;
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;

/**
 * 使用servletcontext读取资源文件
 * 
 * @author gacl
 * 
 */
public class servletcontextdemo6 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");
  readsrcdirpropcfgfile(response);//读取src目录下的properties配置文件
  response.getwriter().println("<hr/>");
  readwebrootdirpropcfgfile(response);//读取webroot目录下的properties配置文件
  response.getwriter().println("<hr/>");
  readpropcfgfile(response);//读取src目录下的db.config包中的db3.properties配置文件
  response.getwriter().println("<hr/>");
  readpropcfgfile2(response);//读取src目录下的gacl.servlet.study包中的db4.properties配置文件
  
 }

 /**
  * 读取src目录下的gacl.servlet.study包中的db4.properties配置文件
  * @param response
  * @throws ioexception
  */
 private void readpropcfgfile2(httpservletresponse response)
   throws ioexception {
  inputstream in = this.getservletcontext().getresourceasstream("/web-inf/classes/gacl/servlet/study/db4.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));
 }

 /**
  * 读取src目录下的db.config包中的db3.properties配置文件
  * @param response
  * @throws filenotfoundexception
  * @throws ioexception
  */
 private void readpropcfgfile(httpservletresponse response)
   throws filenotfoundexception, ioexception {
  //通过servletcontext获取web资源的绝对路径
  string path = this.getservletcontext().getrealpath("/web-inf/classes/db/config/db3.properties");
  inputstream in = new fileinputstream(path);
  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目录下的db.config包中的db3.properties配置文件:");
  response.getwriter().println(
    messageformat.format(
      "driver={0},url={1},username={2},password={3}", 
      driver,url, username, password));
 }

 /**
  * 通过servletcontext对象读取webroot目录下的properties配置文件
  * @param response
  * @throws ioexception
  */
 private void readwebrootdirpropcfgfile(httpservletresponse response)
   throws ioexception {
  /**
   * 通过servletcontext对象读取webroot目录下的properties配置文件
   * “/”代表的是项目根目录
   */
  inputstream in = this.getservletcontext().getresourceasstream("/db2.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("读取webroot目录下的db2.properties配置文件:");
  response.getwriter().print(
    messageformat.format(
      "driver={0},url={1},username={2},password={3}", 
      driver,url, username, password));
 }

 /**
  * 通过servletcontext对象读取src目录下的properties配置文件
  * @param response
  * @throws ioexception
  */
 private void readsrcdirpropcfgfile(httpservletresponse response) throws ioexception {
  /**
   * 通过servletcontext对象读取src目录下的db1.properties配置文件
   */
  inputstream in = this.getservletcontext().getresourceasstream("/web-inf/classes/db1.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));
 }

 public void dopost(httpservletrequest request, httpservletresponse response)
   throws servletexception, ioexception {
  this.doget(request, response);
 }

}

运行结果如下:

javaweb Servlet开发总结(二)

代码范例:使用类装载器读取资源文件

package gacl.servlet.study;

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;

/**
 * 用类装载器读取资源文件
 * 通过类装载器读取资源文件的注意事项:不适合装载大文件,否则会导致jvm内存溢出
 * @author gacl
 *
 */
public class servletcontextdemo7 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/>");
  //test3();
  test4();
  
 }
 
 /**
  * 读取类路径下的资源文件
  * @param response
  * @throws ioexception
  */
 private void test1(httpservletresponse response) throws ioexception {
  //获取到装载当前类的类装载器
  classloader loader = servletcontextdemo7.class.getclassloader();
  //用类装载器读取src目录下的db1.properties配置文件
  inputstream in = loader.getresourceasstream("db1.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 = servletcontextdemo7.class.getclassloader();
  //用类装载器读取src目录下的gacl.servlet.study包中的db4.properties配置文件
  inputstream in = loader.getresourceasstream("gacl/servlet/study/db4.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内存溢出
  */
 public void test3() {
  /**
   * 01.avi是一个150多m的文件,使用类加载器去读取这个大文件时会导致内存溢出:
   * java.lang.outofmemoryerror: java heap space
   */
  inputstream in = servletcontextdemo7.class.getclassloader().getresourceasstream("01.avi");
  system.out.println(in);
 }
 
 /**
  * 读取01.avi,并拷贝到e:\根目录下
  * 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.avi");
  /**
   * path.lastindexof("\\") + 1是一个非常绝妙的写法
   */
  string filename = path.substring(path.lastindexof("\\") + 1);//获取文件名
  inputstream in = this.getservletcontext().getresourceasstream("/web-inf/classes/01.avi");
  byte buffer[] = new byte[1024];
  int len = 0;
  outputstream out = new fileoutputstream("e:\\" + 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);
 }

}

运行结果如下:

javaweb Servlet开发总结(二)

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

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

package gacl.servlet.study;

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 servletdemo5 extends httpservlet {

 public void doget(httpservletrequest request, httpservletresponse response)
   throws servletexception, ioexception {
  string data = "abcddfwerwesfasfsadf";
  /**
   * 设置数据合理的缓存时间值,以避免浏览器频繁向服务器发送请求,提升服务器的性能
   * 这里是将数据的缓存时间设置为1天
   */
  response.setdateheader("expires",system.currenttimemillis() + 24 * 3600 * 1000);
  response.getoutputstream().write(data.getbytes());
 }

 public void dopost(httpservletrequest request, httpservletresponse response)
   throws servletexception, ioexception {

  this.doget(request, response);
 }

}

javaweb Servlet开发总结(二)

以上就是本文的全部内容,希望对大家掌握javaweb servlet开发技术有所帮助。