编写一个Servlet,使程序能读取该Servlet的配置信息(使用ServletConfig),从中获得参数名为username,password,role对应的参数值,并输出到页面上
时间: 2024-06-11 21:05:13 浏览: 163
以下是一个示例代码:
```java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/config")
public class ConfigServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private String username;
private String password;
private String role;
@Override
public void init() throws ServletException {
ServletConfig config = getServletConfig();
username = config.getInitParameter("username");
password = config.getInitParameter("password");
role = config.getInitParameter("role");
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><head><title>Config Servlet</title></head><body>");
out.println("<h1>Config Servlet</h1>");
out.println("<p>Username: " + username + "</p>");
out.println("<p>Password: " + password + "</p>");
out.println("<p>Role: " + role + "</p>");
out.println("</body></html>");
}
}
```
在这个示例代码中,我们使用了`ServletConfig`对象来读取该Servlet的配置信息,并在`init()`方法中将其保存为成员变量。在`doGet()`方法中,我们将这些参数值输出到页面上。请注意,在`web.xml`文件中,你需要为该Servlet提供这些参数的值,例如:
```xml
<servlet>
<servlet-name>config</servlet-name>
<servlet-class>ConfigServlet</servlet-class>
<init-param>
<param-name>username</param-name>
<param-value>admin</param-value>
</init-param>
<init-param>
<param-name>password</param-name>
<param-value>123456</param-value>
</init-param>
<init-param>
<param-name>role</param-name>
<param-value>administrator</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>config</servlet-name>
<url-pattern>/config</url-pattern>
</servlet-mapping>
```
在这个例子中,我们将Servlet的名称设置为`config`,并将其映射到`/config`路径。我们还为该Servlet提供了三个初始化参数:`username`,`password`和`role`。你可以根据自己的需要修改这些值。
阅读全文