創建一個類實現Servlet接口java
package com.cs.helloworld; import java.io.IOException; import javax.servlet.Servlet; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; public class TestServlet implements Servlet { @Override public void destroy() { } @Override public ServletConfig getServletConfig() { return null; } @Override public String getServletInfo() { return null; } @Override public void init(ServletConfig arg0) throws ServletException { } @Override public void service(ServletRequest arg0, ServletResponse arg1) throws ServletException, IOException { } }
在熟悉了Servlet的接口以後咱們會發現每次都實現這個接口,其中都會有一些方法沒有使用到,可是又佔用了地方。因而Servlet的一個抽象子類就出現了ide
|--javax.servlet.GenericServletspa
這個抽象的子類實現了Servlet接口,方法以下:blog
注意在其中的service()方法是abstract的的的繼承
繼承GenericServlet接口
package com.cs.helloworld; import java.io.IOException; import javax.servlet.GenericServlet; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; public class TestGenericServlet extends GenericServlet { private static final long serialVersionUID = -2304229070993476747L; @Override public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException { } }
這樣咱們就只要繼承GenericServlet類,並實現這個類中的service方法就能夠了,這樣一來比起Servlet接口變簡化了不少,也更加有利於人理解。get
可是這還有一點缺陷:這個缺陷就是不能直接經過「request」對http的訪問的,而是要進行一次強轉servlet
進行強轉的request:it
package com.cs.helloworld; import java.io.IOException; import javax.servlet.GenericServlet; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; public class TestGenericServlet extends GenericServlet { private static final long serialVersionUID = -2304229070993476747L; @Override public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException { HttpServletRequest request2 = (HttpServletRequest)request; } }
若是每次都進行一次強轉的話,會顯的狠麻煩,甚至可能出現錯誤。因而繼承GenericServlet的子類HttpServlet出現l,經過這個子類咱們能夠直接使用HttpServlet而沒必要要進行一次強轉。io
使用HttpServlet實現Servlet:
package com.cs.helloworld; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class TestHttpServlet extends HttpServlet { private static final long serialVersionUID = 1L; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.getMethod();resp.getWriter(); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { super.doPost(req, resp); } }
到這一步爲止咱們就認知了Servlet從接口 ---->httpServlet類的實現過程。
從接口到子類的關係圖: