ServletContext方法实例讲解

来源:互联网 发布:阿里巴巴标题优化技巧 编辑:程序博客网 时间:2024/06/05 14:45

1、多个servlet可以通过这个对象实现数据共享

在一个servlet中写

<span style="white-space:pre"></span>String date = "aaa";this.getServletContext().setAttribute("date", date);

另外一个中

<span style="white-space:pre"></span>protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {String value = (String) this.getServletContext().getAttribute("date");System.out.println(value);}
先后运行控制台就能输出aaa


2、实现Servlet的转发

在servlet中

<span style="white-space:pre"></span>protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {String data = "money";//把数据带给jsp一般不通过context域,而是request域this.getServletContext().setAttribute("data", data);RequestDispatcher rd = this.getServletContext().getRequestDispatcher("/test.jsp");rd.forward(request, response);}

在jsp中

<body><font color="red"><%String data = (String)application.getAttribute("data");out.write(data);%></font></body>

在浏览器里访问servlet就能看见输出


3、读取资源文件

在db.properties下写上

url=jdbc:mysql://localhost:3306/test
username=root
password=root


如和servlet放在同一个包下

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {InputStream in = this.getServletContext().getResourceAsStream("/WEB-INF/classes/db.properties");Properties props = new Properties();//map保存props.load(in);String url = props.getProperty("url");String username = props.getProperty("username");String password = props.getProperty("password");System.out.println(url);System.out.println(username);System.out.println(password);}

运行即可输出


0 0
原创粉丝点击