新建目錄框架
- 在tomcat的主目錄下的webapp下建立自己的項(xiàng)目文件夾,如servlet20180420
- 進(jìn)入新建的文件夾,建立一個(gè)WEB-INF文件夾
- 進(jìn)入WEB-INF,建立一個(gè)classes文件夾,用于存放java類(lèi)和編譯后的class文件;建立一個(gè)lib文件夾,用于存放庫(kù)文件
- 下面開(kāi)始編寫(xiě)自己的servlet類(lèi),源代碼放在classes文件夾下,最好建一個(gè)文件夾當(dāng)做java包,在包里寫(xiě)java代碼,如com。
- 寫(xiě)完以后進(jìn)入com文件夾,用javac編譯java類(lèi),如:
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代碼相同的位置,會(huì)出現(xiàn)對(duì)應(yīng)的.class文件。
- 此時(shí)還需要看,如果在servlet類(lèi)上面加了注解:
@WebServlet(name = "Hello", urlPatterns = { "/lzs" })
,那么就可以直接啟動(dòng)Tomcat。按照http://localhost:8080/servlet_20180420/lzs
的URL地址去訪問(wèn),其中,servletXXX是webapp下的文件夾名稱(chēng),等同于項(xiàng)目名,lzs是在servlet上加的映射地址。
- 如果不用注解的方式映射,那么就用配置描述文件web.xml,這個(gè)文件直接放在WEB-INF下。其中,web.xml的最簡(jiǎn)配置如下:
<?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的路徑,包名+類(lèi)名 注意類(lèi)名后不能加上java-->
<servlet-class>com.Hello</servlet-class>
</servlet>
<servlet-mapping>
<!--mapping 自然就是映射了 于是乎 這個(gè)同上,一致-->
<servlet-name>hello_servlet</servlet-name>
<!--這是瀏覽器中輸入的訪問(wèn)該servlet的url 任意的-->
<url-pattern>/lzs</url-pattern>
</servlet-mapping>
</web-app>