一、基本概念
Servlet上下文又叫做:ServletContext。
当WEB服务器启动时,会为每一个WEB应用程序(webapps下的每个目录就是一个应用程序)创建一块共享的存储区域。
ServletContext也叫做“公共区域”,也就是同一个WEB应用程序中,所有的Servlet和JSP都可以共享同一个区域。
ServletContext在WEB服务器启动时创建,服务器关闭时销毁。
二、对象方法
凡是域对象都有如下3个方法:
setAttribute(name,value);name是String类型,value是Object类型; | 往域对象里面添加数据,添加时以key-value形式添加 |
getAttribute(name) | 根据指定的key读取域对象里面的数据 |
removeAttribute(name); | 根据指定的key从域对象里面删除数据 |
三、代码块
1通过setAttibute来设置contextl里面的内容来实现共享
ublic class HelloServelet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// super.doGet(req, resp);
ServletContext servletContext = this.getServletContext();
String num = "haha";
servletContext.setAttribute("zz", num);
System.out.println("jsjdiasdj");
}
}
public class getServelet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// super.doGet(req, resp);
ServletContext servletContext = this.getServletContext();
String zz2 = (String)servletContext.getAttribute("zz");
resp.setContentType("text/html");
resp.setCharacterEncoding("utf-8");
resp.getWriter().print(zz2);
}
}
2通过param模块可以添加url路径然后调用来访问
<context-param>
<param-name>url</param-name>
<param-value>JDBC:mysql://localhost:3306//mybitas</param-value>
</context-param>
public class ServeletDomo3 extends HelloServelet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext servletContext = this.getServletContext();
String url = servletContext.getInitParameter("url");
System.out.println(url);
resp.getWriter().print(url);
}
}
3转发
public class serveleDemo4 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext servletContext = this.getServletContext();
//转发的请求路径
RequestDispatcher lala11 = servletContext.getRequestDispatcher("/lala11");
//forward函数的作用注意一下
lala11.forward(req, resp);
}
}
4读取资源(一般都是相对路径 服务器很难去拿到绝对的路径)
public class ServeletDemo5 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//这里的路径是映射后的路径 直接就是/WEB代表的是当前的目录下面
InputStream resourceAsStream = this.getServletContext().getResourceAsStream("/WEB-INF/classes/db.properties");
Properties properties = new Properties();
//读取的时候只有这一种方式 根据流来读
properties.load(resourceAsStream);
String username = properties.getProperty("username");
String number = properties.getProperty("number");
resp.getWriter().print(username);
resp.getWriter().print(number);
}
}