1. 程式人生 > >Tomcat部署之URL對映

Tomcat部署之URL對映

參考Tomcat官方文件Tomcat Document.

     通常我們在手動部署專案時,是將[projectName].war直接放到[tomcat目錄]/webapps目錄下,那麼你的專案預設的URL是:http://localhost:8080/[projectName]. 有時候這個路徑並不是你想要的,那麼該如何修改預設的URL呢?

     在[tomcat目錄]/webapps目錄下,有一個ROOT目錄,這個就是Tomcat預設的專案,其對映路徑是http://localhost:8080.下面我們來簡單介紹修改URL的三種方法。

     第一種:刪除ROOT目錄

     在你刪除ROOT目錄前,最好先做一個備份。首先我們需要停止執行tomcat,然後刪除ROOT目錄,將[projectName].war重新命名為ROOT.war(必須大寫)。然後將你的ROOT.war直接放到[tomcat目錄]/webapps目錄下。重啟tomcat, 那麼你的專案就會成為Tomcat預設的專案啦,其對映路徑為tomcat根目錄,即:http://localhost:8080。

    第二種:ContextName.xml(推薦使用)

    首先將你的war包從[tomcat目錄]/webapps目錄下移出來,放入電腦中除tomcat目錄]/webapps的任意目錄(這是為了避免重複部署)。在[tomcat目錄]/conf/[engine name]/[host name]目錄下新建一個[ContexName].xml。通常[tomcat目錄]/conf目錄下有預設的contex.xml。將其複製到前面所述的目錄重新命名,然後稍微修改即可。Tomcat預設的engine是Catalina,預設的host是localhost,可以通過server.xml中修改與檢視。因此[ContexName].xml需要放入的路徑是tomcat目錄]/conf/Catalina/localhost/[ContexName].xml。

     值得注意的是[ContexName].xml中必須有 docBase屬性,該屬性指向你war包在你電腦中的存放路徑。

<?xml version="1.0" encoding="UTF-8"?>
<!--
  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.
-->
<!-- The contents of this file will be loaded for each web application -->




<Context docBase ="/home/***/apache-tomcat-9.0.6/emall.war"  debug ="0"  privileged ="true"  reloadable ="false">


   
</Context>

    不需要寫path元素是因為該方式下預設path為ContextName. 例如你的xml為emall.xml,那麼對映路徑為http://localhost:8080/emall。如果你需要對映為tomcat根目錄,即http://localhost:8080,那麼你只需要將其命名為ROOT.xml,同時需要刪除 [tomcat目錄]/webapps目錄下的ROOT目錄 ,然後重啟tomcat即可使用。  

      第三種:修改server.xml(不推薦)

        第一步:在修改server.xml前先備份。同樣地,你需要將war包從[tomcat目錄]/webapps目錄下移出來。

        第二步:修改server.xml。將host的autoDeploy與deployOnStartup設定為false.

        第三步: 在<host></host>中間新增Context, 指定path以及docBase.

<Context  path ="/"  reloadable ="false"  docBase ="/home/***/apache-tomcat-9.0.6/emall.war"  />

圖中對映路徑是根/路徑,如果想要對映為根路徑還需要刪除 [tomcat目錄]/webapps目錄下的ROOT目錄 ,然後重啟tomcat即可使用。