📅  最后修改于: 2020-11-12 05:47:44             🧑  作者: Mango
到目前为止,您已经了解了Servlet如何使用部署描述符(web.xml文件)将应用程序部署到Web服务器中。 Servlet API 3.0引入了一个名为javax.servlet.annotation的新程序包。它提供了可用于对Servlet类进行注释的注释类型。如果使用批注,则不需要部署描述符(web.xml)。但是您应该使用tomcat7或任何更高版本的tomcat。
注释可以替换Web部署描述符文件(web.xml)中的等效XML配置,例如Servlet声明和Servlet映射。 Servlet容器将在部署时处理带注释的类。
Servlet 3.0中引入的注释类型为-
Sr.No. | Annotation & Description |
---|---|
1 |
@WebServlet To declare a servlet. |
2 |
@WebInitParam To specify an initialization parameter. |
3 |
@WebFilter To declare a servlet filter. |
4 |
@WebListener To declare a WebListener |
5 |
@HandlesTypes To declare the class types that a ServletContainerInitializer can handle. |
6 |
@HttpConstraint This annotation is used within the ServletSecurity annotation to represent the security constraints to be applied to all HTTP protocol methods for which a corresponding HttpMethodConstraint element does NOT occur within the ServletSecurity annotation. |
7 |
@HttpMethodConstraint This annotation is used within the ServletSecurity annotation to represent security constraints on specific HTTP protocol messages. |
8 |
@MultipartConfig Annotation that may be specified on a Servlet class, indicating that instances of the Servlet expect requests that conform to the multipart/form-data MIME type. |
9 |
@ServletSecurity This annotation is used on a Servlet implementation class to specify security constraints to be enforced by a Servlet container on HTTP protocol messages. |
在这里,我们已经详细讨论了一些注释。
@WebServlet用于通过容器声明Servlet的配置。下表包含用于WebServlet批注的属性的列表。
Sr.No. | Attribute & Description |
---|---|
1 |
String name Name of the Servlet |
2 |
String[] value Array of URL patterns |
3 |
String[] urlPatterns Array of URL patterns to which this Filter applies |
4 |
Int loadOnStartup The integer value gives you the startup ordering hint |
5 |
WebInitParam[] initParams Array of initialization parameters for this Servlet |
6 |
Boolean asyncSupported Asynchronous operation supported by this Servlet |
7 |
String smallIcon Small icon for this Servlet, if present |
8 |
String largeIcon Large icon for this Servlet, if present |
9 |
String description Description of this Servlet, if present |
10 |
String displayName Display name of this Servlet, if present |
注释的value或urlPattern属性中必须声明至少一个URL模式,但不能两者都声明。
当URL模式是唯一设置的属性时,建议使用value属性,否则应使用urlPattern属性。
以下示例描述了如何使用@WebServlet批注。这是一个简单的servlet,显示文本Hello Servlet 。
import java.io.IOException;
import java.io.PrintWriter;
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;
@WebServlet(value = "/Simple")
public class Simple extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.print("");
out.print("Hello Servlet
");
out.print("");
}
}
以通常的方式编译Simple.java并将类文件放入
现在,尝试通过运行http:// localhost:8080 / Simple来调用任何servlet。您将在网页上看到以下输出。
Hello servlet
@WebInitParam批注用于为Servlet或Filter指定初始化参数。在WebFilter或WebSevlet批注中使用它。下表包含用于WebInitParam批注的属性列表。
Sr.No. | Attribute & Description |
---|---|
1 |
String name Name of the initialization parameter |
2 |
String value Value of the initialization parameter |
3 |
String description Description of the initialization parameter |
以下示例描述了如何将@WeInitParam注释与@WebServlet注释一起使用。这是一个简单的servlet,显示文本Hello Servlet和字符串值Hello World!从init参数中获取。
import java.io.IOException;
import java.io.PrintWriter;
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;
@WebServlet(value = "/Simple", initParams = {
@WebInitParam(name = "foo", value = "Hello "),
@WebInitParam(name = "bar", value = " World!")
})
public class Simple extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.print("");
out.print("Hello Servlet
");
out.println(getInitParameter("foo"));
out.println(getInitParameter("bar"));
out.print("");
}
}
以通常的方式编译Simple.java并将类文件放入
现在,尝试通过运行http:// localhost:8080 / Simple来调用任何servlet。您将在网页上看到以下输出。
Hello Servlet
Hello World!
这是用于声明servlet过滤器的注释。容器在部署时对其进行处理,并将相应的过滤器应用于指定的URL模式,Servlet和调度程序类型。
@WebFilter批注定义了Web应用程序中的过滤器。该注释在类中指定,并且包含有关要声明的过滤器的元数据。带注释的过滤器必须指定至少一个URL模式。下表列出了用于WebFilter批注的属性。
Sr.No. | Attribute & Description |
---|---|
1 |
String filterName Name of the filter |
2 |
String[] urlPatterns Provides array of values or urlPatterns to which the filter applies |
3 |
DispatcherType[] dispatcherTypes Specifies the types of dispatcher (Request/Response) to which the filter applies |
4 |
String[] servletNames Provides an array of servlet names |
5 |
String displayName Name of the filter |
6 |
String description Description of the filter |
7 |
WebInitParam[] initParams Array of initialization parameters for this filter |
8 |
Boolean asyncSupported Asynchronous operation supported by this filter |
9 |
String smallIcon Small icon for this filter, if present |
10 |
String largeIcon Large icon for this filter, if present |
下面的示例描述如何使用@WebFilter批注。这是一个简单的LogFilter,可在控制台上显示Init-param test-param的值和当前时间时间戳。这意味着,过滤器的工作方式类似于请求和响应之间的接口层。在这里,我们将“ / *”用于urlPattern。这意味着,此过滤器适用于所有servlet。
import java.io.IOException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.*;
import java.util.*;
// Implements Filter class
@WebFilter(urlPatterns = {"/*"}, initParams = {
@WebInitParam(name = "test-param", value = "Initialization Paramter")})
public class LogFilter implements Filter {
public void init(FilterConfig config) throws ServletException {
// Get init parameter
String testParam = config.getInitParameter("test-param");
//Print the init parameter
System.out.println("Test Param: " + testParam);
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
// Log the current timestamp.
System.out.println("Time " + new Date().toString());
// Pass request back down the filter chain
chain.doFilter(request,response);
}
public void destroy( ) {
/* Called before the Filter instance is removed
from service by the web container*/
}
}
以通常的方式编译Simple.java并将类文件放入
现在,尝试通过运行http:// localhost:8080 / Simple来调用任何servlet。您将在网页上看到以下输出。
Hello Servlet
Hello World!
现在,打开servlet控制台。在这里,您将找到init参数testparam的值,当前时间戳以及servlet通知消息。