通过ServletContext实现Servlet之间共享数据

ServletContext 是应用级域对象。

web.xml文件:




  
  	
    ServletDemo
    com.neu.ServletDemo
  
  
    ServletDemo2
    com.neu.ServletDemo2
  


  
  	
    ServletDemo
    /hello
  
  
    ServletDemo2
    /servlet/ServletDemo2
  

ServletDemo.java文件:


package com.neu;

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

import javax.servlet.ServletConfig;
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 ServletDemo extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		ServletContext sc = getServletContext();
		sc.setAttribute("p", "ppp");
		response.getWriter().write("OK");
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}
	
}

ServletDemo2.java文件:


package com.neu;

import java.io.IOException;
import java.io.PrintWriter;

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 ServletDemo2 extends HttpServlet {

	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		ServletContext sc = getServletContext();
		String value = (String)sc.getAttribute("p");
		response.getWriter().write(value);
	}


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

		
	}

}

运行及结果:

运行:http://localhost:8080/ServletDemo/hello

结果:OK

运行:http://localhost:8080/ServletDemo/servlet/ServletDemo2

结果:ppp

你可能感兴趣的:(javaweb,Servlet)