对于每个Servlet的设置信息,web容器会为其生成一个ServletConfig作为代表对象,可以从该对象取得Servlet初始参数,以及代表整个web应用程序的ServletContext对象。
一、Servlet、ServletConfig、与GenericServlet
在Servlet的接口上,定义了与Servlet生命周期以及请求服务相关的init()、service()、destroy()三个方法。
web容器启动后,会读取Servlet设置信息,将Servlet类加载并实例化,并为每个Servlet设置信息产生一个ServletConfig对象,而后调用Servlet接口的init()方法,并将产生的ServletConfig对象作为参数传入init()。如图
这个过程只在创建Servlet实例后发生一次,之后每次请求到来,调用Servlet实例的service()方法进行服务。
GenericServlet主要的目的是,将初始的Servlet调用init()方法传入的ServletConfig封装起来。
二、使用ServletConfig
ServletConfig设置了getInitParameter()、getInitParameterNames()方法,可以取得设置Servlet时的初始参数。如
1 ...
2 @WebFilter(
3 urlPatterns = { "/*" },
4 initParams = {
5 @WebInitParam(name = "ENCODING", value = "UTF-8")
6 })
7
8 private String ENCODING;
9
10 public void init(FilterConfig fConfig) throws ServletException {
11 // TODO Auto-generated method stub
12 ENCODING=fConfig.getInitParameter("ENCODING");//读取初始参数
13 }
三、使用ServletContext
ServletContext接口定义了运行Servlet的应用程序环境的一些行为与观点,可以用其实现对象来取得所请求资源的URL、设置与存储属性、应用程序初始参数,甚至动态设置Servlet实例。
当整个web应用程序加载web容器后,容器会生成一个ServletContext对象作为应用程序的代表,并设置给ServletConfig,只要通过ServletConfig的getServletContext()方法就可以取得ServletContext对象。
1、getRequestDispatcher()
用来取得RequestDispatcher实例,使用时路径的指定必须是"/"作为开头,这个斜杠代表应用程序的环境根目录。
context.getRequestDispatcher("/pages/some.jsp").forward(request,response);
2、getResourcePaths()
如果想知道web应用程序的某个目录有哪些文件,可以使用getResourcePaths()方法。如:
1 for ( String avater : getServletContext().getResourcePaths("/")){
2 //显示avatar文字
3 }
例1:取得图片的路径,并通过img标签显示图片。
1 package ServletAPI;
2
3 import java.io.IOException;
4 import java.io.PrintWriter;
5
6 import javax.servlet.ServletException;
7 import javax.servlet.annotation.WebInitParam;
8 import javax.servlet.annotation.WebServlet;
9 import javax.servlet.http.HttpServlet;
10 import javax.servlet.http.HttpServletRequest;
11 import javax.servlet.http.HttpServletResponse;
12
13 /**
14 * Servlet implementation class Avatar
15 */
16 @WebServlet(
17 urlPatterns = { "/avatar.view" },
18 initParams = {
19 @WebInitParam(name = "AVATAR_DIR", value = "/image")//根目录WebContent内部
20 })
21 public class Avatar extends HttpServlet {
22 private static final long serialVersionUID = 1L;
23 private String AVATAR_DIR;
24 /**
25 * @see HttpServlet#HttpServlet()
26 */
27 public Avatar() {
28 super();
29 // TODO Auto-generated constructor stub
30 }
31 public void init() throws ServletException{
32 AVATAR_DIR=getInitParameter("AVATAR_DIR");
33 //AVATAR_DIR=(String) getServletContext().getAttribute("avatars");
34 }
35
36
37 /**
38 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
39 */
40 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
41 // TODO Auto-generated method stub
42 response.setContentType("text/html;charset=UTF-8");
43 PrintWriter out=response.getWriter();
44 out.println("<!DOCTYPE html>");
45 out.println("<html>");
46 out.println("<head>");
47 out.println("<meta content='text/html; charset=UTF-8' http-equiv='content-type'>");
48 out.println("<title>头像显示</title>");
49 out.println("</head>");
50 out.println("<body>");
51 for(String avatar:getServletContext().getResourcePaths(AVATAR_DIR)){//取得头像路径
52 avatar=avatar.replaceFirst("/", "");
53 out.println("<img src='"+avatar+"'>");
54 }
55 out.println("</body>");
56 out.println("</html>");
57 out.close();
58 }
59
60 /**
61 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
62 */
63 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
64 // TODO Auto-generated method stub
65 }
66
67 }
3、getResourceAsStream()
如果想要在web应用程序中,读取某个文件的内容,可以使用该方法,使用时路径的指定必须是"/"作为开头,
例2:读取pdf文件
1 package cc.openhome;
2
3 import java.io.File;
4 import java.io.FileInputStream;
5 import java.io.IOException;
6 import java.io.InputStream;
7 import java.io.OutputStream;
8
9 import javax.servlet.ServletException;
10 import javax.servlet.ServletOutputStream;
11 import javax.servlet.annotation.WebServlet;
12 import javax.servlet.http.HttpServlet;
13 import javax.servlet.http.HttpServletRequest;
14 import javax.servlet.http.HttpServletResponse;
15
16 /**
17 * Servlet implementation class Download
18 */
19 @WebServlet("/download.do")
20 public class Download extends HttpServlet {
21 private static final long serialVersionUID = 1L;
22
23 /**
24 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
25 */
26 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
27 // TODO Auto-generated method stub
28 processRequest(request, response);
29 }
30
31 /**
32 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
33 */
34 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
35 // TODO Auto-generated method stub
36 processRequest(request, response);
37
38 }
39
40 private void processRequest(HttpServletRequest request,
41 HttpServletResponse response) throws IOException {
42 // TODO Auto-generated method stub
43 //String passwd=request.getParameter("passwd");
44 //if("123456".equals(passwd)){
45 response.setContentType("application/pdf");//设置内容类型
46
47 InputStream in=getServletContext().getResourceAsStream("/WEB-INF/LaTeX2e.pdf");//取得输入串流
48 //File pdf = new File("E:/java web/workspace/FirstServlet/WebContent/WEB-INF/LaTeX2e.pdf");
49 //response.setContentLength((int) pdf.length());
50 // FileInputStream in = new FileInputStream(pdf);
51 OutputStream out=response.getOutputStream();//取得输出串流
52 writeBytes(in,out);//读取pdf并输出至浏览器
53 //}
54 }
55
56 private void writeBytes(InputStream in, OutputStream out) throws IOException {
57 // TODO Auto-generated method stub
58 // TODO Auto-generated method stub
59 byte[] buffer=new byte[1024*1024];
60 int length=-1;
61 while((length=in.read(buffer))!=-1){
62 out.write(buffer,0,length);
63 }
64 in.close();
65 out.close();
66 }
67 }
当神已无能为力,那便是魔渡众生