ServletContext知识点总结

本文介绍Servlet在Web应用中的三种实用技巧:获取初始化参数、使用RequestDispatcher进行请求转发及读取资源文件的方法。

一、获取初始化参数

首先在web.xml文件中配置context-param参数

<context-param>
    <param-name>url</param-name>
    <param-value>jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC</param-value>
</context-param>

然后在ServletContext中调用它

public class ServletContext  extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        javax.servlet.ServletContext context = this.getServletContext();
        String url = context.getInitParameter("url");
        resp.getWriter().print(url);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

在web.xml中创建映射即可

   <servlet>
        <servlet-name>url</servlet-name>
        <servlet-class>com.llf.ServletContext</servlet-class>
    </servlet>
  <servlet-mapping>
      <servlet-name>url</servlet-name>
      <url-pattern>/context</url-pattern>
  </servlet-mapping>

二、请求转发(RequestDispatcher)

public class ServletContext  extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        javax.servlet.ServletContext context = this.getServletContext();
        context.getRequestDispatcher("/Hello").forward(req,resp);
       
       

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

相当于通过中间者来实现信息访问的功能   区别它和重定位的区别 一个是通过中间者实现信息访问,另一个是中间者给其指明地址,不参与信息访问的过程  此处的“/hello”是映射的路径

三、读取资源文件 (Properties)一般放在resouurse包下面

文件写完以后 重启Tomcat 使resourse文件加载在web文件下面

写实现类 

public class propertiesServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        InputStream is = this.getServletContext().getResourceAsStream("/WEB-INF/classes/db.Properties");
        Properties properties = new Properties();
        properties.load(is);
        String username = properties.getProperty("username");
        String password = properties.getProperty("password");
        resp.getWriter().print(username+" "+password);

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

 

 结言

这些知识并不是我们学习中必需的,在后续的学习中都会被更好用的类替换  之所以写出来 是为了更好的理解底层的实现

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值