狂神说 javaweb 11集:ServletContext应用

11.ServletContext应用

6.5,ServletContext

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

2.获取初始化参数

context-param

 <!--配置 一些web应用初始化参数-->
 <context-param>
     <param-name>url</param-name>
     <param-value>jdbc:mysql://localhost:3306</param-value>
 </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");
         //RequestDispatcher dispatcher = context.getRequestDispatcher( "/gp" ); //转发的请求路径
         //dispatcher.forward(req,resp);//调用forward实现请求转发
         context.getRequestDispatcher( "/gp" ).forward( req,resp );
 
    }
 
     @Override
     protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
         doGet( req, resp );
    }
 }

在这里插入图片描述

 

5.读取资源文件

Properties

  • 在java目录下新建properties

  • 在resources目录下新建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;

posted @ 2022-05-22 22:40  坚持做  阅读(27)  评论(0)    收藏  举报