《JAVA资格认证-纠正一些关于Servlet的误解.docx》由会员分享,可在线阅读,更多相关《JAVA资格认证-纠正一些关于Servlet的误解.docx(5页珍藏版)》请在金锄头文库上搜索。
1、 JAVA资格认证:纠正一些关于Servlet的误解Servlet三个要素:1.必需继承自HttpServlet2.必需实现doGet()或者doPost()3.必需在web.xml中配置Servlet有谁说了编写一个Servlet必需继承自HttpServlet类,必需实现doGet()或者doPost() ,莫非实现Servlet接口就不行了吗?其实编写一个Servlet主要有三种方法,一是实现Servlet接口,二是继承抽象类GenericServlet,三是继承HttpServlet类。下面分别用这三种方法去实现Servlet:(一)要从实现Servlet接口来编写一个Servlet是
2、比拟麻烦的,由于必需实现Servlet接口中的全部方法,Servlet接口主要定义了五个方法,它们分别为:(1)void init(ServletConfig config) throws ServletException(2)ServletConfig getServletConfig()(3)void service(ServletRequest req,ervletResponse res) throws ServletException,IOException(4)String getServletInfo()(5)void destroy()下面用实现Servlet接口的方法编写一个
3、Servlet:import javax.servlet.*;import java.io.*;public class TestServlet implements Servletpublic void init(ServletConfig config) throws ServletExceptionSystem.out.println(“init“);public ServletConfig getServletConfig()reture null;public void service(ServletRequest req,ServletResponse res)throws Ser
4、vletException,IOException/这里可以实现恳求后要做的内容PrintWriter out = response.getWriter();out.println(“Hello World!“);public String getServletInfo()return null;public void destroy()System.out.println(“destory“);(二)继承抽象类GenericServlet编写一个Serlvet,这个相比照实现Servlet接口要简单一点,GenericServlet类中只有一个抽象方法,即service(ServletReq
5、uest req, ServletResponse res),只要实现这个方法就行了,下面看例子:import javax.servlet.*;import java.io.IOException;public TestGenericServlet extends GenericServletpublic abstract void service(ServletRequest req,ServletResponse res)throws ServletException,IOExceptionPrintWriter out = response.getWriter();out.println
6、(“Hello World!“);(3)继承HttpServlet类编写Servlet应当是最简单的,而且是最常见的,我们一般要编写Servlet直接继承这个类就行了,重写doGet()或者doPost()方法即可,下面看例子:import javax.servlet.http.*;import javax.servlet.*;import java.io.*;public TestHttpServlet extends HttpServletpublic void doGet(HttpServletRequest request, HttpServletResponse response)t
7、hrows IOException, ServletException response.setContentType(“text/html;charset=gb2312“);PrintWriter out = response.getWriter();out.println(“);out.println(“);out.println(“HelloWorld“);out.println(“);out.println(“);out.println(“);out.println(“HelloWorld“);out.println(“);public void doPost(HttpServletRequest request, HttpServletResponse response)throws IOException, ServletException doGet(request, response);