servletConfig对象和servletContext对象的例子
时间: 2024-06-13 14:06:07 浏览: 82
servletContext的实例代码
以下是servletConfig对象和servletContext对象的例子:
1. servletConfig对象的例子:
```java
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class MyServlet extends HttpServlet {
private String message;
public void init() throws ServletException {
message = "Hello World!";
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
// 获取servletConfig对象
ServletConfig config = getServletConfig();
// 从servletConfig对象中获取初始化参数
String paramValue = config.getInitParameter("paramName");
// 输出初始化参数和message
PrintWriter out = response.getWriter();
out.println("<h1>" + message + "</h1>");
out.println("<p>Init Parameter Value: " + paramValue + "</p>");
}
public void destroy() {
}
}
```
2. servletContext对象的例子:
```java
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class MyServlet extends HttpServlet {
private String message;
public void init() throws ServletException {
message = "Hello World!";
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
// 获取servletContext对象
ServletContext context = getServletContext();
// 从servletContext对象中获取初始化参数
String paramValue = context.getInitParameter("paramName");
// 输出初始化参数和message
PrintWriter out = response.getWriter();
out.println("<h1>" + message + "</h1>");
out.println("<p>Init Parameter Value: " + paramValue + "</p>");
}
public void destroy() {
}
}
```
阅读全文