1.Servlet基础类,必须继承HttpServlet
1 package com.fan; 2 3 import java.io.IOException; 4 import java.io.PrintWriter; 5 6 import javax.servlet.ServletException; 7 import javax.servlet.http.HttpServlet; 8 import javax.servlet.http.HttpServletRequest; 9 import javax.servlet.http.HttpServletResponse; 10 11 public abstract class ServletBase extends HttpServlet { 12 public HttpServletRequest request = null; 13 public HttpServletResponse response = null; 14 15 public ServletBase() { 16 } 17 18 public void init() throws ServletException { 19 // Put your code here 20 System.out.println("init"); 21 BeginInit(); 22 } 23 24 public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 25 System.out.println("doGet"); 26 this.request = request; 27 this.response = response; 28 BeginGetIn("Get"); 29 } 30 31 public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 32 System.out.println("doPost"); 33 this.request = request; 34 this.response = response; 35 BeginGetIn("Post"); 36 } 37 38 public abstract void BeginGetIn(String Falg); 39 40 public abstract void BeginInit(); 41 42 public void OutPut(String str) { 43 try { 44 if (this.response != null) { 45 PrintWriter out = this.response.getWriter(); 46 out.println(str); 47 out.flush(); 48 out.close(); 49 } 50 } catch (Exception e) { 51 // TODO: handle exception 52 } 53 } 54 }// end
2.子类
1 package com.fan; 2 3 public class HelloWorld extends ServletBase{ 4 5 @Override 6 public void BeginGetIn(String Falg) { 7 // TODO Auto-generated method stub 8 System.out.println(Falg); 9 OutPut(Falg); 10 } 11 12 @Override 13 public void BeginInit() { 14 // TODO Auto-generated method stub 15 System.out.println("init2"); 16 } 17 18 }
3.配置文件web.xml
4.请求地址
http://localhost:8888/项目名/servlet/ServletBase