Servlet----------通过 HttpServlet 开发Servlet
通过继承HttpServlet抽象类,功能更强大。
通过HttpServlet方法开发Servlet需要重写doGet和doPost方法。这是目前用的最多的一种方法。
如: class MyHttpServlet extends HttpServlet
1 package cn.servlet; 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 class MyHttpServlet extends HttpServlet { 12 //在HttpServlet中,设计者对post提交和get提交分别处理 13 //<form action="提交给?" method="post|get">,默认是get提交 14 //其实,doGet和doPost最终也去调用了Servlet接口中的service()方法 15 public void doGet(HttpServletRequest request, HttpServletResponse response) 16 throws ServletException, IOException { 17 18 PrintWriter out = response.getWriter(); 19 out.print("<h1>I am doGet()..................</h1>"); 20 } 21 22 23 public void doPost(HttpServletRequest request, HttpServletResponse response) 24 throws ServletException, IOException { 25 PrintWriter out = response.getWriter(); 26 out.print("<h1>I am doPost().................</h1>"); 27 } 28 }
部署:
<serlvet> <servlet-name>MyHttpServlet</servlet-name> <servlet-class>cn.servlet.MyHttpServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>MyHttpServlet</servlet-name> <url-pattern>/servlet/MyHttpServlet</url-pattern> </servlet-mapping>
由结果可知,默认调用的是doGet方法,,,,而Get方法在表单时会在地址栏中显示用户名和密码,而Post方法不会。