Annotations is one new feature introduces in the Servlet 3.0 Specification. Previously to declare servlets, listeners or filters we must do it in the web.xml
file. Now, with the new annotations feature we can just annotate servlet classes using the @WebServlet
annotation.
package org.kodejava.servlet;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
@WebServlet(
name = "HelloAnnotationServlet",
urlPatterns = {"/hello", "/helloanno"},
asyncSupported = false,
initParams = {
@WebInitParam(name = "name", value = "admin"),
@WebInitParam(name = "param1", value = "value1"),
@WebInitParam(name = "param2", value = "value2")
}
)
public class HelloAnnotationServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.write("<html><head><title>WebServlet Annotation</title></head>");
out.write("<body>");
out.write("<h1>Servlet Hello Annotation</h1>");
out.write("<hr/>");
out.write("Welcome " + getServletConfig().getInitParameter("name"));
out.write("</body></html>");
out.close();
}
}
After you’ve deploy the servlet you’ll be able to access it either using the /hello
or /helloanno
url.
The table below give brief information about the attributes accepted by the @WebServlet
annotation and their purposes.
ATTRIBUTE | DESCRIPTION |
---|---|
name |
The servlet name, this attribute is optional. |
description |
The servlet description and it is an optional attribute. |
displayName |
The servlet display name, this attribute is optional. |
urlPatterns |
An array of url patterns use for accessing the servlet, this attribute is required and should at least register one url pattern. |
asyncSupported |
Specifies whether the servlet supports asynchronous processing or not, the value can be true or false . |
initParams |
An array of @WebInitParam , that can be used to pass servlet configuration parameters. This attribute is optional. |
loadOnStartup |
An integer value that indicates servlet initialization order, this attribute is optional. |
smallIcon |
A small icon image for the servlet, this attribute is optional. |
largeIcon |
A large icon image for the servlet, this attribute is optional. |
Maven dependencies
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
</dependency>
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024