在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 = 1L; public 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 = 1L; public 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