servlet的入門
1、創(chuàng)建一個(gè)類营袜,實(shí)現(xiàn)Servlet接口
public class MyServlet implements Servlet{}
2、重寫init丑罪、service荚板、destory
public void init(ServletConfig config) throws ServletException {
System.out.println("-------init----------");
}
public void service(ServletRequest req, ServletResponse resp) throws ServletException, IOException {
System.out.println("-------service----------");
}
public void destroy() {
System.out.println("-------destroy--------");
}
3、配置web.xml
1.png
當(dāng)用戶訪問<url-pattern>配置的地址時(shí)吩屹,tomcat會(huì)自動(dòng)找到該地址對應(yīng)的<servlet-name>跪另,然后通過該servlet-name找到對應(yīng)的<servlet-class>
注意:
1. <url-pattern>配置地址時(shí)一定要在前面加/,不然服務(wù)器啟動(dòng)報(bào)錯(cuò)
2. <servlet-class>建議復(fù)制類名煤搜,不要手敲
servlet執(zhí)行過程
1. 用戶第一次訪問servlet時(shí)免绿,會(huì)調(diào)用init()方法,實(shí)例化servlet(所以第一次訪問比較慢擦盾,與jsp一樣)
2. 然后調(diào)用service()方法嘲驾,處理用戶請求與響應(yīng)
3. 用戶第二次方法就不再調(diào)用init()方法了淌哟,直接調(diào)用service()
4. 當(dāng)tomcat容器摧毀時(shí),會(huì)調(diào)用destory()方法
servlet的另外兩種使用方法
- 繼承GenericServlet類辽故,重寫service()
public class YourServlet extends GenericServlet{
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
}
}
- 繼承HttpServlet類徒仓,重寫doGet()和doPost()
public class OurServlet extends HttpServlet {
// 處理get請求
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
}
// 處理post請求
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);// post請求到get請求中處理
}
}
servlet映射的另外一種配置方式:java注解
@WebServlet("/our") //里面的參數(shù)時(shí)servlet的訪問路徑
public class OurServlet extends HttpServlet {}
servlet三大域?qū)ο?/h3>
request ---> HttpServletRequest
session ----> HttpSession
application ----> ServletContext
pageContext
config ---> ServletConfig