116.md 8.1 KB
Newer Older
W
wizardforcel 已提交
1
# Servlet 注解示例
W
init  
wizardforcel 已提交
2 3 4

> 原文: [https://javatutorial.net/servlet-annotation-example](https://javatutorial.net/servlet-annotation-example)

W
wizardforcel 已提交
5
本示例演示了注解的用法,以便配置 Servlet。
W
init  
wizardforcel 已提交
6

W
wizardforcel 已提交
7
在之前的教程中,我们使用部署描述符(`web.xml`文件)来配置我们的 servlet。 从 Servlet 3.0 开始,您可以改用`@WebServlet`注解。 该注解使您可以为 servlet 设置几个属性,例如名称,URL 等。
W
init  
wizardforcel 已提交
8

W
wizardforcel 已提交
9
## 注解与部署描述符
W
init  
wizardforcel 已提交
10

W
wizardforcel 已提交
11
有什么不同? 好吧,很明显,部署描述符是一个单独的文件,您可以在其中以 XML 格式设置配置值,其中注解直接嵌入到源代码中。 如果您希望将代码和配置放在同一位置以提高可读性,请使用注解。 部署描述符恰恰相反 - 您将代码和配置分开。 这样,如果您要更改单个配置值,则无需重新编译整个项目。
W
init  
wizardforcel 已提交
12

W
wizardforcel 已提交
13
对于许多 Java Enterprise 组件,都有两个版本可用 - 注解或描述符。 但其他配置则只能使用注解或通过部署描述符进行配置。 对于 Servlet,可以选择一种或另一种方法。
W
init  
wizardforcel 已提交
14

W
wizardforcel 已提交
15
## `WebServlet`注解属性
W
init  
wizardforcel 已提交
16 17 18

您可以选择几种属性来配置 Servlet。

W
wizardforcel 已提交
19
### 必要
W
init  
wizardforcel 已提交
20

W
wizardforcel 已提交
21
*   `value``urlPatterns` `String[]` – 指定该 servlet 的一个或多个 URL 模式。 可以使用任何一个属性,但不能同时使用。`urlPatterns`的默认值为`{}``value`默认值为`""`
W
init  
wizardforcel 已提交
22

W
wizardforcel 已提交
23
### 可选
W
init  
wizardforcel 已提交
24

W
wizardforcel 已提交
25 26 27 28 29 30 31 32
*   `asyncSupported` `boolean` – 声明 Servlet 是否支持异步操作模式。 默认值为假
*   `name` `String` – Servlet 的名称。 默认值为`""`
*   `description` `String` – Servlet 的描述。 默认值为`""`
*   `displayName` `String` – Servlet 的显示名称。 默认值为`""`
*   `initParams` `WebInitParam[]` – Servlet 的初始化参数。 默认值为`{}`
*   `largeIcon` `String` – Servlet 的大图标。 默认值为`""`
*   `smallIcon` `String` – Servlet 的小图标。 默认值为`""`
*   `loadOnStartup` `int` – Servlet 的启动时加载顺序。 默认值为 -1
W
init  
wizardforcel 已提交
33

W
wizardforcel 已提交
34
## 用于 Servlet 的 POM 文件
W
init  
wizardforcel 已提交
35

W
wizardforcel 已提交
36
我们将使用以下`pom.xml`文件构建本教程后面显示的示例。
W
init  
wizardforcel 已提交
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91

```java
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>net.javatutorial.tutorials</groupId>
	<artifactId>ServletAnnotation</artifactId>
	<version>1</version>
	<packaging>war</packaging>

	<name>ServletAnnotation</name>
	<url>https://javatutorial.net</url>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>

	<dependencies>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>3.1.0</version>
			<scope>provided</scope>
		</dependency>
	</dependencies>

	<build>
		<finalName>servletannotation</finalName>
        <sourceDirectory>src/main/java</sourceDirectory>

        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.3</version>
                <configuration>
                    <warSourceDirectory>src/main/webapp</warSourceDirectory>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

```

W
wizardforcel 已提交
92
## 使用注解时是否需要`web.xml`?
W
init  
wizardforcel 已提交
93

W
wizardforcel 已提交
94
简短答案–不! 如果您选择对所有 Servlet 配置依赖注解,则可以完全删除`web.xml`文件。 但我仍然鼓励您保留该文件,或者至少保留一个如以下示例所示的文件。`Web.xml`用于许多其他配置,因此您迟早需要在项目中使用它。
W
init  
wizardforcel 已提交
95 96 97 98 99 100 101 102 103 104 105 106 107

```java
<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
	version="3.1">

	<display-name>Servlet with Annotations Application</display-name>

</web-app>
```

W
wizardforcel 已提交
108
如果您希望完全跳过`web.xml`,则需要在 Maven 的`pom.xml`中告诉 war 插件停止搜索该文件。 您可以通过将`failOnMissingWebXml`设置为`false`来实现,如下所示:
W
init  
wizardforcel 已提交
109 110 111 112 113 114 115 116 117 118 119 120

```java
<plugin>
	<groupId>org.apache.maven.plugins</groupId>
	<artifactId>maven-war-plugin</artifactId>
	<version>2.3</version>
	<configuration>
		<failOnMissingWebXml>false</failOnMissingWebXml>
	</configuration>
</plugin>
```

W
wizardforcel 已提交
121
## 用一个 URL 模式注解的 Servlet
W
init  
wizardforcel 已提交
122

W
wizardforcel 已提交
123
以下示例仅使用一个属性来注解 servlet 的 URL。 假设您在本地主机上运行应用程序并将其作为`servletannotation.war`部署,则 servlet 的路径将为`http://localhost:8080/servletannotation/hello`
W
init  
wizardforcel 已提交
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150

```java
package net.javatutorial.tutorials;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/hello")
public class ServletWithAnnotations extends HttpServlet {

	private static final long serialVersionUID = -3462096228274971485L;

	@Override
	protected void doGet(HttpServletRequest reqest, HttpServletResponse response) 
			throws ServletException, IOException {
		response.getWriter().println("Hello World!");
	}

}

```

W
wizardforcel 已提交
151
## 具有多个属性的 Servlet 注解
W
init  
wizardforcel 已提交
152

W
wizardforcel 已提交
153
在此示例中,我们将设置 servlet 名称,URL 和`load-0n-startup`加载优先级。 在我们的[简单 Servlet 示例](https://javatutorial.net/java-servlet-example)中,我们在`web.xml`文件中执行了以下操作:
W
init  
wizardforcel 已提交
154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177

```java
<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
	version="3.1">

	<display-name>Servlet with Annotations Application</display-name>

	<servlet>
		<servlet-name>simpleServlet</servlet-name>
		<servlet-class>net.javatutorial.tutorials.ServletWithAnnotations</servlet-class>
		<load-on-startup>1</load-on-startup>
	</servlet>

	<servlet-mapping>
		<servlet-name>simpleServlet</servlet-name>
		<url-pattern>/hello</url-pattern>
	</servlet-mapping>

</web-app>
```

W
wizardforcel 已提交
178
…现在我们将使用`WebServlet`注解实现相同的配置:
W
init  
wizardforcel 已提交
179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205

```java
package net.javatutorial.tutorials;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(name = "simpleServlet", urlPatterns = { "/hello" }, loadOnStartup = 1)
public class ServletWithAnnotations extends HttpServlet {

	private static final long serialVersionUID = -3462096228274971485L;

	@Override
	protected void doGet(HttpServletRequest reqest, HttpServletResponse response) 
			throws ServletException, IOException {
		response.getWriter().println("Hello World!");
	}

}

```

W
wizardforcel 已提交
206
## 具有多个 URL 模式的 Servlet 注解
W
init  
wizardforcel 已提交
207

W
wizardforcel 已提交
208
`urlPatterns`属性接受一个数组作为值,因此您可以设置多个指向同一 servlet 的 URL:
W
init  
wizardforcel 已提交
209 210 211 212 213 214 215 216 217 218 219 220 221 222

```java
@WebServlet(urlPatterns = {"/hello", "/wellcome"})
public class ServletWithAnnotations extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest reqest, HttpServletResponse response) 
			throws ServletException, IOException {
		// ... implementation goes here
	}

}
```

W
wizardforcel 已提交
223
假设您在本地主机上运行应用程序并将其作为`servletannotation.war`部署,则可以访问`http://localhost:8080/servletannotation/hello`以及`http://localhost:8080/wellcome`上的 servlet
W
init  
wizardforcel 已提交
224 225

您可以在我们的 GitHub 存储库[中找到此示例的源代码](https://github.com/JavaTutorialNetwork/Tutorials/tree/master/ServletAnnotation)