ServletContext对象
1)在web应用中,由服务器创建的唯一的一个对象是ServletContext
2)ServletContext对象在每一个Servlet中取得都是相同到
3)ServletContext对象在存取方法:
存ServletContext.setAttribute(String,Object):(返回值)void
取ServletContext.getAttribute(String):(返回值)Object
dome1
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); }}
dome2
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