建立一个类实现Servlet接口
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的一个抽象子类就出现了
|--javax.servlet.GenericServlet
这个抽象的子类实现了Servlet接口,方法如下:
注意在其中的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接口变简化了很多,也更加有利于人理解。
但是这还有一点缺陷:这个缺陷就是不能直接通过“request”对http的访问的,而是要进行一次强转
进行强转的request:
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而不必要进行一次强转。
使用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类的实现过程。
从接口到子类的关系图: