1、我们知道让Servlet成功在服务端运行,就必须实现Servlet接口,而下面的这种方式没有直接实现Servlet接口,而是间接实现了Servlet接口:
import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @WebServlet(name = "MyServlet") public class MyServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setCharacterEncoding("UTF-8");//设置服务器的编码,默认是ISO-8859-1 response.setContentType("text/html; charset = utf-8");//告诉浏览器服务器的编码格式 response.getWriter().write("你好"); } }
关系如下:
public class MyServlet extends HttpServlet//继承
public abstract class HttpServlet extends GenericServlet//继承
public abstract class GenericServlet implements Servlet, ServletConfig, Serializable//实现
2、表单登录与Servlet的联系
(1)get提交与doGet方法:
表单选择get提交:
<body bgcolor="#f5f5dc"> <center> <h3>登录</h3> <form action="http://localhost:8080/MyServlet_war_exploded/abc" method="get"> 用户名:<input type="text" name="myname" size="12"><br> 密 码:<input type="password" name="password" size="6" ><br><br> <input type="reset" value="取消"> <input type="submit" value="登录"> </form> </center> </body>
Servlet方法:
public class MyServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setCharacterEncoding("UTF-8");//设置服务器的编码,默认是ISO-8859-1 response.setContentType("text/html; charset = utf-8");//告诉浏览器服务器的编码格式 response.getWriter().write("我是doPose方法!"); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setCharacterEncoding("UTF-8");//设置服务器的编码,默认是ISO-8859-1 response.setContentType("text/html; charset = utf-8");//告诉浏览器服务器的编码格式 response.getWriter().write("我是doGet方法!"); }
(2)post提交与doPost方法:
将提交方式改为post:
<form action="http://localhost:8080/MyServlet_war_exploded/abc" method="post"> 用户名:<input type="text" name="myname" size="12"><br> 密 码:<input type="password" name="password" size="6" ><br><br> <input type="reset" value="取消"> <input type="submit" value="登录"> </form>
提交后调用doPost方法:
可以看出,表单提交方式中的get与doGet方法对应,而post提交与doPost方法对应。
3、在直接实现Servlet接口时,没有doGet与doPost方法,此时不管是get提交还是post提交,均调用service方法。