javaWeb开发_Servlet02_Servlet、GenericServlet以及HttpServlet之间的关系

1、在程序员自己编写servlet时一定要实现servlet接口,不成所编写的Java类不能称之为Servlet程序。

2、实现了Servlet接口还要实现相关的方法,包括以下方法:

	
    //只被调用一次,在当前servlet所在的Web应用被卸载前调用,用于释放当前servlet所占的内存资源。
    public void destroy() {
		
	}
    
    //通过该方法能够得到ServletConfig对象,这个对象由tomcat生成,在init()方法中传进来
	@Override
	public ServletConfig getServletConfig() {
		return null;
	}

	@Override
	public String getServletInfo() {
		return null;
	}
    
    //只被调用一次,在创建实例后立即被调用,用于初始化当前的servlet。
    //传进来ServletConfig对象
	@Override
	public void init(ServletConfig arg0) throws ServletException {
		
	}

	//Servlet的service()方法用于应答请求:因为每次请求都会调用service()方法
	@Override
	public void service(ServletRequest request, ServletResponse response)
			throws ServletException, IOException {
		System.out.println(request instanceof ServletRequest);
	}

3、由图上该程序,我们能够清楚地知道,ServletConfig对象的由来。那么如何获取ServletContext对象呢?方法是:

//获取ServletConfig对象
ServletContext servletContext = servletConfig.getServletContext();

4、当我们每次想要编写Servlet程序,都需要重写上图中的代码,这给我们的工作量增添了极大的负担。为此,我们可以使用继承了Servlet接口的两个子类,分别是GenericServlet和HttpServlet两个抽象类。

5、GenericServlet抽象类如下所示

GenericServlet makes writing servlets easier. It provides simple versions of the lifecycle methods init and destroy and of the methods in the ServletConfig interface. GenericServlet also implements the log method, declared in the ServletContext interface。

getInitParameter(java.lang.String name)
//Returns a String containing the value of the named initialization parameter, 
//or null if the parameter does not exist.直接获得初始化参数对应的值

getInitParameterNames()
//Returns the names of the servlet's initialization parameters as an Enumeration of String objects, 
//or an empty Enumeration if the servlet has no initialization parameters.直接获得初始化参数对应的String[]

getServletConfig()
//Returns this servlet's ServletConfig object.直接获得ServletConfig对象

getServletContext()
//Returns a reference to the ServletContext in which this servlet is running.直接获得ServletContext对象

其中抽象方法只有Service方法

6、HttpServlet抽象类继承自GenericServlet

主要方法有:

这让编写Servlet变得更加的简单了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值