编写一个Servlet,使程序能读取该Servlet的配置信息(使用ServletConfig),从中获得参数名为username,password,role对应的参数值,并输出到页面上。 建议使用:<init-param>
时间: 2024-06-10 13:10:29 浏览: 47
servlet控制台输出用户名和密码
在web.xml中配置参数,然后在Servlet中使用ServletConfig获取参数值。
以下是示例代码:
web.xml配置:
```xml
<servlet>
<servlet-name>MyServlet</servlet-name>
<servlet-class>com.example.MyServlet</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>password123</param-value>
</init-param>
<init-param>
<param-name>role</param-name>
<param-value>admin</param-value>
</init-param>
</servlet>
```
MyServlet.java:
```java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MyServlet extends HttpServlet {
private String username;
private String password;
private String role;
@Override
public void init() throws ServletException {
super.init();
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>");
out.println("<head><title>Servlet Config Example</title></head>");
out.println("<body>");
out.println("<h1>Servlet Config Example</h1>");
out.println("<p>username: " + username + "</p>");
out.println("<p>password: " + password + "</p>");
out.println("<p>role: " + role + "</p>");
out.println("</body>");
out.println("</html>");
}
}
```
在浏览器中访问该Servlet,将会显示以下内容:
```
Servlet Config Example
username: admin
password: password123
role: admin
```
阅读全文