Java servlet annotations reference
htt/:sp/www.theitroad.com
Here is a reference for the most commonly used Java Servlet annotations:
@WebServlet
: Used to define a servlet and map it to a URL pattern.
@WebServlet(name = "MyServlet", urlPatterns = { "/hello" }) public class MyServlet extends HttpServlet { // ... }
@WebFilter
: Used to define a filter and map it to a URL pattern.
@WebFilter(filterName = "MyFilter", urlPatterns = { "/*" }) public class MyFilter implements Filter { // ... }
@WebListener
: Used to define a listener for various events in the servlet container.
@WebListener public class MyServletContextListener implements ServletContextListener { // ... }
@WebInitParam
: Used to define initialization parameters for a servlet or filter.
@WebServlet(name = "MyServlet", urlPatterns = { "/hello" }, initParams = { @WebInitParam(name = "foo", value = "bar") }) public class MyServlet extends HttpServlet { // ... }
@MultipartConfig
: Used to configure a servlet to handle HTTP multipart requests.
@MultipartConfig(location = "/path/to/upload/directory", maxFileSize = 10 * 1024 * 1024, maxRequestSize = 50 * 1024 * 1024) public class FileUploadServlet extends HttpServlet { // ... }
@HttpMethodConstraint
: Used to define constraints on the HTTP methods that a servlet or filter can handle.
@HttpMethodConstraint(value = "GET", rolesAllowed = { "admin" }) @WebServlet(name = "MyServlet", urlPatterns = { "/hello" }) public class MyServlet extends HttpServlet { // ... }
@ServletSecurity
: Used to define security constraints on a servlet.
@ServletSecurity(@HttpConstraint(rolesAllowed = {"admin"})) @WebServlet(name = "MyServlet", urlPatterns = { "/hello" }) public class MyServlet extends HttpServlet { // ... }
These annotations can help you configure your servlets, filters, and listeners in a more concise and readable way than with the traditional web.xml
deployment descriptor. For more information, you can refer to the Java Servlet API documentation.