<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> <context-param> <param-name>name</param-name> <param-value>this is the context param value</param-value> </context-param> <servlet> <servlet-name>TestServlet</servlet-name> <servlet-class>TestServlet</servlet-class> <load-on-startup>1</load-on-startup> <!-- 0:不加载,1:首先加载-N-依次加载 --> </servlet> <servlet-mapping> <servlet-name>TestServlet</servlet-name> <url-pattern>/TestServlet</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class TestServlet extends HttpServlet { public TestServlet() { super(); } public void destroy () { super.destroy(); } public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException { } public void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException { doGet(request, response); } public void init () throws ServletException { //服务器启动的时候加载 String path = getServletContext().getRealPath(""); System.out.println("RealPath:"+path); String name = getServletContext().getInitParameter("name"); System.out.println("ContextParam:-->"+name); } }