Java webservlet annotation examples
Certainly! Here are some examples of using the @WebServlet
annotation in Java:
- Basic Usage:
The @WebServlet
annotation is used to mark a class as a servlet. Here's an example:
@WebServlet("/MyServlet") public class MyServlet extends HttpServlet { // servlet implementation }
In this example, the @WebServlet
annotation is used to mark the MyServlet
class as a servlet that can be accessed at the URL "/MyServlet".
- Using Multiple URLs:
You can specify multiple URLs for a servlet using the value
attribute of the @WebServlet
annotation. Here's an example:
@WebServlet(value = {"/MyServlet", "/AnotherServlet"}) public class MyServlet extends HttpServlet { // servlet implementation }
In this example, the @WebServlet
annotation is used to mark the MyServlet
class as a servlet that can be accessed at two different URLs.
- Specifying Load On Startup:
You can use the loadOnStartup
attribute of the @WebServlet
annotation to specify the order in which the servlet should be loaded when the web application starts. Here's an example:
@WebServlet(value = "/MyServlet", loadOnStartup = 1) public class MyServlet extends HttpServlet { // servlet implementation }
In this example, the MyServlet
class is marked as a servlet that should be loaded on startup, and given a load order of 1.
- Specifying URL Patterns:
You can use the urlPatterns
attribute of the @WebServlet
annotation to specify one or more URL patterns that the servlet should handle. Here's an example:
@WebServlet(urlPatterns = {"/MyServlet/*", "/AnotherServlet/*"}) public class MyServlet extends HttpServlet { // servlet implementation }
In this example, the MyServlet
class is marked as a servlet that can handle requests for URLs that start with either "/MyServlet/" or "/AnotherServlet/".
- Using Name Attribute:
You can use the name
attribute of the @WebServlet
annotation to specify a unique name for the servlet. Here's an example:
@WebServlet(name = "MyServlet", urlPatterns = "/MyServlet") public class MyServlet extends HttpServlet { // servlet implementation }
In this example, the MyServlet
class is given a unique name of "MyServlet".
These are just a few examples of the many ways that you can use the @WebServlet
annotation in Java. The annotation is a powerful tool for creating and configuring servlets for your web application.