Servlet 共享变量与变量的作用域
-共享变量
、setAttribute 该作用域:只对此请求,请求结束,作用域结束
、getAttribute
-变量的作用域
、ServletContext
-范围最大,应用程序级别的,整个应用程序都能访问
、HttpSession
-次之,会话级别的,在当前的浏览器中都能访问
、HttpServletRequest
-范围最小,请求级别,请求结束,变量的作用域也结束
package com.zhaofei.servletcontext;
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;
import javax.servlet.http.HttpSession;
/**
* Servlet implementation class MyServletContext
*/
public class MyServletContext extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public MyServletContext() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
// 请求结束,作用域就结束
request.setAttribute("request_name", "request_value");
// 会话,针对当前客户端和服务器 客户端与服务器断开这个会话就结束了
HttpSession session = request.getSession();
session.setAttribute("request_name", "request_value");
// ServletContext全局的,是当前web所有用户共享的
ServletContext cnx = this.getServletContext();
cnx.setAttribute("request_name", "request_value");
/*
* //下面是测试代码 用于回去变量值 String request_value = (String)
* request.getAttribute("request_name");
*
* HttpSession session = request.getSession(); String session_value =
* (String) session.getAttribute("request_name");
*
* ServletContext cxt = this.getServletContext(); String servletcontext
* = (String) cxt.getAttribute("request_name");
*/
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
this.doGet(request, response);
}
}