标签:
继承 Servlet 接口,实现Servlet 接口的 所有抽象方法!
实现类代码
package xw.servlet; import java.io.IOException; import java.util.Enumeration; import javax.servlet.Servlet; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; public class ServletInterfaceDemo implements Servlet { //继承 Servlet 接口,实现接口中所有的抽象方法 总共五个, 如果不实现,那么该类就要定义为抽象类 public void destroy() { System.out.println("destory()..."); } /* * 可以用来获取Servlet的配置信息 */ public ServletConfig getServletConfig() { System.out.println("getServletConfig()..."); return null; } /* * 获取Servlet的信息 */ public String getServletInfo() { System.out.println("getServletInfo()..."); return "我是一个快乐的Servlet"; } /* * 它是生命周期方法 * 它会在Servlet对象创建之后马上执行,并只执行一次!(出生之后) * */ public void init(ServletConfig servletConfig) throws ServletException { System.out.println("init()..."); /* * 获取初始化参数 */ System.out.println(servletConfig.getInitParameter("p1")); System.out.println(servletConfig.getInitParameter("p2")); /* * 获取所有初始化参数的名称 */ Enumeration e = servletConfig.getInitParameterNames(); while(e.hasMoreElements()) { System.out.println(e.nextElement()); } } /* * 它是生命周期方法 * 它会被调用多次!!! * 每次处理请求都是在调用这个方法! */ public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException { System.out.println("service()..."); } }
web.xml 配置文件
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <servlet> <description>This is the description of my J2EE component</description> <display-name>This is the display name of my J2EE component</display-name> <servlet-name>servletInterfaceDemo</servlet-name> <servlet-class>xw.servlet.ServletInterfaceDemo</servlet-class> <init-param> <param-name>p1</param-name> <param-value>v1</param-value> </init-param> <init-param> <param-name>p2</param-name> <param-value>v2</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>servletInterfaceDemo</servlet-name> <url-pattern>/servlet/ServletInterfaceDemo</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
访问路径:http://localhost:8080/JavaWebTest/servlet/ServletInterfaceDemo
显示效果:
标签:
原文地址:http://www.cnblogs.com/weiqinshian/p/4921374.html