有谁说了编写Servlet必须继承自HttpServlet类,必须实现doGet()或者doPost() ,难道实现Servlet接口就不行了吗?
其实编写Servlet主要有三种方法,一是实现Servlet接口,二是继承抽象类GenericServlet,三是继承HttpServlet类。下面分别用这三种方法去实现Servlet:
(一)要从实现Servlet接口来编写Servlet是比较麻烦的,因为必须实现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接口的方法编写Servlet:
- import javax.servlet.*;
- import java.io.*;
- public class TestServlet implements Servlet{
- public void init(ServletConfig config) throws ServletException{
- System.out.println("init");
- }
- public ServletConfig getServletConfig(){
- reture null;
- }
- public void service(ServletRequest req,ServletResponse res)
- throws ServletException,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(ServletRequest req, ServletResponse res),只要实现这个方法就行了,下面看例子:
- import javax.servlet.*;
- import java.io.IOException;
- public TestGenericServlet extends GenericServlet{
- public abstract void service(ServletRequest req,ServletResponse res)
- throws ServletException,IOException{
- PrintWriter out = response.getWriter();
- out.println("Hello World!");
- }
- }
(3)继承HttpServlet类编写Servlet应该是最容易的,而且是最常见的,我们一般要编写Servlet直接继承这个类就行了,重写doGet()或者doPost()方法即可,下面看例子:
- import javax.servlet.http.*;
- import javax.servlet.*;
- import java.io.*;
- public TestHttpServlet extends HttpServlet{
- public void doGet(HttpServletRequest request, HttpServletResponse response)
- throws IOException, ServletException {
- response.setContentType("text/html;charset=gb2312");
- PrintWriter out = response.getWriter();
- out.println("");
- out.println("");
- out.println("
HelloWorld"); - out.println("");
- out.println(" bgcolor=\"white\">");
- out.println("
");- out.println("HelloWorld");
- out.println("");
- }
- public void doPost(HttpServletRequest request, HttpServletResponse response)
- throws IOException, ServletException {
- doGet(request, response);
- }
- }
本文名称:编写Servlet的三种方法
网页网址:http://www.shufengxianlan.com/qtweb/news12/341012.html
网站建设、网络推广公司-创新互联,是专注品牌与效果的网站制作,网络营销seo公司;服务项目有等
声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联