ServletContext
1.共享数据
ServletContext servletContext = this.getServletContext();
String username = "徐凤年";
servletContext.setAttribute("username",username);
ServletContext servletContext = this.getServletContext();
String username = (String) servletContext.getAttribute("username");
response.setContentType("text/html");
response.setCharacterEncoding("utf-8");
response.getWriter().print("名字" + username);
web.xml配置文件
2.获取初始化参数
ServletContext servletContext = this.getServletContext();
String url = servletContext.getInitParameter("url");
response.getWriter().print(url);
3.ServletContext应用
4.读取资源文件
Properties
●在java目录下新建properties
●在resources目录 下新建properties
发现:都被打包到了同一个路径下: classes, 我们俗称这个路径为classpath:
思路:需要一个文件流;
db.properties
username=root
password=123456
public class ServletDemo05 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
InputStream resourceAsStream = this.getServletContext().getResourceAsStream("/WEB-INF/classes/db.properties");
Properties properties = new Properties();
properties.load(resourceAsStream);
String username = properties.getProperty("username");
String password = properties.getProperty("password");
response.getWriter().print(username + password);
}
response.getWriter().print(username + password);
}