嵌入式tomcat例子


嵌入式tomcat學習筆記

 

 

 

-1 依賴

 

 

jdk用的1.8

<build>

  <plugins>

    <plugin>

      <groupId>org.apache.maven.plugins</groupId>

      <artifactId>maven-compiler-plugin</artifactId>

      <version>3.1</version>

      <configuration>

        <source>1.8</source>

        <target>1.8</target>

      </configuration>

    </plugin>

  </plugins>

</build>

 

-2 相關類講解

 

備注:tomcat8及以上版本使用

這里有個博客,解釋挺詳細的:https://www.cnblogs.com/mahuan2/p/6733566.html

 

Tomcat tomcat = new Tomcat();//創建tomcat實例,用來啟動tomcat

tomcat.setHostname(“localhost”);//設置主機名

tomcat.setPort(8080);//設置端口

tomcat.setBaseDir(“.”);//tomcat存儲自身信息的目錄,比如日志等信息,根目錄

 

String DEFAULT_PROTOCOL = “org.apache.coyote.http11.Http11NioProtocol”;

Connector connector = new Connector(DEFAULT_PROTOCOL);//設置協議,默認就是這個協議connector.setURIEncoding(“UTF-8”);//設置編碼

connector.setPort(Configs.getEmbedServerPort());//設置端口

tomcat.getService().addConnector(connector);

 

org.apache.catalina.Context ctx = tomcat.addContext(“myapp”,null);//網絡訪問路徑

tomcat.addServlet(ctx,”myServlet”,new MessageServlet()); //配置servlet

ctx.addServletMappingDecoded(“/messageServlet”,”myServlet”);//配置servlet映射路徑

 

StandardServer server = (StandardServer)tomcat.getServer();//添加監聽器,不知何用

AprLifecycleListener listener = new AprLifecycleListener();

server.addLifecycleListener(listener);

 

//設置appBase為項目所在目錄

tomcat.getHost().setAppBase(

System.getProperty(“user.dir”)

+

File.separator

+

”.”

);

//設置WEB-INF文件夾所在目錄

//該文件夾下包含web.xml

//當訪問localhost:端口號時,會默認訪問該目錄下的index.html/jsp頁面

tomcat.addWebapp(“”,”webapp”);

 

tomcat.start();//啟動tomcat

tomcat.getServer().await();//維持tomcat服務,否則tomcat一啟動就會關閉

 

 

-3 例子

=1 項目結構

 

 

=2 主類

 

 

 

=3 servlet

 

 

 

訪問Servlet路徑:http://localhost:8080/myapp/myServlet

訪問html路徑:http://localhost:8080(會訪問到resources目錄下的index.html/jsp)

訪問html路徑:http://localhost:8080/test1(會訪問到resources/test1下的index.html/jsp,當然,也可以在test1后面加上頁面名字,比如test.html)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM