The following code example demonstrates how to Display init Parameters Using a Servlet.
Problem Statement
Display a servlet that fetches init parameters from web.xml displaying user information.
Here is an example of a servlet that fetches init parameters from the web.xml
file and displays user information.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class UserInfoServlet extends HttpServlet {
@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>");
out.println("<title>User Information</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>User Information</h1>");
out.println("<p>Name: " + getInitParameter("name") + "</p>");
out.println("<p>Age: " + getInitParameter("age") + "</p>");
out.println("<p>City: " + getInitParameter("city") + "</p>");
out.println("</body>");
out.println("</html>");
}
}
Likewise, Here is an example of the web.xml
file.
<web-app>
<servlet>
<servlet-name>UserInfoServlet</servlet-name>
<servlet-class>UserInfoServlet</servlet-class>
<init-param>
<param-name>name</param-name>
<param-value>John Doe</param-value>
</init-param>
<init-param>
<param-name>age</param-name>
<param-value>30</param-value>
</init-param>
<init-param>
<param-name>city</param-name>
<param-value>New York</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>UserInfoServlet</servlet-name>
<url-pattern>/user-info</url-pattern>
</servlet-mapping>
</web-app>
In this example, the UserInfoServlet
class handles GET requests. The servlet retrieves the init parameters name
, age
, and city
using the getInitParameter
method and displays the user information in an HTML page. The servlet is mapped to the /user-info
URL pattern in the web.xml
file.