深入學習SSH架構《二:java編程式配置servlet和使用web.xml部署描述符配置servlet》__Java

來源:互聯網
上載者:User

上一篇文章深入學習了Servlet的工作原理,這一篇我們來實現servlet構建web應用。

下面進入本文: 1.使用web.xml來配置servlet,這是最常用也是最簡單的方式。

<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd" ><web-app>  <display-name>Archetype Created Web Application</display-name>  <servlet>   <servlet-name>Servlet的名字(自訂)</servlet-name>   <servlet-class>Servlet的類名(完整路徑,如com.taobao.Servlet)</servlet-class>      <load-on-startup>1</load-on-startup>     </servlet>  <servlet-mapping>  <servlet-name>Servlet的名字(與上面的一致)</servlet-name>  <url-pattern>映射路徑(如:/login)</url-pattern>  </servlet-mapping></web-app>
 2.使用java編程式來配置啟動servlet。 我們必須實現ServletContextListener這個類,因為這個類會監聽servlet的初始化,因此我們可以在它的contextInitialized方法中註冊servlet(不僅僅是servlet,我們也可以註冊監聽器,和過濾器)。
package indi.jack.chapter1.ServletCotext;import javax.servlet.FilterRegistration.Dynamic;import javax.servlet.Servlet;import javax.servlet.ServletContext;import javax.servlet.ServletContextEvent;import javax.servlet.ServletContextListener;import javax.servlet.ServletRegistration;import javax.servlet.annotation.WebListener;/** * <p>Title:ServletStartup</p> * <p>Description:</p> * <p>Company:</p> * @author jackhoo * @date   2017年3月5日 上午10:12:01 */@WebListenerpublic class ServletStartup implements ServletContextListener{@Overridepublic void contextDestroyed(ServletContextEvent arg0) {}@Overridepublic void contextInitialized(ServletContextEvent arg0) {ServletContext context=arg0.getServletContext();ServletRegistration myservlet=context.addServlet("hello", "indi.jack.chapter1.Servlet.HelloServlet");myservlet.addMapping("/hello");System.out.println("手動註冊servlet完成。");}}
3.附上原始碼地址 github項目地址



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.