首先在web.xml中配置初始化参数 <!-- 配置一些Web应用初始化参数--> <context-param> <param-name>url</param-name> <param-value>jdbc:mysql://localhost:3306/mybatis</param-value> </context-param> 从ServletContext中拿取 public class ServletDemo3 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //获取ServletContext容器 ServletContext context = this.getServletContext(); String url = context.getInitParameter("url"); //获取web.xml中的初始化参数 PrintWriter writer = resp.getWriter(); writer.println(url); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } } 最后在web.xml中注册Servlet <servlet> <servlet-name>getParameter</servlet-name> <servlet-class>com.hwh.servlet.ServletDemo3</servlet-class> </servlet> <servlet-mapping> <servlet-name>getParameter</servlet-name> <url-pattern>/getP</url-pattern> </servlet-mapping> 调用输出结果