需要tomcat7运行
package roseindia.webContext;
import java.io.PrintWriter;
import java.io.IOException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.annotation.WebServlet;
import javax.servlet.annotation.WebInitParam;
@WebServlet(name = "ContextParamServlet", urlPatterns = { "/ContextParamServlet" }, initParams = {
@WebInitParam(name = "URL", value = "jdbc:mysql://192.168.10.13"),
@WebInitParam(name = "USER", value = "root"),
@WebInitParam(name = "PASSWORD", value = "root") })
public class ContextParamServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws IOException, ServletException {
res.setContentType("text/plain");
PrintWriter out = res.getWriter();
String url = getInitParameter("URL");
ServletConfig config = getServletConfig();
ServletContext context = getServletContext();
String uid = config.getInitParameter("USER");
String psw = config.getInitParameter("PASSWORD");
String id = context.getInitParameter("userId");
out.println("Context and InitParameters values :");
out.println("URL: " + url);
out.println("User: " + uid);
out.println("PSW: " + psw);
out.println("User Id : " + id);
}
}
<context-param>
<param-name>userId</param-name>
<param-value>bipul</param-value>
</context-param>
原文:http://www.roseindia.net/java/javaee6/servlet3WebXml.shtml
源代码:http://pan.baidu.com/share/link?shareid=462125&uk=3878681452