servlet有三種實現方式:
1.實現servlet接口
2.繼承GenericServlet
3.通過繼承HttpServlet開發servlet
第三種:
1 import java.io.*; 2 3 import javax.servlet.ServletException; 4 import javax.servlet.http.*; 5 6 7 public class hellohttp extends HttpServlet { 8 9 //處理get請求 10 //req用於獲取客戶端(瀏覽器)的信息 11 //res用於向客戶端(瀏覽器)返回信息 12 public void doGet(HttpServletRequest req, HttpServletResponse res) 13 throws ServletException, IOException { 14 15 //業務邏輯 16 try{ 17 PrintWriter pw=res.getWriter(); 18 pw.println("hello,http"); 19 }catch(Exception e){ 20 e.printStackTrace(); 21 } 22 } 23 //處理post請求 24 //req用於獲取客戶端(瀏覽器)的信息 25 //res用於向客戶端(瀏覽器)返回信息 26 public void doPost(HttpServletRequest req,HttpServletResponse res) 27 throws ServletException,IOException 28 { 29 //合二為一,業務邏輯處理方式都一樣 30 this.doGet(req, res); 31 } 32 33 public void init() throws ServletException{ 34 // Put your code here 35 } 36 37 public void destroy() { 38 super.destroy(); // Just puts "destroy" string in log 39 // Put your code here 40 } 41 }