n 创建 Web 应用程序 servletest

n InitParamServlet.java 完整代码如下：

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 java.io.PrintWriter;

import java.io.IOException;

public class InitParamServlet extends HttpServlet

{

public void doGet(HttpServletRequest req, HttpServletResponse res)

throws IOException, ServletException

{

res.setContentType("text/plain;charset=GBK");

PrintWriter out = res.getWriter();

String url = getInitParameter("URL");

ServletConfig config = getServletConfig();

ServletContext context = getServletContext();

String uid = config.getInitParameter("UID");

String pwd = config.getInitParameter("PWD");

String port = context.getInitParameter("some-port");

out.println("初始化参数和上下文初始化参数如下：");

out.println("URL: " + url);

out.println("UID: " + uid);

out.println("PWD: " + pwd);

out.println("some-port: " + port);

}

}

1. 创建 public class InitParamServlet extends HttpServlet

2. 重写 public void doGet(HttpServletRequest req, HttpServletResponse res)

· 设置响应(response)内容类型，即 res.setContentType("text/plain;charset=GBK")

· 获得 response 的输出流，即 PrintWriter out = res.getWriter()

· 获得初始化参数 URL，即 String url = getInitParameter("URL")

· 获得 ServletConfig 的引用，即 ServletConfig config = getServletConfig()

· 获得 ServletContext 的引用，即 ServletContext context = getServletContext()

· 通过 ServletConfig 引用获得初始化参数：String uid = config.getInitParameter("UID"); String pwd = config.getInitParameter("PWD")

· 通过 ServletContext 引用获得上下文初始化参数：String port = context.getInitParameter("some-port")

3. 输出各个参数，如 out.println("URL: " + url)

n 修改 web.xml，配置 Servlet、初始化参数和上下文初始化参数，web.xml 文件内容如下：

<?xml version="1.0" encoding="UTF-8"?>

<web-app id="WebApp_ID" 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">

<display-name>servletest</display-name>

<context-param>

<param-name>some-port</param-name>

<param-value>5000</param-value>

</context-param>

<servlet>

<servlet-name>init</servlet-name>

<servlet-class>InitParamServlet</servlet-class>

<init-param>

<param-name>URL</param-name>

<param-value>jdbc:mysql://localhost/pizza</param-value>

</init-param>

<init-param>

<param-name>UID</param-name>

<param-value>matt</param-value>

</init-param>

<init-param>

<param-name>PWD</param-name>

<param-value>secret</param-value>

</init-param>

</servlet>

<servlet-mapping>

<servlet-name>init</servlet-name>

<url-pattern>/init</url-pattern>

</servlet-mapping>

</web-app>

#### 4.3 部署运行

n 部署文件

· 编译 InitParamServlet.java，把 class 文件放到 WEB-INF\classes\ 目录下。

n 启动 Tomcat

n 在 IE 浏览器的地址栏中输入 http ://localhost:8080/jsp_test/init