ServletContext实现转发和读取Properties配置文件

               

在Servlet开发中,一般很少使用Servlet输出数据,所以需要转发机制实现Servlet向JSp等等的转发,使用Servletontext就能完成这个功能,代码如下

package com.bird.servlet;import java.io.IOException;/** * @use 使用ServletContext实现请求的转移 * @author Bird */import javax.servlet.RequestDispatcher;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class ServletDemo5 extends HttpServlet private static final long serialVersionUID = 1Lpublic void doGet(HttpServletRequest request, HttpServletResponse response)   throws ServletException, IOException {    String data = "aaaaaaaa";  //数据带给JSP  this.getServletContext().setAttribute("data", data);    RequestDispatcher re = this.getServletContext().getRequestDispatcher("/1.jsp");//转发对象  re.forward(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response)   throws ServletException, IOException {   }}



下面的代码为使用ServletContext实现对Properties文件的读取和输出,先把配置文件的内容写出来

url=jdbc:mysql://localhost:3306/testusername=rootpassword=root

代码如下

package com.bird.servlet;import java.io.IOException;import java.io.InputStream;import java.util.Properties;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class ServletDemo6 extends HttpServlet /**  * @use 使用Servlet读取配置文件信息  * @author Bird  */ private static final long serialVersionUID = 1Lpublic void doGet(HttpServletRequest request, HttpServletResponse response)   throws ServletException, IOException {  //读取配置文件信息,其中配置文件为Properties  InputStream in = this.getServletContext().getResourceAsStream("/WEB-INF/classes/db.properties");    Properties pro = new Properties();  pro.load(in);    String url = pro.getProperty("url");  String username = pro.getProperty("username");  String password = pro.getProperty("password");    System.out.println(url);  System.out.println(username);  System.out.println(password);   }  public void doPost(HttpServletRequest request, HttpServletResponse response)   throws ServletException, IOException { }}

一定要注意路径的问题。。。。。           

再分享一下我老师大神的人工智能教程吧。零基础!通俗易懂!风趣幽默!还带黄段子!希望你也加入到我们人工智能的队伍中来!https://blog.csdn.net/jiangjunshow

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值