11.ServletContext应用
6.5,ServletContext
web 容器在启动的时候,他会 为每个web程序都创建一个对应的ServletContext对象,他代表了当前的web应用;
2.获取初始化参数
context-param
ServletDemo03
public class ServletDemo03 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext context = this.getServletContext();
String url = context.getInitParameter( "url" );
resp.getWriter().println(url);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet( req, resp );
}
}
xml
<servlet>
<servlet-name>gp</servlet-name>
<servlet-class>com.study.ServletDemo03</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>gp</servlet-name>
<url-pattern>/gp</url-pattern>
</servlet-mapping>
3.请求转发
public class Servletdemo04 extends HelloServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext context = this.getServletContext();
resp.setContentType( "text/html");
resp.setCharacterEncoding( "utf-8" );
System.out.println("进入了ServletDemo04");
![在这里插入图片描述]()
5.读取资源文件
Properties
发现:都被打包到了同一个路径下:classes,我们俗称这个路径为classpath: 思路:需要一个文件流
properties
username =root
password =123456
java
public class Servletdemo05 extends HelloServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext context = this.getServletContext();
InputStream is = context.getResourceAsStream( "/WEB-INF/classes/db.properties" );
Properties prop = new Properties();
prop.load( is );
String user = prop.getProperty( "username" );
String pwd = prop.getProperty( "password" );
resp.getWriter().println(user);
resp.getWriter().println(pwd);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet( req, resp );
}
}
访问测试即可ok;