servlet和http请求协议

Servlet的体系结构

 

HttpServlet --抽象类

        |  继承

GenericServlet --抽象类

        |  实现

Servlet --接口

 

GenericServlet :将Servlet接口中的其他方法变成了默认空实现,只有将service()方法作为抽象

  如果将来定义servlet类时不用实现Servlet接口而是去继承GenericServlet类时,不用重写其他的方法,只用重写service()方法即可

  ServletDemo2(继承GenericServlet类) :

package wtf.servlet;

import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
import java.io.IOException;

@WebServlet("/demo2")
public class ServletDemo2 extends GenericServlet {
    @Override
    public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
        System.out.println("GenericServlet");
    }
}

 

HttpServlet:对http协议的一种封装,简化操作

  如果将来定义servlet类时不用实现Servlet接口而是去继承HttpServlet类时,不用重写其他的方法,而只需根据请求类型来重写doGet或者是doPost方法即可

  HttpServlet图解:

servlet和http请求协议

 

 

   ServletDemo3(继承HttpServlet类) :

package wtf.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("/demo3")
public class ServletDemo3 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("use get");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("use post");
    }
}

  login.html(分别使用doGet和doPost方法):

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>登录</title>
</head>
<body>
<!--这里method如果是get,控制台会输出的是use get,method如果是post,控制台会输出的是use post-->
    <form action="/demo3" method="post">
        <input name="username">
        <input type="submit" value="提交">
    </form>
</body>
</html>

servlet和http请求协议

 

上一篇:NHibernate从入门到精通系列(3)——第一个NHibernate应用程序


下一篇:The superclass "javax.servlet.http.HttpServlet" was not found on the Java Build Path