编写一个Servlet,使程序能读取该Servlet的配置信息(使用ServletConfig),从中获得参数名为username,password,role对应的参数值,并输出到页面上。 建议使用:<init-param>
时间: 2024-05-05 19:16:44 浏览: 49
在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>123456</param-value>
</init-param>
<init-param>
<param-name>role</param-name>
<param-value>administrator</param-value>
</init-param>
</servlet>
```
然后在Servlet中使用ServletConfig获取参数值并输出到页面上,示例如下:
```java
public class MyServlet extends HttpServlet {
private String username;
private String password;
private String role;
@Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
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;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet Configuration</title>");
out.println("</head>");
out.println("<body>");
out.println("<h2>Servlet Configuration Parameters:</h2>");
out.println("<p>Username: " + username + "</p>");
out.println("<p>Password: " + password + "</p>");
out.println("<p>Role: " + role + "</p>");
out.println("</body>");
out.println("</html>");
out.close();
}
}
```
阅读全文