Show List

Servlet Annotations

Servlet Annotations are metadata annotations that can be used to configure a servlet and map it to a URL pattern without the need for a deployment descriptor file (web.xml). Servlet Annotations are part of the Java EE specification, and they provide a more concise and expressive way to configure servlets.

Here is an example of how to use servlet annotations to define a servlet:

java
Copy code
@WebServlet( name = "helloServlet", urlPatterns = {"/hello"} ) public class HelloServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<html><body><h1>Hello, World!</h1></body></html>"); } }

In this example, we use the @WebServlet annotation to define a servlet called HelloServlet. The urlPatterns attribute maps the servlet to the /hello URL pattern.

Here's another example that shows how to use other common annotations to configure a servlet:

java
Copy code
@WebServlet( name = "userServlet", urlPatterns = {"/user/*"}, initParams = { @WebInitParam(name = "defaultUser", value = "guest"), @WebInitParam(name = "defaultPassword", value = "guest123") }, description = "This servlet handles user requests" ) public class UserServlet extends HttpServlet { private String defaultUser; private String defaultPassword; public void init() throws ServletException { ServletConfig config = getServletConfig(); defaultUser = config.getInitParameter("defaultUser"); defaultPassword = config.getInitParameter("defaultPassword"); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<html><body>"); out.println("<h1>User Information</h1>"); out.println("<p>Default User: " + defaultUser + "</p>"); out.println("<p>Default Password: " + defaultPassword + "</p>"); out.println("</body></html>"); } }

In this example, we use the @WebServlet annotation to define a servlet called UserServlet. We also use the @WebInitParam annotation to define two initialization parameters for the servlet: defaultUser and defaultPassword. Finally, we use the description attribute to provide a brief description of the servlet.

In the init() method of the servlet, we use the getInitParameter() method to retrieve the values of the initialization parameters. We then use these values to generate the output of the servlet.

In summary, Servlet Annotations provide a simple and efficient way to configure servlets, and they can make your code more concise and expressive.


    Leave a Comment


  • captcha text