ServletContext应用

ServletContext

Servlet中的几个变量

在Servlet中:

  • getInitParameter() 初始化参数
  • getServletConfig() Servlet配置
  • getServletContext() Servlet的上下文

ServletContext

web容器在启动时,它会为每个web程序都创建一个对应的ServletContext对象,它代表了当前的web应用;

应用:

共享数据

在这个Servlet中保存的数据,可以在另外一个Servlet中拿到

在这里插入图片描述

public class HelloServlet extends HttpServlet{
	
    @Override
    prodected void doGet(req,resp) throws{
		ServletContext context = this.getServletContext();
        
        String username = "yeyeye";
        context.setAttribute("username",username);
        //将一个数据保存在了ServletContext中,名字为username,值为username
    }
	

}
public class GetServlet extends HttpServlet{
	
    @Override
    prodected void doGet(req,resp) throws{
		ServletContext context = this.getServletContext();
		
        //读取
        String username = (String) context.getAttribute("username");
        
        resp.setContentType("text/html");
        resp.setCharacterEncoding("utf-8");
        resq.getWriter().print(username);
    }
	

}

获取初始化参数

配置一些web应用初始化参数

web.xml

<context-param>
	<param-name>url</param-name>
	<param-value>jdbc:mysql://localhost:3306/mybatis</param-value>
</context-param>

使用初始化参数

Servlet

public class GetServlet extends HttpServlet{
	
    @Override
    prodected void doGet(req,resp) throws{
		ServletContext context = this.getServletContext();
		
        //读取
       String url = context.getInitParameter("url");
        
        resp.setContentType("text/html");
        resp.setCharacterEncoding("utf-8");
        resq.getWriter().print(url);
    }
	
}

请求转发

public class GetServlet extends HttpServlet{
	
    @Override
    prodected void doGet(req,resp) throws{
		ServletContext context = this.getServletContext();
		
        //转发的路径,调用的forward实现请求转发
        context.getRequestDispatcher("/gp").forward(req,resp);
        //服务端请求转发,url不变
    }
	
}

上图为请求转发,下图为重定向

读取资源文件

即Properties

  • 在java目录下新建Properties
  • 在resource目录下新建Properties

发现:都被打包到了同一个路径下:classes,我们俗称这个路径为classpath

public class GetServlet extends HttpServlet{
	
    @Override
    prodected void doGet(req,resp) throws{
		InputStream is = this.getServletContext().getResourceAsStream("/WEB-INF/classes/db.properties");
		
		Properties prop = new Properties();
		prop.load(is);
		String user =  prop.getProperty("username");
        String pwd = prop.getProperty("password");
        resq.getWriter().print(user + " " + pwd);
    }
	
}

思路:需要一个文件流

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值