您当前的位置: 首页 >  servlet

white camel

暂无认证

  • 2浏览

    0关注

    442博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

Servlet——ServletContext对象

white camel 发布时间:2020-01-27 17:56:17 ,浏览量:2

目录
  • ServletContext概述
  • 获取ServletContext对象
  • ServletContext常用功能
    • 多个servlet之间共享数据
    • 获取当前WEB项目中的指定资源(文件)
    • 获取应用初始化参数
ServletContext概述

跳转到目录 ServletContext对象,tomcat为每一个web项目单独创建的一个(ServletContext)上下文(知上知下贯穿全文)对象。服务器启动的时候,为每个WEB应用创建一个单独的ServletContext对象,我们可以使用这个对象存取数据,用这个对象存取的数据,可以在整个WEB应用中获取.

服务器会为每个应用创建一个ServletContext对象:

  • ServletContext对象的创建是在服务器启动时完成的;
  • ServletContext对象的销毁是在服务器关闭时完成的。 在这里插入图片描述
获取ServletContext对象

跳转到目录

  • 直接调用ServletConfig中的getServletContext();
  • request对象.getServletContext();
ServletContext常用功能

跳转到目录 一、多个servlet之间共享数据

  • setAttribute(String name,Object object) 向ServletContext中存数据
  • getAttribute(String name) 从ServletContext中取数据
  • removeAttribute(name) 从ServletContext中移除数据
@WebServlet("/scope")
public class ScopeServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        // application:(也就是 ServletContext)
        Integer numInApp = (Integer) req.getServletContext().getAttribute("NUM_IN_APP");
        if (numInApp == null){
            req.getServletContext().setAttribute("NUM_IN_APP", 1);
        } else {
            req.getServletContext().setAttribute("NUM_IN_APP", numInApp + 1);
        }

        // 请求转发
        req.getRequestDispatcher("/result").forward(req, resp);
    }
}
@WebServlet("/result")
public class ResultServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter out = resp.getWriter();
        out.println("application=" +req.getServletContext().getAttribute("NUM_IN_APP"));
    }
}

二、获取当前WEB项目中的指定资源(文件) 跳转到目录 既然 ServletContext 是 贯穿全文 的对象 ,所以项目中的资源 它都能访问到 , 主要用它获取web项目中文件.

文件保存的位置 : 1.src下 : 发布到 /WEB-INF/classes/文件名 2.web目录下 : 发布到/文件名 3.WEB-INF目录下 : 发布到 /WEB-INF/文件名

  • getRealPath(String str) 获取资源绝对路径
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("ContextFileServlet.doPost");
        // 获取ServletContext对象
        ServletContext sc = request.getServletContext();
        // 读取web目录下的文件
        String realPath = sc.getRealPath("/web下的文件.txt");
        //String realPath = sc.getRealPath("/WEB-INF/info下的文件.txt");
        //String realPath = sc.getRealPath("/WEB-INF/classes/src下的文件.txt");
        System.out.println(realPath); // 返回web下的文件.txt的绝对路径
        // 读取该文件的内容
        BufferedReader br = new BufferedReader(new FileReader(realPath));
        String lineCotext = br.readLine();
        System.out.println(lineCotext);
    }
  • getResourceAsStream(String str) 获取资源输入流对象 参数 : str 与 getRealPath()的参数一致 返回值 : 输入流对象, 用来直接读取文件.
@WebServlet("/ContextFileServlet3")
public class ContextFileServlet3 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 读取web目录下的a.jpg

        // 使用路径的方式(比较麻烦)
        // String realPath = super.getServletContext().getRealPath("/a.jpg");
        // FileInputStream fis = new FileInputStream(realPath);

        // 使用 流 来读取
        InputStream in = getServletContext().getResourceAsStream("/a.jpg");
        // 回写字节数据
        ServletOutputStream out = response.getOutputStream();
        // 读写数据
        byte[] b = new byte[1024];
        int len = 0;
        while ((len = in.read(b)) != -1){
            out.write(b, 0, len);
        }

        // 释放资源
        out.close();
        in.close();
    }

三、获取应用初始化参数 跳转到目录 还可以使用ServletContext来获取在web.xml文件中配置的应用初始化参数!注意,应用初始化参数与Servlet初始化参数不同:

web.xml


  ...
  
	paramName1
	paramValue1  	
  
  
	paramName2
	paramValue2  	
  

ServletContext context = this.getServletContext();
		String value1 = context.getInitParameter("paramName1");
		String value2 = context.getInitParameter("paramName2");
		System.out.println(value1 + ", " + value2);
		
		Enumeration names = context.getInitParameterNames();
		while(names.hasMoreElements()) {
			System.out.println(names.nextElement());
		}
关注
打赏
1661428283
查看更多评论
立即登录/注册

微信扫码登录

0.0363s