1)在web应用中,由服务器创建的唯一的一个对象是ServletContext
2)ServletContext对象在每一个Servlet中取得都是相同到
3)ServletContext对象在存取方法:
存ServletContext.setAttribute(String,Object):(返回值)void
取ServletContext.getAttribute(String):(返回值)Object
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 contDome1 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//取得客户端的请求参数
String nsername = request.getParameter("username");
//取得唯一的一个serverletContext对象
ServletContext context = this.getServletContext();
//将信息存入ServletContext对象
context.setAttribute("nsername", nsername);
}
}
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 contDome2 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//取得唯一的一个serverletContext对象
ServletContext context = this.getServletContext();
//根据name取得ServletContext对象中的值
String username = (String) context.getAttribute("nsername");
//在浏览器输出
response.setContentType("text/html;charset=UTF-8");
response.getWriter().write("用户名:" + username + "<br/>");
}
}
提交
http://localhost:8080/day04/contDome1?nsername=liwen
结果:
http://localhost:8080/day04/contDome2
原文地址:http://blog.51cto.com/357712148/2104531