JAVA中级(三)servlet(3)之HttpServlet基本介绍和使用

HttpServlet是什么?

HttpServlet是一个类,它继承了GenericServlet,GenericServlet实现了Servlet.–>因此HttpServlet也能实现Servlet的功能.
HttpServlet的作用比Servlet更加强大,它能够更快速的处理Http请求,能够更快的根据请求方式(Get,Post)来处理Http请求.继承HttpServlet后不用重写Service方法,也不用去实现init等方法。这些都在HttpServlet和GenericServlet有了默认实现.HttpServlet是针对处理Http请求而设计的一个类

1,HttpServlet怎么用?
(1),创建一个类继承HttpServlet,并重写它的doGet和doPost方法

public class ServletDemo extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("执行了post方法");
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("执行了get方法");
    }
}

使用post请求时就会执行doPost方法,Get请求时会执行doGet方法.但是如果想让Get和Post请求都执行同一个方法,就类似这么写

 @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("执行了post方法");
        doGet(request,response);//post请求也转移到doGet方法中
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("执行了get方法");
    }

(2)启动Tomcat,
Get请求:
在网址输入对应的Servlet就是Get请求
我的是http://localhost:8017/qjq/ServletDemo
结果如下:
在这里插入图片描述
Post请求:
一般web项目都会自动创建一个Index.jsp,在index.jsp中创建一个form表单并制定method为post

 <body>
 <!--action是你的servlet访问路径-->
    <form method="post" action="${pageContext.request.contextPath}/ServletDemo">
      <input type="submit" value="post请求">
    </form>
  </body>

然后启动tomcat在网址输入
http://localhost:端口号/项目名称/
我的是http://localhost:8017/qjq/ 来访问这个index.jsp后
会出现以下信息,点击post请求按钮发送post请求,
在这里插入图片描述
结果输出:
在这里插入图片描述
这样就处理了post请求并执行了dopost()方法。
这样HttpServlet的基本用法就介绍完了。

为什么Http请求使用HttpServlet而不是使用Servlet处理?

在日常开发中,我们处理Http请求使用HttpServlet而不是Servlet.
同样能处理Http请求为什么不用Servlet?
1,Servlet要强制实现5个方法。HttpServlet不用,它有了默认实现,它只要自己去重写doGet和doPost方法,编写上更方便
2,HttpServlet里面有HttpServletRequest和HttpServletResponse.
HttpServletRequest有几个针对Http的方法getHeader(),getSession()
这些方法是我们经常使用的。而Servlet里的ServletRequest没有这些方法.

总结:
1,HttpServlet是什么?
一个专门处理Http请求的一个类.
2,HttpServlet怎么用?
(1)创建一个类继承HttpServlet,并重写doGet和doPost方法
(2)启动tomcat在浏览器输入网址则默认Get方法请求这样就会执行doGet方法。使用表单提交请求,手动指定Post方法则会发起Post请求并执行doPost()方法

  • 5
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值