JavaWeb-ServletContext对象

  • 定义:ServletContext代表是一个web应用的环境(上下文)对象,ServletContext对象 内部封装是该web应用的信息,ServletContext对象一个web应用只有一个。
  • 生命周期:
    创建:该web应用被加载(服务器启动或发布web应用(前提,服务器启动状态))
    销毁:web应用被卸载(服务器关闭,移除该web应用)】
  • 获取ServletContext对象
    ServletContext servletContext = config.getServletContext();
    ServletContext servletContext = this.getServletContext();
  • 作用
    (1)获取web应用中任何资源的绝对路径
    方法:String path = context.getRealPath(相对地址);
    相对得绝对

java代码


public class ImageServlet extends HttpServlet {
	/**
	 * 从服务器上将图片解析到客户端
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		// 明确数据源  -- 根据服务器相对路径获取绝对路径
		String filePath = getServletContext().getRealPath("baby.png");
		FileInputStream fis = new FileInputStream(filePath);
		// 明确目的地
		ServletOutputStream sos = response.getOutputStream();
		// 开始复制
		int len = 0;
		byte[] bytes = new byte[1024];
		while((len = fis.read(bytes)) != -1) {
			sos.write(bytes ,0 , len);
		}
		fis.close();
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
}
  • (2)ServletContext是一个域对象(存储数据的区域就叫域对象)
    ServletContext域对象的作用范围:整个web应用(所有的web资源都可以随意向servletcontext域中存取数据,数据可以共享)
    域对象的通用方法
    |方法|说明|
    |---|---|
    |setAttribute(String name, Object obj);|键值对存取|
    |getAttribute(String name);|通过键得对|
    |removeAttribute(String name);|通过键删除键值对|

java代码

public class LoginServlet extends HttpServlet {
	/**
	 * 实现连接数据库验证用户名密码
	 * 实现在ServletContext对象中存值作为计数器使用
	 * 在init()方法中定义计数器
	 * 在doGet()方法中实现登录功能和计数器增加
	 */
	private UserService userService= new UserService();

 	public void init() throws ServletException {

 		ServletContext context = this.getServletContext();
 		int sum = 0;
 		context.setAttribute("sum", sum);
 		
 	}
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		// 获取用户名和密码
		String username = request.getParameter("username");
		String pwd = request.getParameter("pwd");
		// TODO Service层
		int count = userService.login(username, pwd);
		System.out.println(count);
		if (count == 0) {
			response.getWriter().write("Error");
		} else {
			response.getWriter().write("Bingo");
			// 增加计数器值
			ServletContext context = this.getServletContext();
			int sum = (int) context.getAttribute("sum");
			response.getWriter().write("你是第" + ++sum + "个访客");
		}
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
}
posted @ 2020-05-11 19:30  于大宝执剑江湖  阅读(151)  评论(0)    收藏  举报