ServletContext

时间:2021-05-24 22:44:23   收藏:0   阅读:29

ServletContext

获取初始化参数

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

请求转发:

读取资源文件

Properties

发现:都被打包到同一个路径下:classes,俗称为classpath:

思路:需要一个文件流

@WebServlet("/propertiesServlet")
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("psw");
        resp.getWriter().write("username="+username);
        resp.getWriter().write("psw="+password);
    }
}

原文:https://www.cnblogs.com/saxonsong/p/14805147.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!