Servlet 初始化

本文最后更新于:2024年3月18日 凌晨

Servlet 初始化

pom.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<encoding>UTF-8</encoding>
<java.version>1.8</java.version>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<build>
<plugins>
<!-- 配置Tomcat插件 -->
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
<configuration>
<path>/</path>
<port>8081</port>
<server>tomcat7</server>
</configuration>
</plugin>
</plugins>
</build>

web.xml

  • 默认情况下,Servlet 应用程序位于路径<Tomcat-installation-directory>/webapps/ROOT下,且类文件放在 <Tomcat-installation-directory>/webapps/ROOT/WEB-INF/classes 中。
  • 如果您有一个完全合格的类名称 com.myorg.MyServlet,那么这个 Servlet 类必须位于WEB-INF/classes/com/myorg/MyServlet.class中。
  • 现在,让我们把 HelloWorld.class 复制到<Tomcat-installation-directory>/webapps/ROOT/WEB-INF/classes中,并在位于 <Tomcat-installation-directory>/webapps/ROOT/WEB-INF/web.xml 文件中创建以下条目:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<?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_4_0.xsd"
version="4.0">

<servlet>
<servlet-name>HelloWorld</servlet-name>
<servlet-class>HelloWorld</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>HelloWorld</servlet-name>
<url-pattern>/HelloWorld</url-pattern>
</servlet-mapping>

<!--Session过期时间-->
<session-config>
<session-timeout>15</session-timeout>
</session-config>

</web-app>
  • 上面的条目要被创建在web.xml文件中的<web-app>...</web-app>标签内,在该文件中可能已经有各种可用的条目,但不要在意。
  • 到这里,您基本上已经完成了,现在让我们使用<Tomcat-installation-directory>\bin\startup.bat(在 Windows 上) <Tomcat-installation-directory>/bin/startup.sh(在 Linux/Solaris 等上)启动 tomcat 服务器,最后在浏览器的地址栏中输入 **http://localhost:8080/HelloWorld**,如果一切顺利,您会看到下面的结果:


本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!