编写一个Servlet,使程序能读取该Servlet的配置信息(使用ServletConfig),从中获得参数名为username,password,role对应的参数值,并输出到页面上。 建议使用:<init-param>
时间: 2024-06-10 13:10:16 浏览: 97
在web.xml文件中设置Servlet的初始化参数。
以下是示例代码:
```
@WebServlet("/configServlet")
public class ConfigServlet 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");
}
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><title>Servlet Config Parameter</title></head>");
out.println("<body>");
out.println("<h1>Servlet Config Parameter</h1>");
out.println("<p>Username: " + username + "</p>");
out.println("<p>Password: " + password + "</p>");
out.println("<p>Role: " + role + "</p>");
out.println("</body></html>");
out.close();
}
}
```
在web.xml文件中设置初始化参数:
```
<servlet>
<servlet-name>configServlet</servlet-name>
<servlet-class>com.example.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>admin</param-value>
</init-param>
</servlet>
```
访问该Servlet,将输出以下内容:
```
Servlet Config Parameter
Username: admin
Password: 123456
Role: admin
```
阅读全文