一、ServletConfig详解
1.1 配置Servlet初始化参数
在Servlet的配置文件中,可以使用一个或多个
标签为servlet配置一些初始化参数,例如:
ServletConfigDemo1
rain.servlet.study.ServletConfigDemo1
name
rain
score
140
age
18
1.2 通过ServletConfig获取初始化参数
当Servlet配置了初始化参数以后,web容器在创建servlet实例对象时,会自动将这些参数封装到ServletConfig对象中去,并且在调用Servlet的init方法时会将ServletConfig传递过去。因此我们可以通过ServletConfig对象就可以得到配置的初始化参数信息了。不过现在有了servlet3.0之后,有两种写法了。例如:
package rain.servlet.study;
import java.io.IOException;
import java.util.Enumeration;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class ServletConfigDemo1
*/
//@WebServlet(urlPatterns="/ServletConfigDemo1",initParams= {
// @WebInitParam(name="name",value="rain"),
// @WebInitParam(name="score",value="100"),
// @WebInitParam(name="age",value="18")
//})
public class ServletConfigDemo1 extends HttpServlet {
private static final long serialVersionUID = 1L;
private ServletConfig config;
/**
* 当servlet配置了初始化参数时,web容器在创建servlet实例对象时会自动将这些初始化参数封装到servletconfig
* 对象中,并在调用servlet的init方法时,将改对象传递给servlet
*/
@Override
public void init(ServletConfig config) throws ServletException {
// TODO Auto-generated method stub
// super.init(config);
this.config = config;
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
// response.getWriter().append("Served at: ").append(request.getContextPath());
response.setContentType("text/html;charset=utf-8");
String paramVal = this.config.getInitParameter("name");
response.getWriter().print(paramVal);
response.getWriter().print("
");
//获取所有的初始化参数
Enumeration e = config.getInitParameterNames();
while(e.hasMoreElements()) {
String name = e.nextElement();
String value = config.getInitParameter(name);
response.getWriter().print(name + "=" + value + "
");
}
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
上面注释掉的部分就是Servlet 3.0之后采用注解的形式,可以看到还是挺方便的。运行结果如下:
二、ServletContext对象
web容器在启动时,它会为每个web应用创建一个对应的ServletContext对象,它代表当前web应用。
ServletConfig对象中维护了ServletContext对象的引用,可以通过ServletConfig.getServletContext
获得。
由于一个web应用所有的servlet都共享同一个ServletContext,因此servlet对象之间可以实现通讯。ServletContext对象通常也被称之为context域对象
三、ServletContext的应用
3.1 多个servlet通过 ServletContext 来实现数据共享
下面是一个例子,两个servlet通过Servletc实现数据共享
package rain.servlet.study;
import java.io.IOException;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class RainServletContextDemo1
*/
@WebServlet("/RainServletContextDemo1")
public class RainServletContextDemo1 extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
// response.getWriter().append("Served at: ").append(request.getContextPath());
String data = "rain_sample_data";
/**
* ServletConfig对象中维护了ServletContext的引用,可以通过
* getServletConfig().getServletContext()来获取到。
*/
ServletContext context = this.getServletConfig().getServletContext();
context.setAttribute("data", data);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
下面是另外一个Servlet
package rain.servlet.study;
import java.io.IOException;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class RainServletContextDemo2
*/
@WebServlet("/RainServletContextDemo2")
public class RainServletContextDemo2 extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
// response.getWriter().append("Served at: ").append(request.getContextPath());
ServletContext context = getServletContext();
String data = (String) context.getAttribute("data");//从ServletContext对象中取出数据
response.getWriter().print("data="+data);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
先运行RainServletContextDemo1,然后再运行RainServletContextDemo2,即可以实现数据的共享。运行结果如下:
3.2 用ServletContext对象实现请求转发
RainServletContextDemo3
package rain.servlet.study;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class RainServletContextDemo3
*/
@WebServlet("/RainServletContextDemo3")
public class RainServletContextDemo3 extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
// response.getWriter().append("Served at: ").append(request.getContextPath());
String data = "i am servlet3";
response.getOutputStream().write(data.getBytes());
ServletContext context = getServletContext();
RequestDispatcher dispatcher = context.getRequestDispatcher("/RainServletContextDemo4");
dispatcher.forward(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
RainServletContextDemo4
package rain.servlet.study;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class RainServletContextDemo4
*/
@WebServlet("/RainServletContextDemo4")
public class RainServletContextDemo4 extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.getOutputStream().write("i am servlet4 hia!!!".getBytes());
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
3.3 用ServletContext对象读取资源文件
项目的目录结构:
代码:使用Servlet读取资源文件
package rain.servlet.study;
import java.io.IOException;
import java.io.InputStream;
import java.text.MessageFormat;
import java.util.Properties;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class RainServletContextDemo5
* 使用ServletContext读取资源文件
*/
@WebServlet("/RainServletContextDemo5")
public class RainServletContextDemo5 extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
// response.getWriter().append("Served at: ").append(request.getContextPath());
response.setHeader("content-type", "text/html;charset=UTF-8");
readSrcDirFile(response);//读取src目录下面的文件
response.getWriter().write("
");
readWebContentFile(response);//读取webcontent目录下面的文件
response.getWriter().write("
");
readPackageFile(response);//读取rain.servlet.study目录下的文件
response.getWriter().write("
");
readDataConfigFile(response);//读取data.config下的文件
}
/**
* 读取data.config下的文件 data1.properties
* @param response
* @throws IOException
*/
private void readDataConfigFile(HttpServletResponse response) throws IOException {
InputStream in = getServletContext().getResourceAsStream(
"/WEB-INF/classes/data/config/data1.properties");
Properties prop = new Properties();
prop.load(in);
String name = prop.getProperty("name");
String data = prop.getProperty("data");
String time = prop.getProperty("time");
response.getWriter().println("读取的是data.config包下面的data2.properties:");
response.getWriter().println(
MessageFormat.format("name={0},data={1},time={2}",
name,data,time));
}
/**
* readPackageFile(response);//读取rain.servlet.study目录下的文件 data2.properties
* @param response
* @throws IOException
*/
private void readPackageFile(HttpServletResponse response) throws IOException {
InputStream in = getServletContext().getResourceAsStream(
"/WEB-INF/classes/rain/servlet/study/data2.properties");
Properties prop = new Properties();
prop.load(in);
String name = prop.getProperty("name");
String data = prop.getProperty("data");
String time = prop.getProperty("time");
response.getWriter().println("读取的是src目录下面rain.servlet.study包下面的data2.properties:");
response.getWriter().println(
MessageFormat.format("name={0},data={1},time={2}",
name,data,time));
}
/**
* 读取webcontent目录下面的文件 data4.properties
* @param response
* @throws IOException
*/
private void readWebContentFile(HttpServletResponse response) throws IOException {
InputStream in = getServletContext().getResourceAsStream(
"/data4.properties");
Properties prop = new Properties();
prop.load(in);
String name = prop.getProperty("name");
String data = prop.getProperty("data");
String time = prop.getProperty("time");
response.getWriter().println("读取的是webcontent目录下面的data4.properties:");
response.getWriter().println(
MessageFormat.format("name={0},data={1},time={2}",
name,data,time));
}
/**
* 读取src目录下面的文件 data3.properties
* @param response
* @throws IOException
*/
private void readSrcDirFile(HttpServletResponse response) throws IOException {
InputStream in = getServletContext().getResourceAsStream(
"/WEB-INF/classes/data3.properties");
Properties prop = new Properties();
prop.load(in);
String name = prop.getProperty("name");
String data = prop.getProperty("data");
String time = prop.getProperty("time");
response.getWriter().println("读取的是src目录下面的data3.properties:");
response.getWriter().println(
MessageFormat.format("name={0},data={1},time={2}",
name,data,time));
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
运行结果如下:
四、在客户端缓存Servlet的输出
对于不是经常变化的数据,可以在服务器端设置一个缓存时间,以避免浏览器频繁的向服务器端发起请求,提高服务器的性能。
代码如下:
package rain.servlet.study;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class RainServletDemo6
*/
@WebServlet("/RainServletDemo6")
public class RainServletDemo6 extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
// response.getWriter().append("Served at: ").append(request.getContextPath());
String data = "asdffffdsgsgsfgsgsgs";
response.setDateHeader("expires", System.currentTimeMillis()+24*3600*1000);
response.getWriter().println(data);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}