Java--Servlet到Tomcat的最簡配置步驟

新建目錄框架

  1. 在tomcat的主目錄下的webapp下建立自己的項目文件夾,如servlet20180420
  2. 進入新建的文件夾,建立一個WEB-INF文件夾
  3. 進入WEB-INF,建立一個classes文件夾,用于存放java類和編譯后的class文件;建立一個lib文件夾,用于存放庫文件
  4. 下面開始編寫自己的servlet類,源代碼放在classes文件夾下,最好建一個文件夾當做java包,在包里寫java代碼,如com。
  5. 寫完以后進入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
  6. 編譯完成后,與java代碼相同的位置,會出現對應的.class文件。
  7. 此時還需要看,如果在servlet類上面加了注解:@WebServlet(name = "Hello", urlPatterns = { "/lzs" }),那么就可以直接啟動Tomcat。按照http://localhost:8080/servlet_20180420/lzs的URL地址去訪問,其中,servletXXX是webapp下的文件夾名稱,等同于項目名,lzs是在servlet上加的映射地址。
  8. 如果不用注解的方式映射,那么就用配置描述文件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>

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容