新建目錄框架
- 在tomcat的主目錄下的webapp下建立自己的項目文件夾,如servlet20180420
- 進入新建的文件夾,建立一個WEB-INF文件夾
- 進入WEB-INF,建立一個classes文件夾,用于存放java類和編譯后的class文件;建立一個lib文件夾,用于存放庫文件
- 下面開始編寫自己的servlet類,源代碼放在classes文件夾下,最好建一個文件夾當做java包,在包里寫java代碼,如com。
- 寫完以后進入com文件夾,用javac編譯java類,如:
PS C:\Development\apache-tomcat-9.0.0.M21\webapps\servlet_20180420\WEB-INF\classes\com> javac -classpath C:\Development\apache-tomcat-9.0.0.M21\lib\servlet-api.jar Hello.java
- 編譯完成后,與java代碼相同的位置,會出現對應的.class文件。
- 此時還需要看,如果在servlet類上面加了注解:
@WebServlet(name = "Hello", urlPatterns = { "/lzs" })
,那么就可以直接啟動Tomcat。按照http://localhost:8080/servlet_20180420/lzs
的URL地址去訪問,其中,servletXXX是webapp下的文件夾名稱,等同于項目名,lzs是在servlet上加的映射地址。
- 如果不用注解的方式映射,那么就用配置描述文件web.xml,這個文件直接放在WEB-INF下。其中,web.xml的最簡配置如下:
<?xml version="1.0" encoding="UTF8"?>
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<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"
metadata-complete="true">
<servlet>
<!--給你的servlet起名字,任意的-->
<servlet-name>hello_servlet</servlet-name>
<!--指明servlet的路徑,包名+類名 注意類名后不能加上java-->
<servlet-class>com.Hello</servlet-class>
</servlet>
<servlet-mapping>
<!--mapping 自然就是映射了 于是乎 這個同上,一致-->
<servlet-name>hello_servlet</servlet-name>
<!--這是瀏覽器中輸入的訪問該servlet的url 任意的-->
<url-pattern>/lzs</url-pattern>
</servlet-mapping>
</web-app>