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);
}
}
思路:需要一个文件流